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

DataGridView Events

$
0
0

I created the following event handlers. When clicking on a cell, OnClick_Cell is called. When clicking on a column header, OnClick_CollumnHeader is called but at the same time, OnClick_Cell is also fired. Is it something special? Thanks

Function OnClick_Cell() { Write-Host 'Cell Clicked' }
Function OnClick_CollumnHeader() { Write-Host 'Header Clicked' }
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(600,400)
$DataGridView = New-Object System.Windows.Forms.DataGridView
$DataGridView.Location =  New-Object System.Drawing.Point(5,25)
$DataGridView.Size = New-Object System.Drawing.Size(565,410)
$DataGridView.Add_CellClick({OnClick_Symbol})
$DataGridView.Add_ColumnHeaderMouseClick({OnClick_CollumnHeader})
$col1 = New-Object System.Windows.Forms.DataGridViewTextboxColumn
$col1.Name = 'Col1'
$col1.Width = 50
$DataGridView.Columns.Add($col1)
$col2 = New-Object System.Windows.Forms.DataGridViewTextboxColumn
$col2.Name = 'Col2'
$col2.Width = 50
$DataGridView.Columns.Add($col2)
$Form.Controls.Add($DataGridView)
$Form.ShowDialog()



Powershell - run command in Batches of 100 -SOLVED

$
0
0

I have this code to export Subscription IDs to CSV

 $custIDs = Get-MicrosoftPartnerCustomers

foreach ($custID in $custIDs)

{ $custID | Out-File -FilePath "c:\organization.csv" -Append  }

How to run above command in batches of 100 until all of IDs are reached ?



A script that gives leaders mail on the things they are in charge off. (Im new to powershell)

$
0
0
I want to make a script that gives leaders an email on the things that they are in charge off. This most likely have to have some connection to AD? Pretty new to this so any tips is highly appreciated.

Identity Powershell process started via Scheduled Tasks

$
0
0

Hi,

as the Title suggests i am having multiple powershell scripts which are started via schedulded tasks on W2k16 Host. They are all set to run wheater a user is logged on or not.

I now need to identify which process in get-process is which powershell script. Unfortunatly this is not this easy.
I tried to set a custom title via $host.ui.RawUI.WindowTitle in each script but this is only working if they are started when a user is logged on and the scheduled task ist set to "start only when user is logged on".

it seams as the $host.ui is not loaded when the task is set to "run wheater user is logged on or not"

Any ideas how to identify the correct processes?

Replace exact string in multiple files in multiple folders.

$
0
0

Hi, 

This question has been asked multiple times and i was wondering if there is better pattern these days. it's almost 2020 :) 
So, the pattern below is pretty straight forward. We get all the files in folders and sub-folders and replace and save the new content in a loop. 

In my case, my $old value var got some brackets and brackets must be escaped otherwise the look up value is not going to be picked up by -replace  operator.  

'Product Values'\[ProductName\]

$old = "'Product Values'\[ProductName\]"
$new = "'Product Values'[ProductFullName]"

$path = 'C:\backup\*.txt'

Get-ChildItem -Path $path -Recurse |  
ForEach
{ 
  (Get-Content $_) -replace $old, $new |
   Set-Content $_
}

Any suggestion how this can be improved ?

Thanks


CMD does not recognize desktop as a directory path

$
0
0

I am trying to go from C:\Users\Aubri> to C:\Users\Aubri\Desktop> using "cd Desktop" or "cd desktop"

however I get the error message saying the system cannot find the path specified. I'm not sure why this is, I can use cd .. and go back to a parent directory, but cannot move to the desktop form the user directory. Is there something I'm doing wrong?

Invoke-WebRequest - how to print specific field

$
0
0

Hi,

I have VoIP phones those have web page, 

I want to get the serial number of each phone device,

how can I get only this field using Invoke-WebRequest 



استدعاء-WebRequest

Script to delete after

