/r/PowerShell
PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models. PowerShell includes a command-line shell, object-oriented scripting language, and a set of tools for executing scripts/cmdlets and managing modules.
Windows PowerShell (POSH) is a command-line shell and associated scripting language created by Microsoft. Offering full access to COM, WMI and .NET, POSH is a full-featured task automation framework for distributed Microsoft platforms and solutions.
SUBREDDIT FILTERS
/r/PowerShell
I have a lot of files that begin with a numerical prefix (for example 3029110-FileName.png). The numerical prefix varies, but within certain specific patterns. The group I am working on now all begin '3029...' I need to remove the '3029' from the filename but retain the rest. How can I use PowerShell to do that, please?
I am currently trying to improve the logging in some of my larger and more important scripts I have running. I just made a small custom logging class, and I am now at a point where I try to decide which is the best format for the log file content.
I started with plain text, like:
2024-12-20T16:21:44 - INFORMATION - Something happend
2024-12-20T17:05:02 - ERROR - it happend again
Then I switched to CSV for better machine-readability - three columns, Timestamp, Level, Message.
Now after some reading I am thinking about using JSON - I just started using this for config files and realy start to like it. My problem with a JSON file: during a running script, I would like to create multiple log entries. With text or csv this is a simple "-append" in the command. The problem with JSON is that as soon as there is more than on JSON object in a file, when I read it with Get-Content and try to convert it with ConvertFrom-JSON, I cannot read it. The reason obviously is that if I have more than one object, I have to enclose them all between square brackets. So a simple $logObject | ConvertTo-JSON|Out-File -Append
will not work anymore. At the first run I would have to initialize the file with the brackets, and every time I want to add, I first have to Get-Content, remove the trailing bracket, add my log object and add the bracket.
I thought about adding all my log objects into one large object and writing it at the end of the script. Like this I would only have to do this read and write once. But I don't like the idea that if something in the script fails misserably, I would not have any line of the run in the log.
Another way would be to read the content of the file, convert it to a Json Object, add my object, and export it again. But again - read and write the whole file at every log event.
While writing I think my best option would be to just use the "-append" and live with the missing brackets - and if I have to import it machine-readable, I would have to add the brackets after the Get-Content
manually at the beginning and the end. Not nice, but I think it would be the best solution if I wanted to start using JSON logging. I also could write a small LogParsing class for my custom logs, or add the parsing to my initial log class... But it still is an ugly way...
Do you guys have any better idea how to use JSON logging? Or should I just keep using plain text? I don't have so much logging to parse that it wouldn't be possible with a plain text log file, I just wanted to explore my options...
Is this module available for the new ARM processors by chance? Or will it be available at some point?
Hi,
On our DCs I archive the security logs instead of overwriting. My question is :Do you have a powershell script that copies the archive logs to another location and zips them?
Thanks,
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 commandlets:
$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"
}
I know it's been asked, and I did a google search, but the newest was over a year ago, and wasn't instructor led.
I learn best by working with people who know, and self paced learning I just zone out on.
I use YT as reference, not to fully learn.
For me to easily level up, I'm going to need instructor led. Also, my company will likely reimburse me.
So I'm open to suggestions for classes where a live human will work with me in real time.
Hi,
I am currently struggling to get remote PS to work from my Windows 2022 domain joined server to a Windows 11 Entra joined machine. From my Windows 11 to another Windows 11 machine (on the corporate network) it works without issues.
I have added my Entra account to the Administrators group on the machine, the firewall rules are enabled, PS Remoting has been enabled. I only get it to work if I create a local account on the Windows 11 machine and add that to the Administrators group.
Does anyone has an idea to get this to work without creating a local account?
Yesterday, during an open school day, a father and his son walked into the IT classroom and asked some questions about the curriculum. As a teacher, I explained that it included PowerShell. The father almost jumped scared and said he works as a system administrator in Office365 at an IT company where PowerShell wasn’t considered useful enough. He added that he preferred point-and-click tasks and found PowerShell too hard to learn. So I could have explained the benefits of PowerShell and what you can achieve with it, but he had already made up his mind "it’s hard to learn and not useful". How would you have responded to this?
Any recommendations on powershell courses to help me become more advanced.
I am setting up a new PC and wanted to setup a Credman vault with the SecretManagement and SecretStore modules but for the life of me I can't get the syntax correct. I keep getting the error that the specified module "microsoft.powershell.something.something" is not correct. It doesn't help that every time I try to find an example of this, the stupid AI keeps showing me a different spelling for the module name. UGH. Can someone toss me a bone here?
Register-SecretVault -Name "fooo" -ModuleName "Microsoft.PowerShell.Credman"
Register-SecretVault: Could not load and retrieve module information for module: Microsoft.PowerShell.Credman with error : The specified module 'Microsoft.PowerShell.Credman' was not loaded because no valid module file was found in any module directory.
I was asked to schedule weekly reboots for a clients systems and have it prompt the users prior to initiating the reboot. I've tried a few different functions I've found on Reddit and searching the web, but nothing has really worked properly. I figured it was time to just make a post and see if I get lucky.
I need to schedule a task to run as system based on what I'm seeing with trying to schedule through my RMM. I would like to to prompt to notify the user the computer will reboot in 15 minutes or to reboot now. And either reboot the computer immediately if they click reboot now or reboot the computer after 15 minutes if any other action is taken. If anyone has any advice I'd appreciate it greatly!
When I make a constructor with a similar matching name to a method, calling the method in the class seems to be calling the class contructor instead.
Why does this happen?
Example below
class Person {
[string]$eye_color
[string]$name
Person([string]$name) {
$this.name = $name
$this.eye_color = $this.get_eye_color()
}
[string]get_eye_color() {
return "blue"
}
}
$mike = [Person]::new("mike")
write-host $mike.name
write-host $mike.eye_color
$mike.get_eye_color()
the first write host diplays "mike" in the terminal the second and third displays nothing despite being a return value in the method.
If I change either the constructor name "eye_color" or method name "get_eye_color" to something none matching then it works as intended
I recently started in a new environment and there's a lot of cleanup to be done here. I've been trying to set up a script to mirror users based of a template user but I keep running into the error below when I run it and can't figure out where the issue really is. Any clarity would be greatly appreciated as poweshell is not my strong suit.
There is the error message:
An error occurred while sending the request. At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.6.0\netFramework\ExchangeOnlineManagement.psm1:762 char:21 + throw $_.Exception.InnerException; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], HttpRequestException + FullyQualifiedErrorId : An error occurred while sending the request.
And the code is:
I have a bunch of files name in a folder, that start with the following string in their name Lesson <three sequencial digits>...
. I would like to get the files sorted from "lesson 01..." to "lesson 154", get-childitem
by default is supposed to do this sort of thing but sometimes it has a brain fart or something, here is what it gives me:
c:\temp\File Projects.txt
c:\temp\Lesson 01.txt
c:\temp\Lesson 02.txt
c:\temp\Lesson 03 ConceptAnd Reference.txt
c:\temp\Lesson 04 Zbrush blockout 01.txt
c:\temp\Lesson 05 Zbrush blockout 02.txt
c:\temp\Lesson 06 Zbrush blockout 03.txt
c:\temp\Lesson 07 Zbrush blockout 04.txt
c:\temp\Lesson 08 Zbrush blockout 05.txt
c:\temp\Lesson 09 Zbrush blockout 06.txt
c:\temp\Lesson 10 Zbrush blockout 07.txt
c:\temp\Lesson 100 Hair Modeling Shading 04.txt #<----- this should be "c:\temp\Lesson 11 Zbrush blockout 08.txt"
c:\temp\Lesson 101 Hair Modeling Shading 05.txt
c:\temp\Lesson 102 Hair Modeling Shading 06.txt
c:\temp\Lesson 103 Hair Modeling Shading 07.txt
c:\temp\Lesson 104 Hair Modeling Shading 08.txt
c:\temp\Lesson 105 Hair Modeling Shading 09.txt
c:\temp\Lesson 106 Hair Modeling Shading 10.txt
c:\temp\Lesson 107 Hair Modeling Shading 11.txt
c:\temp\Lesson 108 Hair Modeling Shading 12.txt
c:\temp\Lesson 109 Hair Modeling Shading 13.txt
c:\temp\Lesson 11 Zbrush blockout 08.txt
c:\temp\Lesson 110 Hair Modeling Shading 14.txt
c:\temp\Lesson 111 Final worlds.txt
c:\temp\Lesson 112 Hammer 01.txt
c:\temp\Lesson 113 Hammer 02.txt
c:\temp\Lesson 114 Hammer 03.txt
...
...
c:\temp\Lesson 154 Hair Modeling Shading 158.txt
Instead of the above incomplete ordering, I would like to get the following:
c:\temp\Lesson 01. Introducion about.txt
c:\temp\Lesson 02. Pipeline.txt
c:\temp\Lesson 03 ConceptAnd Reference.txt
c:\temp\Lesson 04 Zbrush blockout 01.txt
c:\temp\Lesson 05 Zbrush blockout 02.txt
c:\temp\Lesson 06 Zbrush blockout 03.txt
c:\temp\Lesson 07 Zbrush blockout 04.txt
c:\temp\Lesson 08 Zbrush blockout 05.txt
c:\temp\Lesson 09 Zbrush blockout 06.txt
c:\temp\Lesson 10 Zbrush blockout 07.txt
c:\temp\Lesson 11 Zbrush blockout 08.txt
c:\temp\Lesson 12 Zbrush blockout 09.txt
c:\temp\Lesson 13 Retopo High 01.txt
c:\temp\Lesson 14 Retopo High 02.txt
c:\temp\Lesson 15 Retopo High 03.txt
c:\temp\Lesson 16 Retopo High 04.txt
c:\temp\Lesson 17 Highpoly modeling 01.txt
c:\temp\Lesson 18 Highpoly modeling 02.txt
c:\temp\Lesson 19 Highpoly modeling 03.txt
...
...
c:\temp\Lesson 154 Highpoly modeling 03.txt
I tried piping the files to sort-object
but it does not change anything at all, the sorting persists.
am on pwsh 7.4
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
Hello
I have been using ChatGPT/Co-Pilot as I am not all that familiar with Graph queries, I am trying to get this script working but not having much luck. At some point during the query of Group Members, the detailedRoleAssignments becomes a bad object is no longer considered an array, giving me an error stating that the method Op_Addition is not valid. Could anyone try to run it and fix it?
#Several Variables for Script
$WorkingPath = "D:\Scripts\Adhoc"
$Today = (Get-Date -Format "dd/MM/yyyy")
$ScriptDate = (Get-Date -Format "ddMMyyyy")
Import-Module Microsoft.Graph.Identity.DirectoryManagement -ErrorAction SilentlyContinue
Import-Module Microsoft.Graph.Authentication -ErrorAction SilentlyContinue
#Logon to MG Graph
function Logon-MGGraph{
$ClientId = ""
$TenantId = ""
$ClientSecret = ""
$ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $ClientSecretPass
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $ClientSecretCredential
}
Logon-MGGraph
# Fetch all role definitions
$roleDefinitions = Get-MgRoleManagementDirectoryRoleDefinition -All
# Fetch active role assignments
$activeRoleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -All
# Fetch eligible role assignments
$eligibleRoleAssignments = Get-MgRoleManagementDirectoryRoleEligibilityScheduleInstance -All
# Initialize the array explicitly
$detailedRoleAssignments = @()
# Function to process role assignments (active or eligible)
function Process-RoleAssignments {
param (
[array]$roleAssignments,
[string]$assignmentType # "Active" or "Eligible"
)
foreach ($assignment in $roleAssignments) {
try {
# Fetch principal details
$principal = Get-MgDirectoryObject -DirectoryObjectId $assignment.PrincipalId -ErrorAction Stop
} catch {
Write-Warning "Unable to resolve PrincipalId: $($assignment.PrincipalId)"
continue
}
if ($principal.AdditionalProperties["@odata.type"] -eq "#microsoft.graph.group") {
# Handle group assignments
try {
$groupMembers = Get-MgGroupMember -GroupId $assignment.PrincipalId -All
if ($groupMembers) {
$tempArray = @() # Temporary array for group members
foreach ($member in $groupMembers) {
$tempArray += [pscustomobject]@{
RoleName = ($roleDefinitions | Where-Object { $_.Id -eq $assignment.RoleDefinitionId }).DisplayName
PrincipalType = "Group Member"
UPN = $member.AdditionalProperties.userPrincipalName
PrincipalId = $member.Id
AssignedBy = $assignment.AssignedBy
AssignmentDate = $assignment.AssignedDateTime
AssignmentType = $assignmentType
GroupName = $principal.AdditionalProperties.displayName
GroupId = $principal.Id
}
}
# Safely append the group members to the main array
$detailedRoleAssignments += $tempArray
} else {
Write-Warning "No members retrieved for group: $($principal.AdditionalProperties.displayName)"
}
} catch {
Write-Warning "Unable to fetch members of group: $($principal.AdditionalProperties.displayName). Error: $_"
}
} else {
# Handle individual assignments
$upn = if ($principal.AdditionalProperties.ContainsKey("userPrincipalName")) {
$principal.AdditionalProperties.userPrincipalName
} else {
"N/A"
}
# Safely append direct assignments
$detailedRoleAssignments += [pscustomobject]@{
RoleName = ($roleDefinitions | Where-Object { $_.Id -eq $assignment.RoleDefinitionId }).DisplayName
PrincipalType = $principal.AdditionalProperties["@odata.type"] -replace "#microsoft.graph.", ""
UPN = $upn
PrincipalId = $assignment.PrincipalId
AssignedBy = $assignment.AssignedBy
AssignmentDate = $assignment.AssignedDateTime
AssignmentType = $assignmentType
GroupName = "DIRECT"
GroupId = "N/A"
}
}
# Debugging to verify the array type
Write-Host "Type of \$detailedRoleAssignments after assignment: $($detailedRoleAssignments.GetType().Name)"
}
# Ensure $detailedRoleAssignments is still an array
$detailedRoleAssignments = @($detailedRoleAssignments)
}
# Process active and eligible role assignments
Process-RoleAssignments -roleAssignments $activeRoleAssignments -assignmentType "Active"
Process-RoleAssignments -roleAssignments $eligibleRoleAssignments -assignmentType "Eligible"
# Output results to a CSV file
$detailedRoleAssignments | Export-Csv -Path "$Workingpath\RoleAssignmentsWithEligibility.csv" -NoTypeInformation -Encoding UTF8
Write-Output "Role assignments (active and eligible) have been exported to 'RoleAssignmentsWithEligibility.csv'."
Write-Host "Type of \$detailedRoleAssignments $($detailedRoleAssignments.GetType().Name)"
Thanks in advance for any time spent looking.
I have nearly automated everything of my daily work and i need to pass time over christmas....
What should i do? What should i script? What could be a fun challange or even usefull for work?
Thanks in advany for some kind holiday ideas :)
Hello everyone,
I'm trying to silently connect to the Microsoft Graph API, but I keep getting this error when I run my script: Connect-MgGraph : Invalid JWT access token
.
Here is my script:
$tenantId = "XXXXXXXXXXX"
$clientId = "XXXXXXXXXXXXXXXX"
$clientSecret = "XXXXXXXXXXXXXXXXXXX"
$secureClientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($clientId, $secureClientSecret)
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $credential
I've checked the client ID, tenant ID, and client secret, as well as the application's API permissions, but this error persists. I don't know what else to do.
Hey everyone
I’m a network guy who has recently transitioned to Hyper-V maintenance. Only ever done very light and basic scripting with Powershell, bash, etc.
Now I’m finding myself automating a whole bunch of stuff with Powershell, and I love it!
I’m using AI for inspiration, but I’m writing/rewriting most of the code myself, making sure I always understand what’s going on.
I keep learning new concepts, and I think I have a firm grasp of most scripting logic - but I have no idea if I’m only just scratching the surface, or if I’m moving towards ‘Advanced’ status.
Are there any milestones in learning Powershell that might help me get a sense of where I am in the progress?
I’m the only one using Powershell in the department, so I can’t really ask a colleague, haha.
I guess I’m asking to get a sense of my worth, and also to see if I have a bit of an imposter syndrome going on, since I’m never sure if my code is good enough.
Sorry for the rant, hope to hear some inputs!
Let's say, I have a standalone file, where $file is its full name and $name is its name.
I need to ReadAllBytes from the file and add the bytes to the registry (to feed it to the target application).
I do it as follows:
$bytes = [byte[]][IO.File]::ReadAllBytes($file)
if ($bytes) {Set-ItemProperty -path $registryPath -name $keyName -value $bytes -type Binary -force}
And it works like a charm.
However, if that same file is archived (within $archive) I cannot figure out how to get the identical result from it.
I'm trying it like that:
$zip = [IO.Compression.ZipFile]::OpenRead($archive)
$stream = ($zip.Entries | Where {$_.Name -eq $name}).Open()
$reader = New-Object IO.StreamReader($stream)
$text = $reader.ReadToEnd()
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$reader.Close()
$stream.Close()
$zip.Dispose()
if ($bytes) {Set-ItemProperty -path $registryPath -name $keyName -value $bytes -type Binary -force}
While the string values of the standalone "$file" (defined separately as [IO.File]::ReadAllText($file)) and of its archived copy "$archive.zip$name" (already defined as $text) are identical, the byte values from "$file" and from "$archive.zip$name" differ; therefore the latter results in the wrong registry entry which is ignored by the target application.
Note: [System.Text.Encoding]::UTF8|Unicode|ASCII etc, didn't make any difference.
Thank you very much.
Does anyone have any suggestions on how to use PowerShell to change settings in Windows? I understand that this can be done via group policy but my team moves slow with that stuff and I want to find a more efficient way than disabling them by hand.
Hey. Can anyone help me develop a script to launch an RDP session that uses SendKeys (or similar) to enter the username, password, and IP address? I can't find a way to get past the Ctrl + Alt + End. Even with the SendKeys, I can't get past it. My script worked well for Windows 10:
Set-PSDebug -Trace 0
$servers= @("<IP ADDRESS>")
$username = "USER@DOMAIN";
# read the password from a file, or have it hardcoded
#$pw = Get-Content C:\pw.txt
$pw = "<PASSWORD>";
echo "password read from file: " $pw
# login with remote desktop
foreach ($server in $servers)
{
mstsc /v:$server
# wait X seconds for the window to appear
Sleep 5
# creates a com object to send key strokes
$wshell = New-Object -ComObject wscript.shell;
# send the password
$wshell.SendKeys($pw)
# wait 1 second
Sleep 1
# send enter, this is a special chararecters for enter
$wshell.SendKeys('~')
Sleep 1
}
One of our office locations has moved so I want to update the address for all users with Office Location in Los Angeles.
I've been manually entering StreetAddress, City, State, PostalCode in Azure as each new user joins the company. I'm looking at one user's Azure profile and see all these fields filled out. However, when I run Get-AzADUser -Filter "UserPrincipalName eq ‘use@domain’” it's showing all these fields are blank. I've tried to use the MgGraph API in PowerShell but I keep getting errors.
Why does this work fine:
for /r X:\Data-for-converting\ffmpeg %a in (*.avi) do ffmpeg -i "%a" "%~pa%~na.mp4"
But this does not work, doesn't leave any error messages, just doesn't work:
for /r "X:\Also for converting\ffmpeg" %a in (*.avi) do ffmpeg -i "%a" "%~pa%~na.mp4"
Is quotation mark " illegible for paths?
Trying to set the wallpaper on a certain user's account on remote computers pulled from C:\powershell\complist.txt. The wallpaper is already there and located at C:\Windows\Web\Wallpaper\Windows\EXAMPLE.png. The script looks for EXAMPLEUSER and then is supposed to set the registry key for that computer and refresh so it updates.
However for some reason I keep getting: "[ERROR] Wallpaper file not found at C:\Windows\Web\Wallpaper\Windows\EXAMPLE.png", and I'm not sure what's going on. I'm running the script in ISE logged under a network admin account.
Script here: https://pastebin.com/raw/kySmmQn3
Hi all, I'm learning about PowerShell classes (currently starting with the MS documentation) and I'm curious the exact meaning of the double colon ::
with class usage. The MS Learn article explains how the usage [<class-name>]
denotes type in PowerShell, and is used for "built-in" types as well as classes. By "built-in", I mean what are typically basic types in other languages, such as int
, string
, float
, etc.
From Example 1 in the article, I thought perhaps the double colon was used to create a new instance, or object, of a class. The example defines a class Device
and instantiates it by using [Device]::new()
and assigning that to a variable.
In Example 2, they instantiate their Book
class the same way, although they then pass in a collection of properties using the @()
symbol, since one of the constructors defined for the class takes in a hashtable of properties. However, later in the example code, they use the Floor
method found in the Math
class for a calculation using the same double colon notation:
[Math]::Floor()
Would it be correct to say the double colon is the PowerShell way of accessing class methods and properties, similar to how some languages like Python, C, Java, C++, etc. use dot notation? If not, how should I read the double colon?
I have a system.array of files created by Get-ChildItem:
$myFileList
Directory: \\server\share\directory
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 11/26/2024 8:55 AM 10850269 UserData_Extract_20241126.csv
-a---- 11/27/2024 9:06 AM 10853413 UserData_Extract_20241127.csv
-a---- 12/1/2024 9:03 AM 10863303 UserData_Extract_20241201.csv
-a---- 12/3/2024 8:59 AM 10864772 UserData_Extract_20241203.csv
-a---- 12/4/2024 8:59 AM 10867326 UserData_Extract_20241204.csv
Through some other checks I see that I do not need UserData_Extract_20241204.csv
in the array and I'd like to remove it. The file that should be excluded will be assigned to $fileToBeExcluded. Typically I perform this via:
$myFileList = $myFileList | Where-Object { $_.Name -ne $fileToBeExcluded }
This can be iterative and this works but I was wondering if there are any other suggestions using conventional methods. For example I see that the array carries functions like Remove and RemoveAt but I cannot get these to work and Google says that is because of the array's fixed size. At this point any delay time is insignificant but this process may scale up in the future - longer and longer file lists and individual object entries may need to be removed. Is it accepted practice to just overwrite the original array with everything except those objects not matching a value?
Bonjour,
Je souhaite récupérer les fichiers ouvert sur un serveur et exclure les dossiers du résultat.
Voici mon code :
$SmbOpenFile = Get-SmbOpenFile | Where-Object {$_.Path -notlike "*~$*"} | Select-Object -Expandproperty Path
For($a=0 ; $a -lt $SmbOpenFile.Length ;$a++){
$TestDossier = Test-Path -Path $SmbOpenFile[$a] -PathType Container
if ($TestDossier -eq $false){
$file1 = $file1 + SmbOpenFile[$a]
}
}
Dans mon code je récupère d'abord tout dans ma variable $SmbOpenfile puis je teste chaque Path pour vérifier qu'il ne s'agit pas d'un dossier. Cependant je n'arrive à structurer mon résultat. La variable $file1 me retourne les bons chemins (sans les dossiers) mais les uns à la suite des autres (sans retour chariot). Je ne trouve pas comment structurer ma variable (pour faire des retour à la ligne propre)
Avez-vous des conseils à me donner ? Ou une autre méthode plus propre pour récupérer ces infos ?
Merci d'avance.
Error is cannot convert value '7fffff' to type "SystemUInt32" when trying to add a dword value to a registry key. Why is it trying to convert at all instead of accepting it as a string?
I tried defining the value as $val = '7fffff', and confirmed that was a string, but same error.
Hi all,
I hope this community will help me because I'm in stuck with a very weird error.
For our cd pipelines we often use linux containers with powershell installed and recently provisioned some new jenkins linux agents that run in our linux workers using no-priviledged users.
Any jenkins pipeline with a pwsh comand on the new workers goes in error with the following output:
Process terminated. Object reference not set to an instance of an object.
at System.Environment.FailFast(System.String, System.Exception)
at Microsoft.PowerShell.UnmanagedPSEntry.Start(System.String[], Int32)
at Microsoft.PowerShell.ManagedPSEntry.Main(System.String[])
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Management.Automation.Language.AstSearcher.Contains(Ast ast, Func`2 predicate, Boolean searchNestedScriptBlocks)
at Microsoft.PowerShell.ConsoleHost.DoRunspaceInitialization(RunspaceCreationEventArgs args)
at Microsoft.PowerShell.ConsoleHost.CreateRunspace(RunspaceCreationEventArgs runspaceCreationArgs)
at Microsoft.PowerShell.ConsoleHost.DoRunspaceLoop(String initialCommand, Boolean skipProfiles, Collection`1 initialCommandArgs, Boolean staMode, String configurationName, String configurationFilePath)
at Microsoft.PowerShell.ConsoleHost.Run(CommandLineParameterParser cpp, Boolean isPrestartWarned)
at Microsoft.PowerShell.ConsoleHost.Start(String bannerText, String helpText, Boolean issProvidedExternally)
at Microsoft.PowerShell.UnmanagedPSEntry.Start(String[] args, Int32 argc)Aborted (core dumped)
We are unable to reproduce the error outside Jenkins, if we try to start the container manually in the same worker using the same no-priviledged user and the same options it works without exceptions.
If we start the same pipeline in the same workers with a priviledged user (root) it works.
Thanks in advance