Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Set-Msoluser : Access Denied. You do not have permissions to call this cmdlet

$
0
0

I have successfully connected to Office 365 Admin service and Exchange Online Services. I have tested the cmdlets such as Get-MsolUser and they work fine. However, when I try to run the command Set-MsolUser to change the Title, I get the Access Denied error as shown below. It's weird because I can manually go into Exchange and change any property I want but it won't let me run this command? Any way around this?

Script to update Office 365 user attributes

## Variables
$systemmessagecolor = "cyan"
$processmessagecolor = "green"
$savedcreds=$false                      ## false = manually enter creds, True = from file
$credpath = "c:\downloads\tenant.xml"   ## local file with credentials if required

## If you have running scripts that don't have a certificate, run this command once to disable that level of security
## set-executionpolicy -executionpolicy bypass -scope currentuser -force

Clear-Host

write-host -foregroundcolor $systemmessagecolor "Script started`n"

#install-module msonline
Import-Module -Name "C:\Temp\MsOnline" -Verbose
write-host -foregroundcolor green "MSOnline module loaded"

## Get tenant login credentials
$cred = Get-Credential


## Connect to Office 365 admin service
connect-msolservice -credential $cred
write-host -foregroundcolor $systemmessagecolor "Now connected to Office 365 Admin service"

## Start Exchange Online session
$EXOSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell -Credential $cred -Authentication Basic -AllowRedirection
import-PSSession $EXOSession -AllowClobber
write-host -foregroundcolor $processmessagecolor "Now connected to Exchange Online services`n"
write-host -foregroundcolor $systemmessagecolor "Script Completed`n"


# Load data from file.csv
$EXUsers = Import-csv file_path.csv


# Count variable for number of users update
$count = 0

# Go through each row that has user data in the CSV we just imported 
ForEach($User in $EXUsers)
{
    # Ppopulate hash table for Get-Msoluser splatting:
    $GetParams =
    @{
        UserPrincipalName     = $User.userPrincipalName
    }

    # Initialize hash table for Set-Msoluser splatting:
    $SetParams =
    @{
        UserPrincipalName     = $User.userPrincipalName
        Title                 = $User.title
    }

    # Get user and update.
    if ( Get-Msoluser @GetParams)
    {
         # Set User attributes
         Set-MsolUser @SetParams

         # Print that the user was updated 
         Write-Host -ForegroundColor Yellow "$User - User attributes have been updated." 

         # Update Count
         $count += 1    
     }
}

# Print the number of updated users
Write-Host $count "Users have been updated" -ForegroundColor Green

Error message

Set-Msoluser : Access Denied. You do not have permissions to call this cmdlet.
At line:1 char:59+ ... ncipalName "name@company.com" | Set-Msoluser -Title "Test Title"+                                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OperationStopped: (:) [Set-MsolUser], MicrosoftOnlineException+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.AccessDeniedException,Microsoft.Online.Administration.Automation.SetUser


How to Get the local Group Members list with nested users (until last one) using power shell script

$
0
0

I have a requirement to get local group members list (Administrators, Remote Dekstop Users ETC..) with its nested members as well until the last one using powershell script for given list of servers.

Example: when we run the script in given list of servers, it should check for its local groups wherever members are available it should return output with the below table format until it nested groups members list.

ServerUser NameUser typeDescriptionStatusPriv groupPriv group AdminParent local groupDisplay nameCompany
Server Name*******Local/Domain*******EnabledAdministratorsLocalAdministrators   ***************

Note: Could anyone help me with the script please. 

PowerShell : Suppress WPF WebBrowser script errors

$
0
0

Hi,

I have a requirement to show Webpage through Powershell. I have designed a wpf Xaml and able to show the web browser through powershell.

The Problem is that when clicking on any hyperlinks on the page it throws error "Do you want to continue Running script on this page?". I have tried many ways but unable to suppress the error. Hence, seeking your help.

Please see the error:

https://i.stack.imgur.com/J8nMP.png

Xaml Code I have used:

<Grid xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><DockPanel ><WebBrowser Name="WebBrowser" DockPanel.Dock="Left" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ></WebBrowser></DockPanel></Grid>

