powershell
348 TopicsCannot install PnP.Powershell
Something has changed recently I can no longer execute scripts that I had. So I decided to re-install various bits and pieces. When I come to install PnP.Powershell I get an error: 'WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2'.992Views1like6CommentsGet-Secret fails when PowerShell script runs as a scheduled task.
I have a PowerShell backup script that connects to SMB shares, copies files from one share to the other share, and disconnects. Passwords used to connect to the shares are stored in a SecretStore. The user account that the script runs under is an unpriviledged Backup Operator that has access to the SMB shares. THe SecretStore was created under the same user context. I can run the script manually in the console, and it executes correctly. When I run the same script as a scheduled task, running under the same user account, the script stops when the Get-Secret cmdlet is called. Here is some pertinent information: PS C:\Users\incodebackup\Documents\Scripts\TUNet_Backup> $PSVersionTable Name Value ---- ----- PSVersion 5.1.14393.3471 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.14393.3471 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1 PS C:\Users\incodebackup\Documents\Scripts\TUNet_Backup> Get-Module -ListAvailable Directory: C:\Program Files\WindowsPowerShell\Modules ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 1.0.1 Microsoft.PowerShell.Operation.V... {Get-OperationValidation, Invoke-OperationValidation} Binary 1.1.2 Microsoft.PowerShell.SecretManag... {Register-SecretVault, Unregister-SecretVault, Get-SecretVault, Set-SecretVaultDefault...} Binary 1.0.6 Microsoft.PowerShell.SecretStore {Unlock-SecretStore, Set-SecretStorePassword, Get-SecretStoreConfiguration, Set-SecretStoreConfiguration...} PS C:\Users\incodebackup\Documents\Scripts\TUNet_Backup> Get-SCheduledTask | Format-List -Property * State : Ready Actions : {MSFT_TaskExecAction} Author : WIN-M95PVJLVDAB\incodebackup Date : 2026-01-27T15:28:35.7952875 Description : This task copies files out of the TUNET/datafile directory once a say to ARCHIBALD. Documentation : Principal : MSFT_TaskPrincipal2 SecurityDescriptor : Settings : MSFT_TaskSettings3 Source : TaskName : Daily TUNet Backup Copy TaskPath : \ Triggers : {MSFT_TaskDailyTrigger} URI : \Daily TUNet Backup Copy Version : PSComputerName : CimClass : Root/Microsoft/Windows/TaskScheduler:MSFT_ScheduledTask CimInstanceProperties : {Actions, Author, Date, Description...} CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties I execute Start-Transcript early in the script execution, and because of the crash(?), it is short enough to included in its entirety: ********************** Windows PowerShell transcript start Start time: 20260127190002 Username: WIN-M95PVJLVDAB\incodebackup RunAs User: WIN-M95PVJLVDAB\incodebackup Machine: WIN-M95PVJLVDAB (Microsoft Windows NT 10.0.14393.0) Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NonInteractive -File C:\Users\Incodebackup\Documents\Scripts\TUNet_Backup\Copy-TUNetBackup.ps1 -daily -test Process ID: 2084 PSVersion: 5.1.14393.3471 PSEdition: Desktop PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.14393.3471 BuildVersion: 10.0.14393.3471 CLRVersion: 4.0.30319.42000 WSManStackVersion: 3.0 PSRemotingProtocolVersion: 2.3 SerializationVersion: 1.1.0.1 ********************** Transcript started, output file is C:\Users\Incodebackup\Documents\Scripts\TUNet_Backup\daily_2026-01-27_190002.log 2026/01/27 19:00:02 INFO 940 TUNet backup script started. 2026/01/27 19:00:02 INFO 941 Copy-TUNetBackup.ps1 Version: 6.0F 2026/01/27 19:00:02 INFO 942 Parameter qhourly: False 2026/01/27 19:00:02 INFO 943 Parameter hourly: False 2026/01/27 19:00:02 INFO 944 Parameter daily: True 2026/01/27 19:00:02 INFO 945 Parameter purge: False 2026/01/27 19:00:02 INFO 946 Parameter archive: False 2026/01/27 19:00:02 INFO 947 Parameter test: True 2026/01/27 19:00:02 INFO 1035 Creating mutex object. 2026/01/27 19:00:02 INFO 1037 Creating semaphore object. 2026/01/27 19:00:02 INFO 1058 Mutex timeout set: 300000 2026/01/27 19:00:02 INFO 1072 Attempting to acquire mutex to enter semaphore... 2026/01/27 19:00:02 INFO 1074 ...got the mutex! 2026/01/27 19:00:02 INFO 1075 Attempting to enter the semaphore... 2026/01/27 19:00:02 INFO 1077 ... got the semaphore! 2026/01/27 19:00:02 INFO 719 Release-Mutex: Attempting to release mutex... 2026/01/27 19:00:02 INFO 721 Release-Mutex: ...done. 2026/01/27 19:00:02 INFO 1090 Using TEST values for source and destination paths. 2026/01/27 19:00:02 INFO 1109 TUnet Source: \\192.168.100.46\Netbackup\Netbackup\Tantalus\test_src\datafile 2026/01/27 19:00:02 INFO 1110 ARCHIE Dest: \\192.168.100.46\Netbackup\Netbackup\Tantalus\test_dest\datafile 2026/01/27 19:00:02 INFO 1114 Attempt to acquire mutex to mount network shares... 2026/01/27 19:00:02 INFO 1116 ...got the mutex! 2026/01/27 19:00:02 INFO 1117 Opening SecretStore vault...! 2026/01/27 19:00:02 INFO 1120 ... vault opened! 2026/01/27 19:00:02 INFO 1121 Checking connection to \\192.168.100.46\Netbackup\Netbackup\Tantalus ... 2026/01/27 19:00:02 INFO 1126 ...not connected to \\192.168.100.46\Netbackup\Netbackup\Tantalus . 2026/01/27 19:00:02 INFO 1127 Get FULTON\incodebackup password... ********************** Windows PowerShell transcript end End time: 20260127190002 ********************** Now I will show you the script around line 1127 where it goes out into the weeds: Write-Log -Level "INFO" -Message "$(__LINE__) Opening SecretStore vault...!" $pw = Import-CliXml -Path '.\TUNet-Backup-Vault.xml' -Verbose Unlock-SecretStore -Password $pw Write-Log -Level "INFO" -Message "$(__LINE__) ... vault opened!" # # Statements omitted # Write-Log -Level "INFO" -Message "$(__LINE__) Get $archie_un password..." try { $pw = Get-Secret -Name $archie_un -Verbose -Debug } catch { $err_msg = "Get-Secret exception. Name: $archie_un Exception: $($_.Exception.Message)" Write-Log -Level "FATAL" -Message "$(__LINE__) $err_msg" throw $err_msg } Write-Log -Level "INFO" -Message "$(__LINE__) ...done!" I was able to unlock the SecretStore, but Get-Secret fails. The very odd thing, besides not getting my password out the SecretStore, is that there is no exception posted by Powershell. I have no information at all about why my attempt did not work. If Get-Secret exited, then I would expect one of the two possible log messages printed in the transcript, but as you can see, the transcript ended. Note: the entire script body is encapsulated in a try{} block, which has an associated finally{} block, which contains other logging commands that execute when the finally{} block is entered, but in scheduled task instance, nothing. If anyone can tell me how to make Get-Secret work, that would be great, but I'll settle very gratefully for some way to get more information from this system to try to figure out why it is not, that would be most helpful. Additional information supplied on request.35Views0likes1CommentBuild PowerShell as "framework-dependent"
Before I start a time expensive and maybe unsuccessful attempt: Is it relatively easily possible to compile PowerShell from the source and make it "framework-dependent" instead of "self-contained"? In doing so, PowerShell could be de-coupled from the .NET runtime (which is most probably already installed), and maybe an even newer runtime version could be used (currently, PowerShell has no .NET 10 packed and I have to wait for a release that supports it)...54Views0likes1CommentMap vmdk to guest volume
I have a Hyper-V cluster and want PowerShell to give me a list of what vmdk file is assigned to which volume mount point in the virtual machine OS (Windows). Example: vmdk file mount point ------------------------------------------------------------------------------------------- C:\ClusterStorage\Data1\VM\ComputerA\Virtual Hard Disks\OSDisk.vhdx C:\ C:\ClusterStorage\Data1\VM\ComputerA\Virtual Hard Disks\MainMount.vhdx M:\ C:\ClusterStorage\Data1\VM\ComputerA\Virtual Hard Disks\Temp.vhdx M:\Temp The vmdks for C: and M: are mapped to drives in the guest, whereas Temp.vhdx is mounted in a folder under M:\. The main challenge for me is actually to find the correct elements that allow me to link a VMDK to a disk inside the virtual machine OS. The ones I found so far are: Get-Disk gives me numbers for adapter, port, target, and LUN, and Get-VMHardDiskDrive returns numbers for controller and location, which I guess link to target and LUN. But I'm pretty unsure whether it's safe to use these properties... Get-Disk returns a path, and I think I can use this to map the result of a win32_mountpoint CIM query to it to get the volume mount point... Does anyone have some valuable information for me on this?168Views0likes1CommentNew-MgBookingBusinessService | Customer Information Questions
I'm trying to turn off the stock Customer Information questions except for the customer email using PowerShell and New-MgBookingBusinessService and cannot seem to figure it out. Any assistance is much appreciated! # Prompt for Booking Business ID $bookingBusinessId = Read-Host "Enter the Booking Business ID (e.g., email address removed for privacy reasons)" # Prompt for default duration in minutes $defaultDurationMinutes = Read-Host "Enter default appointment duration in minutes (e.g., 15)" $defaultDuration = [TimeSpan]::FromMinutes([double]$defaultDurationMinutes) # Post-buffer stays at 5 minutes $postBuffer = [TimeSpan]::FromMinutes(5) # Hardcoded Excel file path $excelFilePath = "C:\Users\apettit\OneDrive - Eau Claire Area School District\Downloads\adamtestconferencedata.xlsx" # Prompt for worksheet/tab name $sheetName = Read-Host "Enter the worksheet/tab name to read data from" # Import Excel data using Import-Excel (requires ImportExcel module) if (-not (Get-Module -ListAvailable -Name ImportExcel)) { Install-Module -Name ImportExcel -Scope CurrentUser -Force } Import-Module ImportExcel $staffEmails = Import-Excel -Path $excelFilePath -WorksheetName $sheetName # Retrieve all staff members for the booking business Write-Host "Fetching all staff members for booking business ID: $bookingBusinessId" $allStaff = Get-MgBookingBusinessStaffMember -BookingBusinessId $bookingBusinessId if (-not $allStaff) { Write-Error "No staff members found for the booking business ID: $bookingBusinessId" return } # Retrieve all custom questions Write-Host "Fetching all custom questions for booking business ID: $bookingBusinessId" $allCustomQuestions = Get-MgBookingBusinessCustomQuestion -BookingBusinessId $bookingBusinessId if (-not $allCustomQuestions) { Write-Error "No custom questions found for the booking business ID: $bookingBusinessId" return } # Loop through each staff member from Excel automatically Write-Host "Creating individual booking services for each staff member..." foreach ($row in $staffEmails) { $email = $row.emailAddress.Trim().ToLower() # Automatically match staff from Booking Business $matchingStaff = $allStaff | Where-Object { $_.AdditionalProperties["emailAddress"] -and ($_.AdditionalProperties["emailAddress"].Trim().ToLower() -eq $email) } if ($matchingStaff) { $staffId = $matchingStaff.Id $displayName = $matchingStaff.AdditionalProperties["displayName"] Write-Host "Automatically creating service for: ${displayName} ($email)" -ForegroundColor Cyan try { # Prepare custom questions $customQuestions = $allCustomQuestions | ForEach-Object -Begin { $isLast = $false } -Process { $isLast = ($_.Id -eq $allCustomQuestions[-1].Id) $questionAssignment = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphBookingQuestionAssignment $questionAssignment.QuestionId = $_.Id $questionAssignment.IsRequired = if ($isLast) { $false } else { $true } $questionAssignment } # Prepare the reminder $defaultReminder = New-Object Microsoft.Graph.PowerShell.Models.MicrosoftGraphBookingReminder $defaultReminder.Message = "Don't forget! Family Teacher Conferences are tomorrow, and we are excited to visit with you! If you wish to change the meeting type (virtual, in-person, hybrid, or phone), please let the teacher know as soon as possible!" $defaultReminder.Offset = [TimeSpan]::FromDays(1) $defaultReminder.Recipients = @("customer") # Prepare service parameters $serviceParams = @{ BookingBusinessId = $bookingBusinessId DisplayName = "${displayName} Family Conference" Description = "Family Teacher Conference with ${displayName}" StaffMemberIds = @($staffId) # Assign specific staff member DefaultDuration = $defaultDuration DefaultPrice = 0.00 DefaultPriceType = "free" CustomQuestions = $customQuestions PostBuffer = $postBuffer IsLocationOnline = $true IsCustomerAllowedToManageBooking = $true DefaultReminder = $defaultReminder AdditionalInformation = @" Please arrive on time for your conferences as we will be sticking to a tight schedule. If you wish to change the meeting type (virtual, in-person, hybrid, or phone), please let the teacher know as soon as possible. If you require a translator, please submit a request at this form: https://forms.office.com/r/XWwBFWP7XD "@ # Appears in the customer confirmation email AdditionalProperties = @{ customerEmail = @{ isRequired = $true } # Only email field remains } } # Log service parameters Write-Host "Service Parameters for ${displayName}:" -ForegroundColor Blue $serviceParams.GetEnumerator() | ForEach-Object { Write-Host "$($_.Key): $($_.Value)" } # Create the booking service New-MgBookingBusinessService @serviceParams Write-Host "Booking service successfully created for ${displayName}!" -ForegroundColor Green } catch { Write-Error "Failed to create booking service for ${displayName}: $_" } } else { Write-Warning "No match found for email: $email" } }143Views0likes1CommentCan't add device member in Static Security Entra Group with powershell
Hi, With Graph, I want to add some device members in a static security Entra group using it to deploy some certificates with Intune. I do it with following command: New-MgGroupMember -GroupId $groupId -DirectoryObjectId $device.AzureAdDeviceId but I receive this error: New-MgGroupMember : Resource 'df75dfe1-8b5a-4cc6-8f99-17746bb8c07e' does not exist or one of its queried reference-property objects are not present. In C:\Users\E21996\OneDrive - Fondazione Enasarco\Lavoro\!HelpDesk\!Intune\Scripts\Set-Device-Department-Attribute.ps1:57 car:9 + New-MgGroupMember -GroupId $groupId -DirectoryObjectId $devic ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: ({ GroupId = 9fa...ferenceCreate }:<>f__AnonymousType1`2) [New-MgGroupMember_CreateExpanded], Exception + FullyQualifiedErrorId : Request_ResourceNotFound,Microsoft.Graph.PowerShell.Cmdlets.NewMgGroupMember_CreateExpanded I've checked the GroupID and Azure Device ID and are correct. If I try to add a user it works fine, with device I have this error. In the group I can add device member manually from Intune without problems. There is a known issue when add device members to groups in Graph? Can anyone help me to resolve this issue, please?236Views0likes2CommentsCopy-Item -Recurse bug
We are copying files using the Copy-Item cmdlet from a local disk to a remote disk. The source folder contains around 900 files in numerous subdirectories. Copy-Item -Path "build\image\*" -Destination $output_path -Recurse -Verbose Get-Command Copy-Item | Select-Object Name, Version Name Version ---- ------- Copy-Item 3.1.0.0276Views1like3CommentsFC Target discovery
I was looking for a way to discover FC targets for each initiator. Searching on the web I found this code # Get all initiator ports (HBA ports) $initiatorPorts = Get-InitiatorPort # Loop through each initiator port and list its targets foreach ($port in $initiatorPorts) { Write-Host "Initiator Port: $($port.NodeAddress) - $($port.PortAddress)" $targets = Get-InitiatorTarget -InitiatorPortAddress $port.PortAddress foreach ($target in $targets) { Write-Host " Target: $($target.NodeAddress) - $($target.PortAddress)" } } But is not working because the Get-initiatortarget is not recognized as valid command. Is there a way I can do it thanks177Views0likes2CommentsNeed help importing user data from csv
I need to fill in the Manager Attribute for employee accounts using a CSV export from HR. I have the added bonus of the fact that SamAccountNames do not follow a consistent naming convention. So I need to use the EmployeeID attribute for finding accounts. Here is an example of the CSV. "LAST_NAME","FIRST_NAME","EmployeeID","SupervisorID" "Doe","John","12345","13324" "Jane","Laura","13456","3455" "Mclane","John","12351","11331" In this case, John Doe's Manager has an EmployeeID of 13324. So I need to search AD for a User object with the EmployeeID attribute of 13324. Then I need to pull the DistinguishedName attribute from that User Object, for example "CN=LSkywalker,OU=Department,DC=contoso,DC=com" Then I'd have to copy that data into the Manager attribute of John Doe's account. I've been trying to outline the script and so far this is what I have. Variables $User $SupervisorID $EmployeeID $DistinguishedName For each $User in CSV find $EmployeeID and $SupervisorID Search AD for Supervisor Account where EmployeeID attribute = $SupervisorID Pull $DistinguishedName Attribute value from Supervisor's account Input $DistinguishedName value into original $EmployeeID's Manager Attribute Proceed to next line of CSV and repeat Hopefully I've explained the situation well and someone can help me flesh this out more, any help would be greatly appreciated, thank you.Solved2.6KViews0likes8Comments