$
0
0
I have got a script and it works ok but I want to add more command to empty the folder when all these tasks finished but not sure how as I tried to add Remove-Item -path 'E:\id\Upload\* it doesn't seem to work. Could someone please advise? param ( $localPath = "E:\id\Upload\*.*", $backupPath = "E:\id\Archive", $backupPath2 = "E:\id\Archive2", ) try { # Connect $session.Open($sessionOptions) # Upload files, collect results $transferResult = $session.PutFiles($localPath, $remotePath, $False, $transferOptions) # Iterate over every transfer foreach ($transfer in $transferResult.Transfers) { # Success or error? if ($transfer.Error -eq $Null) { Write-Output "$(Get-Date) Upload of $($transfer.FileName) succeeded, moving to backup">> $logFile # Upload succeeded, move source file to backup Move-Item $transfer.FileName $backupPath Move-Item $transfer.FileName $backupPath2 } } }

Set-ADUser to modify givenname and surname attributes based upon displayname in powershell

$
0
0
Hello to everyone,

i'm trying to restore AD Users records to a proper shape.

More in details,current AD users records contains only the displayname and the other mandatory attributes,everything is lacking (like givenname,surname,telephonenumber,address,city,country ecc. ecc.)

Actuallly,i'm trying to achieve three results:

1 - Populate at least the Givenname and Surname from the displayname attribute (since this one is "name-space-surname")

2 - Populate the address,country,city based on the OU's membership

3 - populate the phonenumber attribute from a csv that i'm trying to build from mixing various others excel files

I need help for the first one.

An example of a displayname that i have is like:

"test1 Test2"

What i'm trying to do is to extract "test1"and assign as "Givenname" and extract "test2" and assign it as "surname"

How can i use Set-aduser to achieve what i want?

Thanks for any reply


Create powershell object using dynamic properties

$
0
0

In my scripts I often need to use a lot of data that I read from the AD or other resources.
I then make use of specific filters and/or properties to get the data I need.

After that I create a PSobject with that data using foreach.
Look at the sample below to give an idea with whay i mean.

 
$Report = foreach ($user in $Users) 
            {

             New-Object -typename PSObject -property @{
             'Login' = $user.samaccountname
             'Organization' = $user.company
             }

            }

My question about this is:

The property part (marked bold in script block) is something I want to build before the foreach command starts, using custom given array's.
So something like this:

[array]$names = "Login","Organization", ...
[array]$items = "Samaccountname","company", ...

Create and use the property part using??????

Tried allready different things with add-member, but can't find a good solution.

With this solution I could build a template for building an import for different kind of data sets using just dynamic parameters.
Instead of scripting it everytime from scratch.
And I think it can be used in many other circumstances.

I hope you guys have an answer for this!

 

PowerShell Script to Get the Objects schema Backup

$
0
0

Hi All,

I am using below power shell script to get the all the Objects Schema backup. It is working fine to get all the objects. Now we need to filter the objects based on object create date. which is not working .Could any one please help on this.

"

 foreach ($objs in $db.$Type | Where-object {-not $_.IsSystemObject -and $_.create_date -gt $date_ })

"

In the above  $_.create_date -gt $date_  condition is not working . Below is the total powershell script.

# this will filter systme databses and system tables

$date_ = (date -f yyyyMMdd)
$currentDate = Get-Date
$ServerName = "." #If you have a named instance, you should put the name. 
$path = "c:\SQL_Server\Backup\Objects\"+"$date_"
 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $ServerName
$IncludeTypes = @("Tables","StoredProcedures","Views","UserDefinedFunctions", "Triggers") #object you want do backup. 
$ExcludeSchemas = @("sys","Information_Schema")
$so = new-object ('Microsoft.SqlServer.Management.Smo.ScriptingOptions')

 
$dbs=$serverInstance.Databases | Where-Object {!($_.Name -in ("master","model","msdb","ReportServer","ReportServerTempDB","tempdb"))}  #you can change this variable for a query for filter yours databases.
foreach ($db in $dbs)
{
       $dbname = "$db".replace("[","").replace("]","")
       $dbpath = "$path"+ "\"+"$dbname" + "\"
    if ( !(Test-Path $dbpath))
           {$null=new-item -type directory -name "$dbname"-path "$path"}
 
       foreach ($Type in $IncludeTypes)
       {
              $objpath = "$dbpath" + "$Type" + "\"
         if ( !(Test-Path $objpath))
           {$null=new-item -type directory -name "$Type"-path "$dbpath"}
#              foreach ($objs in $db.$Type | where {!($_.IsSystemObject)})
               foreach ($objs in $db.$Type | Where-object {-not $_.IsSystemObject -and $_.create_date -gt $date_ })
              {
               
                     If ($ExcludeSchemas -notcontains $objs.Schema ) 
                      {
                           $ObjName = "$objs".replace("[","").replace("]","")                 
                           $OutFile = "$objpath" + "$ObjName"+ ".sql"
                           $objs.Script($so)+"GO" | out-File $OutFile
                      }
              }
       }     
}



Thanks and Regards Rajesh

Deploying IP based printers using Powershell

$
0
0

Hello all,

I'm currently trying to deploy some printers using Intune.

What I did so far is to create an .msi intaller using Advanced Installer to push the driver files (including the .inf) onto the client W10 devices. That worked just fine and I now have the files locally on each device.

After that, I did try to run a Powershell command on each device to add the driver to the driver repository and ultimately adding the printer, but I'm running into some strange problem.

First, here' the script I'm using:

$driver = "KONICA MINOLTA C754SeriesPCL"
$address = "192.168.XX.XX"
$name = "PRINTER"
$sleep = "3"



# The invoke command can be added to specify a remote computer by adding -computername. You would need to copy the .inf file to the remote computer first though. 
# This script has it configured to run on the local computer that needs the printer.
# The pnputil command imports the .inf file into the Windows driverstore. 
# The .inf driver file has to be physically on the local or remote computer that the printer is being installed on.

Invoke-Command {pnputil.exe -a "C:\%UserProfile%\AppData\Roaming\Folder_XY\Advanced_Print_C754e\KOAYSJ__.inf" }


Add-PrinterDriver -Name $driver

Start-Sleep $sleep

# This creates the TCP\IP printer port. It also will not use the annoying WSD port type that can cause problems. 
# WSD can be used by using a different command syntax though if needed.

Add-PrinterPort -Name "PRINTER-PORT_XY" -PrinterHostAddress $address

start-sleep $sleep

Add-Printer -DriverName $driver -Name $name -PortName $address

And here's what I get:

PS C:\WINDOWS\system32> D:\!INTUNE\Print\Enable_Advanced_Print32.ps1MicrosoftPnPUtilityAdding the driver package failed :Invalid INF passed as parameter.Total attempted:0Number successfully imported:0Add-PrinterDriver:The specified driver does not exist in the driver store.At D:\!INTUNE\Print\Enable_Advanced_Print32.ps1:22char:1+Add-PrinterDriver-Name $driver+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:NotSpecified:(MSFT_PrinterDriver:ROOT/StandardCimv2/MSFT_PrinterDriver)[Add-PrinterDriver],CimExcep
   tion+FullyQualifiedErrorId: HRESULT 0x80070705,Add-PrinterDriverAdd-PrinterPort:The specified port already exists.At D:\!INTUNE\Print\Enable_Advanced_Print32.ps1:29char:1+Add-PrinterPort-Name $name -PrinterHostAddress $address+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:ResourceExists:(MSFT_PrinterPortTasks:ROOT/StandardCimv2/MSFT_PrinterPortTasks)[Add-PrinterPort],Ci
   mException+FullyQualifiedErrorId: HRESULT 0x800700b7,Add-PrinterPortAdd-Printer:The specified driver does not exist.Use add-printerdriver to add a new driver,or specify an existing driver.At D:\!INTUNE\Print\Enable_Advanced_Print32.ps1:33char:1+Add-Printer-DriverName $driver -Name $name -PortName $address+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:NotSpecified:(MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer)[Add-Printer],CimException+FullyQualifiedErrorId: HRESULT 0x80070705,Add-Printer

As you can see right at the beginning, the pnputil states that the .inf file is invalid (although it shouldn't). I guess this initial error leads to the others where Powershell says that the "specified driver does not exist in driver store".

Any idea what could be causing this? I'm using the .inf file directly from the driver package provided by Konica Minolta: www.konicaminolta.eu/eu-en/support/download-centre

  • bizhub C754e
  • Driver: English (W10 32bit)
  • Driver Version: 5.4.0.0
  • Driver Emulation: PCL6

I've also tried using the 64bit version, but without success.

As reference, here's the original thread in the Intune forums: https://social.technet.microsoft.com/Forums/en-US/14d74f51-1850-4a69-a776-3319897193ca/deploying-ip-based-printers-using-intune?forum=microsoftintuneprod

Honestly, I'm kinda lost here since the script itself should work; it might be related to the driver/inf file?

Thanks!

error 18456 on secondary node alwayson with powershell

$
0
0

Hi all,

i get the error in object when try to launch a powershell script that remove from AG some db.

Configuration is following:

- 1 domain user added as administrator locally on both 2 node;

- powershell script is invoked by jenkins scheduler. Domain user is stored on jenkins scheduler;

- on both sql server domain user is sysadmin.

So script work fine on primary node, remove db from ag and after delete it. When i try to launch script from primary node to secondary doesn't work, i got error in attach with "login failed for NT AUTHORITY\ANONYMOUS LOGON".

user and password for security are not hardcoded into the script. Into the script there is integrated security = true. We tried with integrated security = SSPI but got same error. If we put integrated security = false it works on secondary node.

What are doing wrong?

Thanks

SQL Server Agent Jobs - Change the Run As property in all job steps

$
0
0
Question
You cannot vote on your own post
0
For SQL Server Agent, can someone guide me with a PowerShell script to change the value of the Run As property from "Proxy X" to "Proxy Y" in all job steps of type SSIS or CmdExec in all jobs on an instance?  Thanks!

invoke-ascmd error does not trigger catch

$
0
0

I run this command to backup a database to a network path.
Invoke-ASCmd -Server $ASServer -Query ($ASBackupQry.Replace('$(Database)', $Database))

I know the path does not exist and will trigger the an error
<return xmlns="urn:schemas-microsoft-com:xml-analysis"><root xmlns="urn:schemas-microsoft-com:xml-analysis:empty"><Exception xmlns="urn:schemas-microsoft-com:xml-analysis:exception" /><Messages xmlns="urn:schemas-microsoft-com:xml-analysis:exception"><Error ErrorCode="-1056833536" Description="File system error: The following error occurred during a file operation:  An unexpected network error occurred. . (networkpath.abf)." Source="Microsoft SQL Server 2016 Analysis Services" HelpFile="" /></Messages></root></return>

I run this in a try/catch, but it does not trigger the catch.  $ErrorActionPreference is set to stop.  My work around is to send the output to a string object and then search for exception and trigger the catch manually. 

Am I doing something wrong?


Invoke-RestMethod Issues

$
0
0

I am trying to connect to an external api website. I don't know details around how REST/JSON works, but I want to use powershell to download a csv file via GET method. I could successfully connect via CURL, but with powershell I cannot, and am exhausted.

CURL:

curl.exe -v -H "Accept: application/json" -u APIKEY: "https://"

Powershell:

Invoke-RestMethod -Uri 'https://' -Headers @{"AUTHORIZATION"="Basic "} -Method Get

I always receive following error:

the underlying connection was closed an unexpected error occurred on a send and the underlying connection was closed an unexpected error occurred on a receive

I tried using following script for certificate:

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

Source: http://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error

still no luck.

Can someone help me understand what I am doing wrong?

Update# 2:

Basic is followed by Base64Encoded API KEY. This is what I see when I use the API Web, the one website provides:

{
"Accept": "application/json",
"Authorization": "Basic Base64Encode",
"Content-Length": 0,
"x-forwarded-for": "Source IP"
}

I upgraded to v4

PS C:\> $PSVersionTable.PSVersion

Major Minor Build Revision
—– —– —– ——–
4 0 -1 -1

and also used:

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

since TLS1.2 is the requirement, still same error:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a receive.
At line:1 char:1
+ Invoke-RestMethod -Method Get -Uri 'https:////// ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], We
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

If I don't use https, then it says:

Unable to connect to the remote server

GetCMDevice results to pass to Get-ChildItem

$
0
0

Hello,

I have the script:

Get-CMDevice -CollectionID UCP0088F | ForEach-Object {$_.Name} 
$Name = {$_.Name}
$DeptIDsAllowed 
Get-ChildItem "\\$Name\C$\Program Files\CCSI\800\8001\OBIXConfig\defaults.ini" |
 Get-Content | Select-String "DeptIDsAllowed=*"


But it does not work the Names resulting from the Get-CMDevide are not passed to the Get-ChildItem.

I have an error

Get-ChildItem : Cannot find path '\\$_.Name\C$\Program Files\CCSI\800\8001\OBIXConfig\defaults.ini' because it does not exist.
At line:4 char:1+ Get-ChildItem "\\$Name\C$\Program Files\CCSI\800\8001\OBIXConfig\defa ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (\\$_.Name\C$\Pr...ig\defaults.ini:String) [Get-ChildItem], ItemNotFoundException+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

How to pass the machine name(s) issued from the Get-CMDevice to the UNC path in Get-ChilItem?

Thanks,

Dom


Security / System Center Configuration Manager Current Branch / SQL

How To Search For Multiple Patterns Found In A Specific Order Within A Node

$
0
0

Hi,

I have multiple xml files in a folder.  I want to get the filename of the files that have patterns found in a specific order.  Here is my xml file example.

<SyncDQEMAXGROUP xmlns="http://www....>
  <DQEMAXGROUPSet>
    <MAXGROUP>
      <APPLICATIONAUTH>
        <APP>PO</APP>
        <APPLICATIONAUTHID>154676</APPLICATIONAUTHID>
        <CONDITIONNUM />
        <OPTIONNAME>STOPWF</OPTIONNAME>
      </APPLICATIONAUTH>

And I want to find all files that have APP=PO AND OPTIONNAME=STOPWF in the APPLICATIONAUTH node.  I know how to search for multiple patterns, I just don't know how to search for multiple patterns found in a specific order in the same node. Not sure if it's possible, but if someone knows how, PLEASE let me know.

Powershell Scripts in the Windows 10 OS and script execution policy of "Allow only Signed scripts"

$
0
0

We have the group policy " Turn on Script execution" enabled and set to "Allow only Signed scripts".  

Will this affect the powershell scripts used in the Windows 10 operating System or does windows have something inbuilt that overrides the settings we apply.  I'm thinking that it would block even the W10 built in scripts.  

An example of what I am talking about are the 246 .ps1 files in the various diagnostic directories in c:\windows\diagnostics\system\ .  our diags never come back with issues even when deliberately disabling components before running.  

other areas that Powershell scripts live that I have found with a quick search - 

C:\Windows\WinSxS\wow64_microsoft.powershell.odatautils_31bf3856ad364e35_10.0.17763.1_none_d60dcab1d9234fab

C:\Program Files (x86)\WindowsPowerShell\Modules\Microsoft.PowerShell.Operation.Validation\1.0.1\Diagnostics\Comprehensive

C:\Program Files\WindowsPowerShell\Modules - various folders in here.  

Do we need to sign all powershell scripts that come with the OS?

Does Microsoft have a method of doing this? 

Is there a list of script files that come with the OS so we don't just do a sign all approach, then find we have signed malware files.  

we could probably configure something in the build task sequence to sign what is there initially.  Is there any plan in place for Microsoft to start signing their scripts?

Will this be an ongoing process as updates are applied and files replaced, do we need to have a process in place to sign all PS1 files in the OS?


MCSA, MCSE

Task Scheduler PowerShell Script

$
0
0

I have a script that finds a specific process, if it is running, terminate, wait x seconds, run the program again. When I test in PowerShell, it works as designed. However, I add the script to Task Scheduler it does not work. 

Script Example:

(Get-WmiObject -Class Win32_Process -Filter "Name = 'notepad.exe'").Terminate();
Start-Sleep 10
Start-Process -FilePath "C:\Windows\notepad.exe"

Not sure if that is the correct path to start-process but it's just an example. 

Task Scheduler Setup (Export XML):

<?xml version="1.0" encoding="UTF-16"?><Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Date>2019-10-15T16:02:32.6662873</Date><Author>Domain\Username</Author><URI>\RestartNotepadDaily</URI></RegistrationInfo><Triggers><CalendarTrigger><StartBoundary>2019-10-15T04:00:00</StartBoundary><Enabled>true</Enabled><ScheduleByWeek><DaysOfWeek><Monday /><Tuesday /><Wednesday /><Thursday /><Friday /></DaysOfWeek><WeeksInterval>1</WeeksInterval></ScheduleByWeek></CalendarTrigger></Triggers><Principals><Principal id="Author"><UserId>SID GUID HERE</UserId><LogonType>Password</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>true</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>false</StartWhenAvailable><RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable><IdleSettings><StopOnIdleEnd>true</StopOnIdleEnd><RestartOnIdle>false</RestartOnIdle></IdleSettings><AllowStartOnDemand>true</AllowStartOnDemand><Enabled>true</Enabled><Hidden>false</Hidden><RunOnlyIfIdle>false</RunOnlyIfIdle><DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession><UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine><WakeToRun>false</WakeToRun><ExecutionTimeLimit>PT2H</ExecutionTimeLimit><Priority>7</Priority><RestartOnFailure><Interval>PT1M</Interval><Count>20</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>PowerShell.exe</Command><Arguments>-NoProfile -ExecutionPolicy Bypass -File "c:\scripts\NotePadRestartDaily.ps1"</Arguments></Exec></Actions></Task>

Can anyone provide me with some suggestions on why I cannot get this to work? I have been bashing my brain for the past month trying different things to no success.

Server Version: Windows Server 2015 Datacenter v1607 (Azure VM)

Viewing all 21975 articles
Browse latest View live


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