I am implementing through hamburger menu. So, the above xaml is the child window of an button. Webpage is displaying perfectly. The problem is with the script error.

Could someone please enlighten me how to suppress this error?


Wanted to block particular security group so that they can not query/access/modify/create or delete data of Active Directory using powershell commands or powershell scripts but they can use RSAT for same.

$
0
0

Hello Everyone,

In brief, we have Domain environment (Active Directory structure) and wanted to block particular security group only (not for all the groups but only for the particular group say group X) so that they can not access Active Directory using powershell commands or powershell scripts. We do not want to block powershell utility for them on their local systems but to block access of AD whenever they will use powershell utility only. Here they should access  AD whenever they use RSAT (only need to block AD access whenever they will use powershell utility to access AD).

Looking for your great support on this.

Unable to install window update using Powershell Script

$
0
0

Hi Support,

I am trying to install windows remotely using power shell and getting the error message.

Invoke-AzureRmVMRunCommand  -CommandId 'RunPowerShellScript' -ScriptPath $Inputscript -Confirm:$false -Verbose | Out-File -FilePath $OutFile

Script:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

Install-Module -Name PSWindowsUpdate -Force

Import-Module -Name PSWindowsUpdate

Install-WindowsUpdate -KBArticleID KB890830,KB2267602 -Confirm:$false -AutoReboot

Error Message:

