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

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 Month name

$
0
0

Hi,

I have a problem when I try to get the month day. For June I didn't have any problem but for this month it is not good.

$CurrentMonth = (Get-Date).month
$Current = (Get-Culture).DateTimeFormat.GetMonthName($CurrentMonth)
$Today = Get-Date -Format "dd-$Current-yyyy"
$Today

The result is:

02-Jul20-2020 -> I don't understand why I have Jul20, for last month the result is 02-June-2020.

I have tested all months and for a lot of them it is not working.

Have you any idea of this problem? How can I fix it?

Thank you.

T.

Error '0x80073701' while trying to install Containers Windows feature

$
0
0

Dear Community,

I'm facing an issue trying to install Windows Docker, more specifically its containers feature, to a Windows 2016 server.

I tried installing Docker using the following set of commands on Powershell ran as Admin:

Install-Module DockerMsftProvider -Force

cd C:\Users\s7qzqx\AppData\Local\Temp\DockerMsftProvider
Start-BitsTransfer -Source https://dockermsft.blob.core.windows.net/dockercontainer/docker-19-03-5.zip -Destination docker-19-03-5.zip
Get-FileHash -Path docker-19-03-5.zip -Algorithm SHA256
Install-Package -Name docker -ProviderName DockerMsftProvider -Verbose

And then restarting the server. The reason why I used the 3 commands in the middle is because the package couldn't be found and therefore installed.

Anyway, that seemed to work and I'm now able to check Docker version using 'docker --version' command.

The only thing that failed is adding the containers feature, which gives the following error:

WARNING: A restart is required to enable the containers feature. Please restart your machine.

Install-package : The request do add or remove features on the specified server failed.

Installation of one or more roles, role services, or features failed.

The referenced assembly could not be found. Error: 0x80073701

At line:1 char:1

+ Install-Package -Name docker -ProviderName DockerMsftProvider -Verbos ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo            : InvalidOperation: (@{Vhd=; Credent...Name=localhost}:String) [Install-Package], Exception

+ FullyQualifiedErrorId : DISMAPI_Error__Failed_To_Enable_Updates,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureCommand,Microsoft.Powershell.PackageManagement.Cmdlets.InstallPackage

