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

Where-Object breaks script

$
0
0

I need to pull a list of accounts from a single OU that have 2 specific values in 2 attributes, these accounts also need to have not reset their passwords in a number of days.

I can run part of my script and get the accounts without password reset in the given number of days, but as soon as I add a condition looking for either of the attribute values it returns 0 results, even though I know there are thousands of them

The code I am trying is 

$PasswordAge = 30
$time = (Get-Date).Adddays(-($PasswordAge))
Get-ADUser -ResultpageSize 20000 -Filter {pwdLastSet -lt $time} -SearchBase "ou=MYOU,dc=domain,dc=com" | Where-Object {$_.customattribute -contains 'Value'} | Where-Object {$_.memberof -contains 'CN=Group Name,OU=Security Groups (Mail Enabled),DC=domain,DC=com'} Select-Object sAMAccountName |  ConvertTo-Csv -NoTypeInformation |  Select-Object -Skip 1 | Set-Content -Path "c:\users\test.csv"

So this should give me all accounts in MYOU with a password reset date of 30 days or more in the past with the given values in customattribute and memberof. The results should be saved to a csv on my C drive with the column headercremoved and only the saMAccountName attribute should be listed.

If I run just 

$PasswordAge = 30
$time = (Get-Date).Adddays(-($PasswordAge))
Get-ADUser -ResultpageSize 20000 -Filter {pwdLastSet -lt $time} -SearchBase "ou=MYOU,dc=domain,dc=com" | Select-Object sAMAccountName |  

I get all the sAMAccountName values for users in the OU with no password reset in 30 days or more scrolling down the screen, if I add the code to export to csv I get the same results saved to the csv file

What am I doing wrong?



Create NIC team using all interfaces

$
0
0

I'm trying to put together a function that will take all the physical NICs on a server and team them together. I'm not even sure where I found the example, but here is the code I have below. This seems like it should be much simpler and that I'm missing something.

# Create a network team using switch independent teaming and Hyper-V port mode
Function TeamSetup ($teamName)
{
	$adapters = Get-NetAdapter
	$nicList = @()
	Foreach ($nic in $adapters)
	{
		$nicList += $nic.Name
	}
	New-NetLbfoTeam $teamName –TeamMembers ($nicList) –TeamNicName $teamName -TeamingMode SwitchIndependent -LoadBalancingAlgorithm HyperVPort
}

Eventual time out of session (suspected)

$
0
0

Hi All

While running a script I do a connection to SkypeOnline so I can set some policies on potentially thousands of students in a tenant:

Import-Module SkypeOnlineConnector
    $SfBsession = New-CsOnlineSession -Credential $cred -Verbose -OverrideAdminDomain $MSDomain
    Import-PSSession -Session $SfBsession

After a while of running the loop successfully setting policies, it starts throwing this:

Grant-CsTeamsMeetingPolicy -PolicyName Tag:Education_Student -Identity  REDACTED@REDACTED.COM
Starting a command on the remote server failed with the following error message : The WinRM client cannot process the
request. The authentication mechanism requested by the client is not supported by the server or unencrypted traffic is
disabled in the service configuration. Verify the unencrypted traffic setting in the service configuration or specify
one of the authentication mechanisms supported by the server.  To use Kerberos, specify the computer name as the
remote destination. Also verify that the client computer and the destination computer are joined to a domain. To use
Basic, specify the computer name as the remote destination, specify Basic authentication and provide user name and
password. Possible authentication mechanisms reported by server: For more information, see the
about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OperationStopped: (admined2.online.lync.com:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : JobFailure
    + PSComputerName        : admined2.online.lync.com

The fact that if you kick it off again it runs for ages says to me it is timing out of the imported PS Session so how do I work around this?  Can I check for session expiry or can I just re-authenticate every 10 minutes, pull in another session and then continue the user list?

The loop is just this:

$ALLUsers = Get-MsolUser -All | ?{ $_.isLicensed -eq "TRUE" }
$ALLUsersApply = $ALLUsers | ?{ ($_.Licenses | ?{ $_.AccountSkuId -eq $LicenseSelection}).Length -gt 0} | select SignInName
foreach ($User in $ALLUsersApply) {
    write-host "Grant-CsTeamsMessagingPolicy -PolicyName $PolicySelection -Identity " $User.SignInName
    Grant-CsTeamsMessagingPolicy -PolicyName $PolicySelection -Identity $User.SignInName
    write-host "Grant-CsTeamsMeetingPolicy -PolicyName $PolicySelection -Identity " $User.SignInName
    Grant-CsTeamsMeetingPolicy -PolicyName $PolicySelection -Identity $User.SignInName
       }

Thanks.

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

Help with what should be a simple script

$
0
0

I am attempting to write a script that will perform mass import of data into various fields in AD, however I can seem to get foreach portion of the script to work correctly.  I have CSV with a list of Distinguished Names, then I have several additional columns that I want to import into AD.  I believe the issue is with my ForEach statement, I want it to pull one entry from the distinguished name, then use the other columns from the same row, in my below script I've simplified it down to just write-host.

$UserList = Import-Csv -LiteralPath 'C:\Temp\ADEmployeeIDProject\Users.csv'

Foreach ($DistinguishedName in $UserList)
{
    Write-Host $UserList.Name
}

My test CSV has 6 lines, and instead outputting the Name on the row to the for each DN, it prints all 6 names, on 6 different lines.  I'm not sure what I have wrong here.  I did think it was because the distinguished name has comma's in it, an possible that was causing the issue, but if I Import-CSV it outputs the correct data in with the correct number of columns.

 

How to find if object is replicated or not

$
0
0

Hi family,

i am searching a methode to get if an object replicated from another DC or site, like user for exemple,

or when a do a request to a server i can detect an object if he is replicated or not.

Thanks,


Vertical Bar Graph Built in Powershell

$
0
0

I am needing to build a Vertical bar chart to graph locations and numbers. Below is a sample of the outcome we are looking for.

Below is the Script I already have. I think it needs some work!!

cls
# Load .Net Chart Control Assemblies  
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") 
# create chart object  
$Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart.Width = 800  
$Chart.Height = 700  
$Chart.Left = 40  
$Chart.Top = 30
$Chart.Anchor = 'Right,Top,Left' 
# create a chartarea to draw on and add to chart  
$ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea  
$Chart.ChartAreas.Add($ChartArea) 
# add title and axes labels 
[void]$Chart.Titles.Add("NET DDA Dashboard - " + (Get-Date -Format D))  
##$ChartArea.AxisX.Title = "Branches" 
$ChartArea.AxisX.Interval = 1 
$ChartArea.AxisY.Interval = 5
##$ChartArea.AxisY.Title = "Count" 

$items = Import-Csv 'C:\Users\user\Desktop\test.csv'

$Branches = @(foreach($item in $items){$item.Branch}) 
$Counts = @(foreach($item in $items){[Double]$item.Count}) 
 
[void]$Chart.Series.Add("Data") 
$Chart.Series["Data"].Points.DataBindXY($Branches,$Counts)
$Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::StackedBar
$Chart.Series["Data"].color = "#62B5CC"
$Chart.Series["Data"].color.Negative = "#9644"
# save chart to file 
$path = 'C:\Users\user\Desktop\'
$Chart.SaveImage($path + "\chart.png", "PNG") 

Get ADUser to export to CSV returning blank entries

$
0
0

Hello All,

I'm relatively new to Powershell and am trying to run a command to query certain ad groups, pull user informaiton, and return them in to a CSV. I'm getting a blank file output when I run the command. Can someone tell me what I'm doing wrong? Here's my command:

Get-ADUser -Filter * -properties name,Title, EmailAddress, Department  |select name,Title, EmailAddress, Department|where Department -eq "Finance", "Legal", "HR","Commercial", "Operations" |Out-File C:\Test\departments.csv -Encoding utf8


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.

How to perform chkdsk.exe /r and defrag.exe by Powershell ?

$
0
0

Hi,

Do anyone inform me how to use powershell to perform chkdsk/r and defrag in schedule ?

Since, it warns the disk is locked or in use. and not allow to execute until next boot

thanks

Convert Strings To Numbers

$
0
0
I have some script that outputs string values where they should be numeric values (with 2 decimal places) and I just need the script to output them with numeric values instead of strings with quotation marks around them.  Please help.

All Project Files are here.
https://mega.nz/file/4tckTQSB#voXExrndNk_PvDMC8880XjioVl946FVAu_i_uRZ4HZ0

Here's a video explaining how it works.
https://www.screencast.com/t/beLka3XBIdJr

The exported data needs to be in this format.
https://postimg.cc/dZLTcD0q

Thank you for your help.

Regards, PC User

Powershell -- Get-RandomCharacters not recognised

$
0
0

Hello

I'm having some major issues with powershell. Im trying to use the 'Get-RandomCharacters' module to generate a random string password. This works fine on my host PC, but when I execute this in my virtual machine ( Running microsoft server 2016) It's an unknown Module. Both versions are powershell 5.1.


Can this not be executed on Microsoft Server?

Do i need to install this module?

Please help

Thank you

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

Get-ItemProperty Error message

$
0
0

Hi all, Anyone can figure this one out? Why the error message?

Regards, Gideon.

# Change NIC Power Management value to 0 (Zero) If((Get-ItemProperty -path HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0001 -name PnPCapabilities -ea 0).pnpcapabilities) {‘Propertyalready exists’} ELSE { Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0001 -name PnPCapabilities -Value’0000’}

Error:

Get-ItemProperty : A positional parameter cannot be found that accepts argument '4D36E972-E325-11CE-BFC1-08002BE10318'.
At C:\Users\Administrator\Desktop\NIC.ps1:3 char:5
+ If((Get-ItemProperty -path HKLM:\SYSTEM\CurrentControlSet\Control\Cla ...


Using IF Condition Based on the Results

$
0
0

Hello,

I have following script which basically reads the sql server native client version and writes the output to the console. I want to change the color of the font to RED if the version is the right one and GREEN if it has the right version and may be possibly write additional word "and is TLS 1.2 compliant"

#Serverslist

$ServersList = Get-Content 'D:\PowerShellScripts\list.csv';

 #Checking SQL Server Native Client in registry

$Results = Icm -cn $Servers {Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\SQLNCLI11\CurrentVersion"| Select-Object @{n='ServerName';e={$_.pscomputername}}, Version

#Display results

If (Version -ge '11.4.7000.0') {

      WriteHost $Results -ForeGroundColor Green  -->"TLS 1.2 compliant"

   } else { WriteHost $Results -ForeGroundColor Red} -->"Not TLS 1.2 Compliant. Download the right version from https://www.microsoft.com/en-us/download/details.aspx?id=50402"

   }

$Results | Format-Table -AutoSize -Wrap

 Obviously, the above if statement is read correctly and need help to fix it. Will greatly appreciate your input.

Thanks in advance,

Victor


Victor

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


need help on a power shell script to filter with keywords and paste the data in new sheet.

$
0
0

A bit new to power shell but learning it fast, I have downloaded a content from a web url containing servers data like server name, env details, Site address, Country, I want to filter a column headed as "Country" and paste its filtered data in new sheet. So far i have the below script, please assist:-

Invoke-WebRequest -Uri "URL Address" -OutFile "C:\Users\tarwaniv\Desktop\file1.csv"
$import = get-content "C:\Users\tarwaniv\Desktop\file1.csv"
$import | select-Object -Skip 1 | Set-Content "C:\Users\tarwaniv\Desktop\file2.csv"
Import-csv -Path "C:\Users\tarwaniv\Desktop\file2.csv" -Header "#Active Servers", "Street Address" , "City", "Country"
@filter = @("#Active Servers", "City", "Country")


Viewing all 21975 articles
Browse latest View live


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