Message  : Install-PackageProvider : The term 'Install-PackageProvider' 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:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows\1.1.5\Downloads\s
cript2.ps1:2 char:1
+ Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Install-PackageProvider:String)
    [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Powershell -- The argument is null or empty

$
0
0

Hello Microsoft Community,

I'm very new to Powershell, but I do have a bit of experience coding.

I'm trying to create a powershell script to onboard users into our AD.

Here's an example of what I'm attempting.

function example{
     $user = read-host -prompt "enter username"

     Invoke-Command -ComputerName Server -ScriptBlock {New-ADUser -Name $user}

}

Im getting this error message

Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then
try the command again.

I'm assuming the scriptblock command isn't able to reference the variables in this function. I'm wondering what syntax to use call these variables inside scriptblock.

A nudge in the right direction would greatly help.

Thank you

Debug Add-InsightsCapability PowerShell command using WinDbg

$
0
0

Is it possible to step inside a PS command and get more information on the error messages.

For example when I run the following command in three ways I sort of get three different error messages but none of them actually point to the error causing character:
Way 1:
Add-InsightsCapability -Name "Syt" -Library "C:\RdtCapability.dll" -Confirm:$false
The error message I get is
Add-InsightsCapability : System Insights failed to register one or more of data sources for capability 'Syt'. At line:1 char:1
Way 2:
Debug-Process -Name "Add-InsightsCapability -Name "Syt" -Library "C:\RdtCapability.dll" -Confirm:$false"
Debug-Process : A positional parameter cannot be found that accepts argument 'Syt -Library C:\RdtCapability.dll -Confirm:False'.
At line:1 char:1
Way 3:
> Add-InsightsCapability
cmdlet Add-InsightsCapability at command pipeline position 1
Supply values for the following parameters:
Name: "Syt"
Library: "C:\RdtCapability.dll"
Adding a capability:
Adding capability '"Syt"'. Do you want to continue?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
Add-InsightsCapability : Illegal characters in path.
At line:1 char:1
I was told if I run PS inside WinDbg then I might be able to step inside the Add-InsightsCapability() call and exactly locate the illegal character. In general if this is indeed possible then it will be a very useful procedure to know for any other PS command. 
regards

ananda


Get-Clusternode using Role IP address for a remote cluster

$
0
0

Is there a way to get cluster nodes of a remote cluster using role IP address with powershell cmdlets in a single line.

Please advice!! I have a to execute this one line command to get cluster nodes. For ex: 

powershell.exe (Get-ClusterNode).Nodename

returns:

CN33
CN34
CN44
CN45

Above are node names in the local cluster.

Thanks for help!!

Thanks,

Surabhi


Surabhi


registry change

$
0
0

Hi All i want to modify the below registry values from 0 to 1 using powershell on remote servers, i have servers list in the below format. experts guide me on this, i am trying the below but i am not getting it

Server01.contoso.com
Server02.contoso.com

$ServersList = "c:\list.txt"
$SS = get-Content -Path $ServersList
foreach ($Servers in $SS ) {
Set-itemproperty -name EnableSecuritySignature -path "HKLM\System\CurrentControlSet\Services\LanManWorkstation\Parameters" -value "1";}

CPU usage increases to 50% when I use "Get-WmiObject", why it is happening?

$
0
0
CPU usage got increase when I use Get-WmiObject, any reason behind that, or is it a bug?

After some search, I found out the alternative of this command which is Get-CimInstance but is also using the same space. Is there any alternative available to mitigate this issue? 

Pull All User Attributes with PowerShell

$
0
0

Okay, when I go into ADUC and open up the Attribute Editor for a User I see something like 300 attributes. Many are blank or unused, that's fine. I need to pull that full list with Powershell. I don't care whether they are blank or null or whatever, I want a list of every attribute available in my directory. I've tried several different queries with different tools. Get-ADUser is the most comprehensive at 100 attributes returned.

Get-ADUser username -Properties * | Select *
This isn't all of them. For example the "Audio" Attribute doesn't show up. But as soon as I put a value in Audio it does show up. So I know that the CMDLET has access to the attributes it just isn't showing them to me. Is there a flag/switch I'm missing that will show everything? Is there a different CMDLET I should be using?

Thanks much for the help in advance.

Search last date modified starting 2 folders down.

$
0
0

We have tons of archived projects.  I'm looking to run through the folders, starting two folders deep and export the results  to csv with the Folder path and the LastWriteTime.

Example of folder structure:

Projects 1-1000

***Project 1

******Project 1.1

******Project 1.2

 There are thousands of projects which is why they are grouped 1-1000, 1001-2000, etc.

Ideally, the final list would look like this:

Folder Path\Project 1.1    July 21, 2000

Folder Path\Project 1.2    May 22, 2017

etc.

The date being the latest modified date of anything in the folder (Project 1.1) or any of the many sub-folders within Project 1.1 and so on for Project 1.2.

Our attorney will then choose how many years back we need to keep the data, so she may say Project 1.1 can be deleted because of how old it is.

This code works great, but I need to somehow add the -depth parameter to start at the Project 1.1 level.

$Result = Get-ChildItem -Path '.\Program 1\Projects 1-1000\*' -Directory |
    ForEach-Object {
        $NewestItem = Get-ChildItem -Path $_.FullName -File -Recurse | Sort-Object -Property LastWriteTime | Select-Object -Last 1
        [PSCustomObject]@{
            Folder = $_.FullName
            NewestItem = $NewestItem.FullName
            NewestItemDate = $NewestItem.LastWriteTime
        }
    }
$Result | Export-Csv -Path .\output.csv -NoTypeInformation

How do I modify this to start at the Project 1.1 level?

.





Microsoft Module Browser for Windows PowerShell ISE - how to make it work with modern Windows 10?

$
0
0

I'm unable to make Microsoft Module Browser for Windows PowerShell ISE working on my Windows 10 machine. Is it still suported, or is there some reasonable alternative?

Here are older tool descriptions and download links:

https://devblogs.microsoft.com/powershell/ise-module-browser-a-new-way-to-manage-your-powershell-modules/

https://www.microsoft.com/en-us/download/details.aspx?id=45885

PowerShell Script for updating an employeeID by either current employeeID or username

$
0
0

PowerShell Script for updating an employeeID by either current employeeID or username?

Any idea what the best scipt for this would be.

Select-String - take only the following text

$
0
0

How get from, including, the searched word and next text?

I use

Get-Content 'C:\Teste\Fruit.txt'|Select-String "Naranja"

Result

Limones    30 Kg     Manga 50Kg    Naranja   10KG

How to object the result is:

Naranja   10KG


PowerShell - Display lines based on character position.

$
0
0

The List.txt file contains:

00.0001 - Product 1
Manufacturer
Country of origin
Distributor
unity
Amount
Purchase Date
Due date
00.0002 - Product 2
Manufacturer
Country of origin
Distributor
unity
Amount
Purchase Date
Due date
00.0003 - Product 3
Manufacturer
Country of origin
Distributor
unity
Amount
Purchase Date
Due date


I want to display only the lines that have a dot in the third character, like this:

00.0001 - Product 1
00.0002 - Product 2
00.0003 - Product 3

I tried

$x = Get-Content C:\Teste\List.txt
for($i=0;$i -lt $x.Count;$i++){
    if ($x.Substring(2,1) = '.'){
	$x.Substring(2,1)
}
}

 

how to view / export AD users logged on report

$
0
0

Hi,

Can someone help me to generate report for the following task using Power shell command!

1. List all the AD users currently logged on to the computers & also exporting

2. History of individual AD user / all users logged on from which computer past 1 week.

The above to be generated for document purpose, kindly advice

Thanks in advance

FSRM powershell cmdlet New-FsrmQuota throws ObjectNotFound exception in VM of Custom Image with FSRM pre-installed

$
0
0

I built a Custom Image based on windows-2019-datacenter, with FSRM feature installed. After I create a VM with my Custom Image, I tried to run the following command:

 New-FsrmQuota -Path "D:\Test" -Description "limit usage to 1.5 GB" -Size 1.5GB

But I encountered the following exception:

New-FsrmQuota : Not found
At line:1 char:1
+ New-FsrmQuota -Path "D:\Test" -Description "limit usage to 1.5 GB" -S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (MSFT_FSRMQuota:Root/Microsoft/.../MSFT_FSRMQuota) [New-FsrmQuota], CimE
   xception
    + FullyQualifiedErrorId : HRESULT 0x80041002,New-FsrmQuota

It seems like a DLL is not loaded. But I don't see any FSRM dlls are under the module path, so I'm not sure which dll is not loaded. So please help me to get an idea what's going on here.

Need help getting a DHCP script to work !! Ignores the -le condition

$
0
0

Bit of a noob at powershell so bare with me..

Trying to get a script to automatically create 4 scopes, all with the same DHCP options, with the only difference being the value in the 2nd octet of the subnet:

Example:

10.32.12.32/28


+32 to second octet


10.64.12.32/28


+32 to second octet


10.96.12.32/28


+32 to second octet


10.128.12.32/28

===================

for($z=32;$z -le 128){

    for($b=12){

    for($i=32){

                     $startip = $i+2

                     $endip = $i+12

                     $router = $i+1

                     Add-DhcpServerv4Scope -Name 10.$z.$b.$i -StartRange 10.$z.$b.$startip -EndRange 10.$z.$b.$endip -SubnetMask 255.255.255.240 -LeaseDuration 1.00:00:00

                     Set-DhcpServerv4OptionValue -ScopeId 10.$z.$b.$i  -Router  10.$z.$b.$router -DnsDomain XXX.com.au -DnsServer 192.168.160.52

                     $z = $z + 32

        }

    } 

}


=====

Looks like the script screams past the -le 128 condition i put in :


Any ideas on how to get the desired result??



Powershell and configuration files - Read data from configuration file to restore database in remote SQL Server

$
0
0

Hi.

I am trying to use Powershell to restore backup to a remote SQL Server.

I have a config.xml file, which has format as below

<?xml version="1.0"?><Config><Action>Deploy</Action><Region1><DBRestorePath Path= "\\SourceServer\D$\BACKUP\" > </DBRestorePath><DestinationSQLServer Path="\\servername\D$\BACKUP\;\\2NDservername\D$\BACKUP\"> </DestinationSQLServer></Region1><Region2><DBRestorePath Path= "\\SourceServer\D$\BACKUP\" > </DBRestorePath><DestinationSQLServer Path="\\servername\D$\BACKUP\"> </DestinationSQLServer><Region2></Config></xml>

I am trying to create a Windows Powershell script file, which does three things:

1) Take the input of which Region from user

2) depending on the input , copy the files from the DBRestorePath and pastes in the DestinationSQLServer Path.

3) Restores the database in remote server with the backup files.

Region1 has 2 destination server seperated by semicolon. So the files needs to be copied to multiple server.

How to achieve this in Powershell ?

Thanks



Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>