(I can't insert images because my account is not verified for some reason)

The same error happens even after restarting the machine and running this command: 'Install-WindowsFeature -Name Containers'.

I found online that it might have to do with some registry entries in "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\PackageDetect" that were created and orphaned and that the solution would be to delete them, but personally I'm afraid to delete Windows registry entries without fully knowing what I'm doing.

Do you know if there's a precise way to know what to delete and what to not touch, or if there's any other solution/workaround to fix this error and complete Docker's installation?

Thanks a lot in advance,

Nicolò

unable to extract particular element from object[]

$
0
0

I have output from $a as 

$a

Name  Collage Marks Address Date
----  ------- ----- ------- -----
Andra   JKI     78.9  RRRR    5/15/2020 3:10 PM
Prakash TYU     67.9  EWSR    6/15/2019 6:10 PM
Amit    ERT     88.9  RRFR    6/15/2020 7:10 AM
Nobel   VFR     33.9  TTT     2/15/2020 3:10 PM

$a.gettype()
IsPublic ISSerial Name       BaseType
------- -------- ------      --------
True     True    Object[]    System.Array

I am unable to exract name or line Amit with Marks 88.9
due to Object[] no success 

I have tried all like  
$a=$a | ? {$_.Name -ilike "Amit"} OR contains  

I convert $a to string or to convertto-json but the json is weared and have no value of any of the fields 

also tried echo ($a | select -ExpandProperty "Name") OR $a."Marks" OR $a.PSObject.Properties |  ? isGettable| select-object -Property Name but no names are sorted 

Exchange MS v2.0 Exporting to CSV -append Error

$
0
0

Hi - I am trying to import a list of users, get mailbox permissions and export results to a .csv file. If i have just one name in the input file it works as soon as I have multiple it does not.If I use -append it errors (I believe it is cause I am using version 2.0 of PS EMS) any suggestions?

$users = get-content “mailboxusers.txt”
foreach ($user in $users) {
Get-MailboxPermission -identity $user | where {$_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false} | Export-Csv MailboxAccess.csv;
}

Deleted

Deleted

High CPU Usage Running PS Scripts on Windows Server 2016 after applying KB4556813

$
0
0

Hello,

We patched one Windows Server 2016 Standard edition with KB4556813 and after this patch, all of our PowerShell scripts running on this server started generating 100% CPU usage.

Basically, this server is a monitoring satellite ( Icinga2 service) which is running couple of hundred PS scripts with PS Remote. It is checking some specific values on the remote Windows servers and is reporting back to our monitoring their status. 

Prior to this update and now after removing KB4556813 all scripts are running fine, with low to none CPU usage. 

For example, below is how one script is started and we can see it got killed after not responding for 60 seconds:

[2020-06-30 14:33:00 +0200] warning/Process: Killing process group 1216 
('C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "& C:\ProgramData\icinga2\var\lib\icinga2\api\zones\global-windows\_etc\plugins\PS1\check_sepm_av.ps1" 
-credential DOMAIN\svc_user__monitoring%thepasswordfortheuser= -target MY-SERVER-PRODUCTION') after timeout of 60 seconds

PS. I understand that icinga2 is not a Microsoft product, but what it does is the as Task Scheduler would do.

Anyone any ideas ? Thank you in advance!


Mario Patov


add-odbcDSN for Azure database with Encrypted=yes

$
0
0

Hey!

Posting this here and on SQL Server Data Access forum, I believe it relates to both. 

I'm trying to create user dsn for Azure DB. The script I'm using right now is:

Add-OdbcDsn -Name "DSNNAME" -DriverName "ODBC Driver 17 for SQL Server" -DsnType "User" -SetPropertyValue @("Server=servername.database.windows.net", "Trusted_Connection=Yes", "Database=dbname", "Authentication=ActiveDirectoryIntegrated", "Encrypt=Yes")


While this command ends with success, I can't connect using this datasource, I'm getting the following error:

Exception calling "Open" with "0" argument(s): "ERROR [FA001] [Microsoft][ODBC Driver 17 for SQL Server]Cannot use Authentication option with Integrated Security option.
ERROR [FA001] [Microsoft][ODBC Driver 17 for SQL Server]Cannot use Authentication option with Integrated Security option."

The way to fix the DSN is to open the ODBC data source Admin, click on the datasource, then configure, then go through the wizard without any single change. Looks like wizard is writing some properties under the hood. 

I tried to compare properties before and after, and here is what I got:

BEFORE THE WIZARD: 

Get-OdbcDsn  -Name DSNNAME | select -expandproperty attribute

Name                           Value
----                           -----
TrustServerCertificate         Yes
Database                       dbname
Server                         servername.database.windows.net
Trusted_Connection             Yes
Authentication                 ActiveDirectoryIntegrated

AFTER THE WIZARD:

Get-OdbcDsn -Name DSNNAME | select -expandproperty attribute Name Value ---- ----- KeystoreSecret Encrypt Yes ClientCertificate Database dbname Server servername.database.windows.net TrustServerCertificate Yes KeystoreAuthentication KeystorePrincipalId KeystoreLocation Authentication ActiveDirectoryIntegrated

As you can notice, I have few properties added: 

  • KeystoreSecret
  • ClientCertificate
  • KeystoreAuthentication
  • KeystorePrincipalId
  • KeystoreLocation

but their values are not shown. How can I set them? These must be some system/user default as I don't see any corresponding input on the ODBC GUI. 

Could someone advice what I miss here?

Regards 

Olek 


Test-Path difference between -Path and -LiteralPath when using a "literal" path

$
0
0

I frequently use the -Path argument for Test-Path and pass in a full/static/literal path, like C:\Temp\FileName.txt.  The path does not contain spaces, and is passed as a variable.  Test-Path -Path $PathVar.

I have not used the -PathType argument.

PowerShell version 5.1

I've recently had some issues accessing network resources using PSDrive for the connection, where using the -Path argument returns not found or generates an Access Denied error.  If I change to -LiteralPath, with the same value, Test-Path behaves as expected.

What is the difference?

Just curious...


PowerShell - Get Folder ID from String

$
0
0

Hi All,

I am trying to write a powershell script that will get the contents of a folder which contains zip file and then move these to the corresponding folders.

For example d:\datadownload contains;

data-230809_0008888.zip
data-230809_0008878.zip

I wont a script that will move the file data-230809_008878.zip to d:\data\0008878.

The script doesn't need to unpack it but just needs to move it.

[string[]]$files = Get-ChildItem -Path "d:\datadownload" | Select -ExpandProperty name

foreach($file in $files)
{
    [string[]]$folder = $file.Split("_",8)
    write-host $file.Split("_")
}

This is what I have currently started with but I can't figure out how to remove everything other than the bit of information that I need.

Could someone point me in the right direction of where to go next. I was looking at using some kind of 'substring' but there doesn't seam to be a substring option in PowerShell.

Regards,

Tom


TPark IT Technician

Active Directory PowerShell Issue

$
0
0

Hi

I have an issue with Powershell and the Active Directory Module.  When trying to load the Active Directory Module I get the following error :

import-module : The server was unable to process the request due to an internal error.  For more information about the
error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug>
configuration behavior) on the server in order to send the exception information back to the client, or turn on
tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
    + CategoryInfo          : NotSpecified: (AD:PSDriveInfo) [Import-Module], ADException
    + FullyQualifiedErrorId : ADProvider:NewDrive:InvalidRoot:ADError,Microsoft.PowerShell.Commands.ImportModuleComman
   d

Any help is greatly appreciated.

Regards

Mark

ACL System.Security.AccessControl.FileSystemRights permissions level

$
0
0

Hi,

I want to set folder permissions to two folders "f:\first" and "f:\first\second"     On the "first folder" the user has to have "FullControl" permissions, on the "second" folder I want the user having "Read" permissions.

I also don't want that changing the permissions to read/write in the first folder of a new user is going to change the permissions on the second folder to the old users already there.

I have run this script 

#For the folder first

    

       $acl = Get-Acl $homeShare

    $FileSystemRights = [System.Security.AccessControl.FileSystemRights]"FullControl"
    $AccessControlType = [System.Security.AccessControl.AccessControlType]"Allow"
    $InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"


    $AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User, $FileSystemRights,      $InheritanceFlags, $PropagationFlags, $AccessControlType)
    $acl.AddAccessRule($AccessRule)

    Set-Acl -Path $homeShare -AclObject $acl -ea Stop

# for the second folder

      $acl2 = Get-Acl $homeShare

    $FileSystemRights2 = [System.Security.AccessControl.FileSystemRights]"Read"
    $AccessControlType2 = [System.Security.AccessControl.AccessControlType]"Allow"
    $InheritanceFlags2 = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
    $PropagationFlags2 = [System.Security.AccessControl.PropagationFlags]"InheritOnly"


    $AccessRule2 = New-Object System.Security.AccessControl.FileSystemAccessRule ($User, $FileSystemRights2,      $InheritanceFlags2, $PropagationFlags2, $AccessControlType2)
    $acl2.AddAccessRule($AccessRule2)

    Set-Acl -Path $homeShare -AclObject $acl2 -ea Stop

I run both in the same script, It all goes through without error and "First" folder is set to read/write for the user but "second"

is set to "custom" . Any idea what I should change?

Thanks

Task Scheduler, Execute powershell script with a command

$
0
0
I have a powershell api script that changing wifi passwords in Meraki.
Now i want to add this script to Task Scheduler and execute it with a specific command line, for example:

In "Action" section i'm always putting those lines:

    Program/script : Powershell.exe
    Add arguments : -ExecutionPolicy Bypass C:\Policies\Meraki\ChangePass.ps1

But this won't work here, because this script can be executed only when using this command:

    .\ChangePass.ps1 -site "Building1" -ssid "Wifi-Guest" -action "Change"

Thanks for help

How to delete printer in a domain user profile

$
0
0

Hi,

iam new into powershell. Iam trying to figure to remove all printers on a workstation/domain user

I have written a small script where i get the list of all the printer on a domain. Removed any policies which removed all the printers but some user have installed manually the printers (shared) and local printers. Somehow the script does not show them. I ran is admin and highest level of domain administrator no luck. I cannot believe that as an administrator i cannot see or delete those printers via power shell.

See script for making a list which printer is installed on which computer. I will modify the result then delete those printers. Like mention shared and local printers do not show up. 

Get-Content -Path c:\ListOfComputers.txt | ForEach-Object {
if (Test-Connection $_ -Count 1 -Quiet) {
Get-Printer -ComputerName $_ | Select-Object -Property Computername,Name | Export-Csv -Path c:\PCPrinterList.csv -NoTypeInformation -Append
} else {"Computer $_ offline" >> c:\OfflinePCs.txt
}
}


This scripts would remove the printers according to list

Import-Csv c:\PCPrinterList.csv |`
    ForEach-Object {
	Remove-Printer -ComputerName $_.ComputerName -Name $_.Name
}

Any idea how can get it done in powershell? 

Indian



Unable to install multiple KBArticle on window Servers

$
0
0

Hi Support,

I am unable to install multiple KBArticle on Widows Servers but this command is working fine.

Working Command:

Install-WindowsUpdate -KBArticleID KB4535104 -Confirm:$false -AutoReboot

Error Command: When adding multiple KBArticle

Install-WindowsUpdate -KBArticleID KB4535104,KB4486105  -Confirm:$false -AutoReboot

A parameter cannot be found that matches parameter name 'Title' when updating Exchange users via powershel

$
0
0

# Updates Exchange user attributes from CSV file

$Credential = Get-Credential Connect-ExchangeOnline -Credential $Credential # Load data from file.csv $EXUsers = Import-csv file_path # 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-EXUser splatting: $GetParams = @{ Identity = $User.Username } # Initialize hash table for Set-ADUser splatting: $SetParams = @{ Title = $User.Title } # Check to see if the user already exists in AD. If they do, we update. if ( Get-EXORecipient @GetParams) { # Set User attributes Set-User @SetParams -WhatIf # 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:

A parameter cannot be found that matches parameter name 'Title'.+ CategoryInfo          : InvalidArgument: (:) [Set-User], ParameterBindingException+ FullyQualifiedErrorId : NamedParameterNotFound,Set-Mailbox+ PSComputerName        : outlook.office365.com

I have written a script to update Exchange user mailbox attributes but I get this error.

I think I am using the wrong cmdlet but I am not sure which one I need to update the title

attribute.



Powershell script to append multiple entries on Windows Hosts file to list of servers?

$
0
0
I Have a list of servers which requires adding 2 entries on hosts file remotely but could'nt find the script.

CSV Files Error: "String was not recognized as a valid DateTime."

$
0
0

I have an odd one. I have written a script that will work through a bunch of csv files which are being generated from a Nimble Infosight lab, determine the hours to be between 07:00 and 17:55 and give me the max, min and average of the read, write iops and read, write throughputs.

It has worked previously fine.

For some reason, there are certain csv files where i am getting an error saying the below. Out of a folder with 22-23 csv files, maybe 2-5 do not work now for some reason I cannot work out:

Cannot convert value "13/04/2020 03:31" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At C:\Temp\IOPsWeekdays.ps1:16 char:5
+     (([datetime]$_.ts).Hour -gt 7 -and ([datetime]$_.ts).Hour -lt 17) ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

Here is the script I am using:

#run the below cmd in an elevated powershell cmd window to allow unsigned scripts to execute
Set-ExecutionPolicy unrestricted

#set path to pick up ,csv`s
$Path = "C:\Users\blahblah\\Servername\volumepool\volume\April"

$Files = Get-ChildItem -Path $Path -Filter '*.csv' | Select-Object FullName

Write-Output  "Processing $($Files.count) Files"

foreach ($File in $Files)
{
    Write-Output $File.FullName
    $csv = Import-Csv -Path  $Files.FullName | 
    Where-Object{
    (([datetime]$_.ts).Hour -gt 7 -and ([datetime]$_.ts).Hour -lt 17) -or 
    (([datetime]$_.ts).Hour -eq 17 -and ([datetime]$_.ts).Minute -lt 55)
                }
    $csv.read_iops | measure -Maximum
    $csv.read_iops | measure -Minimum
    $csv.read_iops | measure -Average
    $csv.write_iops | measure -Maximum
    $csv.write_iops | measure -Minimum
    $csv.write_iops | measure -Average
    $csv.read_mbps | measure -Maximum
    $csv.read_mbps | measure -Average
    $csv.write_mbps | measure -Maximum
    $csv.write_mbps | measure -Average
}

I can try and add a couple of csv files if this lets me add attachments later.

Any help would be appreciated.

Thanks

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.

Viewing all 21975 articles
Browse latest View live


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