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

Copy cell from Excel

$
0
0
Good morning, I need help writing a script that copies a single cell from excel, cell B20 to cell B1.

Powershell Export to csv or text file

$
0
0

Hi All,

I am querying AD to get the group details and I want to output to be in the below format. Is it possible via powershell?

NAME Members AD STATUS
Group 1 Member 1 Active
  Member 2 Inactive
  Member3 Active
Group 2 Member 1 Active
  Member 2 Active
Group 3 Member 1 Active

Kindly assist. Thanks.


Rajesh

Getting Values from DataGridView

$
0
0

Hello guys,

I have created a Data Grid view were users will put personal information on it. I'm trying to get that data and save it into a variable but I don't know how to navigate through it, could you please help me with this?

The data grid view contains:

Lastname | Name | Phone Number
Contoso | Jhon | +187655272837
Markson | Steve | +123443243521

$lastname = Column1 (cell1 + cell2)

$name = column2 (cell1 + cell2)

$phone = column3 (cell1 + cell2)

Thanks, best regards.

ConvertTo-Json gives unexpected characters in JSON payload.

$
0
0

I have been submitting JSON payloads to our certificate store for sometime now. If there was an error then it could be attributed to incorrect data. Recently we have been submitting a JSON payload to our CA for the renewal of certs as we migrate from old to new servers / websites. We would submit an array consisting of the old Subject Alternative Names along with new Subject Alternative Names. For the most part this goes well. However, for some migrations we get additional characters in the payload which causes a failure. I'll show an example of the [PSCustomObject] and the JSON payload.

$json =[PSCustomObject]@{
  CertificateTypeRequested = $CertificateTypeRequested
  CN = $CN
  CertificateSigningRequest = $CSR
  Email = $Email
  EnhancedKeyUsage = $EKU
  ExpireNotificationFlag = $Expire
  PAHAttestation = $PAHA
  RenewContact = $Renew
  SAN = $SAN
  ServerFacing = $SF 
  CTEnable = $CTE
  CTEnableAttestation = $CTEA
} 

I'm now going to convert the contents of $Json using ConvertTo-Json. The following is the result of the converstion.

$json
{"CertificateTypeRequested":  "PEM","CN":  "wwwqa.cns.company.com","CertificateSigningRequest":  "-----BEGIN NEW CERTIFICATE REQUEST----- MIIEcDCCA1gCAQAwgYoxCzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNaWNoaWdh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HGhHYdUwIwDgYDVR0PAQH/BAQDAgUg MA0GCSqGSIb3DQEBBQUAA4IBAQBQAYuptZuVzIdh8GRdKOXTbDyFiXnTjZHUEim1 ts8fQ+ACpGaDXgrHj9qu0pYXRpfe/Or
273QNT9PcAz65/7ZM3U7Wn+Ak6nDdWrT6 rj0hffLJqZ5iSfLw68Eav9LPcGtIdf8vqzt1ve9kNNQA5Lkg3P45SGusdMJzIL7w Jum6wJYcnnHjnvin1a5Snm3ZUa6Lxa55PMQYF6FGd7hIT5bntf
dxW95STkgDoe9p 862Re6hNIZrGrreGurfSGHtB/QSogA1e9gwDTpwOKcz3R9Ns+80rw4T0PN1XWito C0zJ0qvC5mczGlUf285uPH8nPI8mWQMvYCTU/9tUONwLm87R -----END NEW CERTIFI
CATE REQUEST-----","Email":  "Jed@company.com","EnhancedKeyUsage":  "1.3.6.1.5.5.7.3.1,1.3.6.1.5.5.7.3.2","ExpireNotificationFlag":  "True","PAHAttestation":  "True","RenewContact":  "RenewalParties","SAN":  ["[\"wwwqa-cns.app.company.com\",\"wwwqa.cns.company.com\r\"]"
            ],"ServerFacing":  "1","CTEnable":  2,"CTEnableAttestation":  "True"
}
I have no idea where the r character comes from in the following string. 
wwwqa.cns.company.com\r\
 If I go to a web portal for the CA and request the old value for the SAN instead of using PowerShell to obtain the SAN values there is no additional r character. Is this a web portal issue or errant  ConvertTo-JSON conversion?

Format output csv

$
0
0

I am looking to format the output of my csv, my code is below:

Get-ADUser -Filter {department -like "*"} -Properties * |Select-Object givenname, surname, department, emailaddress, office, manager |Export-Csv "c:\test.csv"

Output:  John, Doe, Department, email@domain, Office, CN=John Manager,OU=user,DC=domain,DC=local

I would like to strip out the domain objects in the output of manager and just have John Manager show, how could I do this please? 

The workflow definition has been recycled, because the workflow definition cache limit of 1000 has been reached

$
0
0

Hi all,

We are experiencing a issue executing a long powershell processes. We get this message:

The workflow definition has been recycled, because the workflow definition cache limit of 1000 has beenreached

This occurs after October 2018 patch in Windows 2016 Datacenter Server edition. For a while was possible uninstall this patch but now, after December update, isn't possible do this.

There is a workaround but don't work.

Are there any related issue?

Regards,

Eduard.


Use Get-WmiObject with PCs on domain

$
0
0

Hi,

Apologies, I'm new to PowerShell so be gentle.  Please let me know if I need to provide any more information.

I'm trying to make a script to get the list of computer names on a domain and check whether their drives are being reported as failure predicted.  

I'm using Get-ADComputer to get the names all PCs which have the format PC401*, this seems to work.  I then use a ForEach loop to Get-WmiObject to get the data I need.  I think the problem is with the format of the output of the Get-ADComputer, but I can't find a way to format it that the Get-WmiObject likes.  If I specify a PC name in the Get-WmiObject query it outputs correctly, but when I use the $computer variable it gives a RPC connection error (presumably because the PC name is formatted wrongly).  Any thoughts on how I can achieve this would be appreciated. 

Import-Module ActiveDirectory
$computerslist = Get-ADComputer -Filter {name -like PC401*}| Select-Object -Property Name

ForEach ($computer in $computerslist) {
Get-WmiObject -namespace root\wmi -class MSStorageDriver_FailurePredictStatus -ComputerName $computer | 
Select PSComputerName, InstanceName, PredictFailure, Reason}

Get-VM | vSphere Web

$
0
0

Hi,

What Get-VM cmdlet should I use if we are using web vSphere? We just upgarded our vmware and now using web vsphere. It seems Get-VM cmdlet is not recognized already for this one.

Here's the code:

if (( Get-PSSnapin Vmware.Vimautomation.core -ErrorAction SilentlyContinue |Out-Null ) -eq $null) {
    Add-PSSnapin vmware.vimautomation.core -ErrorAction SilentlyContinue | Out-Null
    
}
Set-PowerCLIConfiguration -DefaultVIServerMode multiple -DisplayDeprecationWarnings:$false -Confirm:$false | Out-Null
Connect-VIserver -Server $vcenters -credential $cred -ErrorAction SilentlyContinue| Out-Null
foreach($VM in $servers){
$vminfo =  Get-VM -name $VM -erroraction silentlycontinue


Powershell newbie Help

$
0
0

Hey All,

I'm very new to powershell and would like a little help on getting some information to export to a csv

So i'm looking for windows update source to make sure all computers are updating through Windows Update, we dont run a WSUS.

my script currently looks like this.

$MUSM = New-Object -ComObject "Microsoft.Update.ServiceManager"
$MUSM.Services | select Name, ServiceUrl,IsManaged | 
Export-Csv -Path c:\Temp\Windowsupdate.csv -NoTypeInformation 

This works fine i get the information i want on a CSV file now the tricky part is i want to run this on all computers on the network around 90 and then compile them all into 1 csv so i can check them all at once. Also would add the computer name in the csv file. So i get Computer name then the source i want then next computer ect... in the compiled csv

Hopefully this is easy for someone who is an expert at powershell and can help me or point me in the right direction. If you know an easier way to check if the computer is connecting to Windows Update that would be very helpful. 

Do a select string on files after a get-childitem but keep path

$
0
0

First time I have needed to ask anything but this is killing me.

I am trying to extract the KB name out of the filename while keeping the path name or directory name. The reason being is I want to sort the KB's and then install them in that order, so here is the code.

$spname=Get-ChildItem-file-RecurseC:\KBupdates|selectname,PSchildname|%{((Select-String-InputObject$_-Pattern"KB\d{7}").Matches[0].Value) }

$spname only holds the KB's as in KB8654321 but not the path. I need to keep the directory or path name to install them.

Can anyone help with this?
Do I need to somehow make a hash table so KB4132216 = c:\kbupdate\2018-05 Update for Windows Server 2016 for x64-based Systems (KB4132216).msu

Hope this makes sense

Running set of SQL agent jobs in parallel

$
0
0

Hi,

I am able to run a sqlagent job from powershell. Can anyone help me how to run multiple sql jobs in parallel and wait for the set to get complete. Once all jobs in first set completes, next set of sql jobs should start.

Lets say..

Set1 = Job1.1, Job1.2, Job1.3

Set2 = Job2.1, Job2.2

Set 3 = Job3.1, Job 3.2, Job 3.3, Job 3.4

My PS should start all jobs {Job1.1, Job1.2, Job1.3} in parallel, wait for all jobs to complete. If any of them failed, Rerun them.. and wait for completion...

Next, Set 2 will be started..


sekhar

How to delete a question posted by in this forum?

$
0
0
I want to delete a question that i asked previously.. How can i do that?

sekhar

Find files out of sync

$
0
0

Hi Experts, 

I am trying to achieve the following objectives with this code and report if source and destination folders are out of sync (which are located in different servers)

  1. List of new files that have been added to source (temp1 in the code)
  2. List of existing files that got modified in the source (temp2 in the code)

However, I am getting inconsistent results when new files are added to the source.

Say here is the example folder structure on both servers when they are in sync.

Folder 1 – File 1a , File 1b,

Folder 2 – File 2a

Folder 3  -  File 3a

If I modify File 1a, the code reports that File 1a is modified (as expected). No issues there.

However, if I create new file ‘File 1c’ in Folder 1, code not only reports that there is a new file ‘File 1c’ (as expected), but also reports that ‘File 3 a’ has been modified, though ‘File 3 a’ was not modified.

If I copy the newly created file ‘File 1c’ to the destination on server 2, the code reports the folders are now in sync and does not complain about ‘File 3a’ anymore

Why the code is creating false alarm with respect to a file that was not modified, when a new file is created in some other folder?  The code is using SHA256 algorithm for hashing.

$SourceFolder = "\\server01.company.com\c$\Directory"
$TargetFolder = "\\server02.company.com\c$\Directory"


$SourceFolderItems = @(Get-ChildItem -Recurse -Path $SourceFolder)  
$TargetFolderItems = @(Get-ChildItem  -Recurse -Path $TargetFolder)

$Sourcedocs = @(Get-ChildItem -Recurse -Path $SourceFolder) |  foreach  {Get-FileHash –Path $_.FullName}
$Targetdocs = @(Get-ChildItem  -Recurse -Path $TargetFolder) | foreach  {Get-FileHash –Path $_.FullName}

$difference1 = @(Compare-Object -ReferenceObject $SourceFolderItems -DifferenceObject $TargetFolderItems -IncludeEqual -PassThru | where {$_.SideIndicator -eq "<="})
$count1 = $difference1.Count

$difference2 = @(Compare-Object -ReferenceObject $SourceDocs -DifferenceObject $Targetdocs -Property Hash -IncludeEqual -PassThru |  where {$_.SideIndicator -eq "<="})
$count2 = $difference2.Count



if ($count1 -eq 0 -and $count2 -eq 0)
 {
  write-host "Folders are in sync"
 }

 else{

 if($count1 -gt 0)
 {
 $temp1 = Compare-Object -ReferenceObject $SourceFolderItems -DifferenceObject $TargetFolderItems -IncludeEqual -PassThru | where {$_.SideIndicator -eq "<="} | Select-Object versioninfo
 $temp1 = $temp1 | Out-String

 write-host "New files in the following location $temp1"

 }
 if($count2 -gt 0)
 {
 $temp2 = Compare-Object -ReferenceObject $SourceDocs -DifferenceObject $Targetdocs -Property Hash -IncludeEqual -PassThru |  where {$_.SideIndicator -eq "<="} | Select-Object  Path
 $temp2 = $temp2 | Out-String

 write-host "Files in the following location have changed $temp2"
 }
 }

Robocopy only run during certain hours.

$
0
0

My copies are taking longer than anticipated and bleeding into the workday I added the /Z along with /RH commands to robocopy although it doesnt seem to stop copying when the second time rolls around. I have tried changing up the order of the commands or seeing if there is a known problem with this modifier online but not found much. Can I accomplish the same results another way? Here is the script for reference:

foreach ($Config in $ConfigList) {
    $LogFile = Join-Path -Path $($Config.LogDir) -ChildPath $LogFileName
    Robocopy.exe $($Config.Source) $($Config.Destination) /s /DCOPY:T /Z /R:5 /W:30 /RH:2100-0500 /NFL /NDL /NP /XJ /LOG:$LogFile
}




_Sam_


Missing PTR records after updating forward records TTL with Set-DnsServerResourceRecord

$
0
0

I have noticed that after updating the host DNS records TTL with Set-DnsServerResourceRecord the PTR records go missing.

has anyone else experienced this happening?


ForEach Script Block

$
0
0

I am in the process of learning PowerShell and have been reading about the ForEach statement.  The simple code below is based on a script that I found online, and I have been trying to modify it to perform two separate operations.  I want to stress this point.  I am not looking for a clever way to consolidate the math into one operation.  I am purposely doing two operations in order to learn how to perform multiple operations in a script block.  Seems like it should be easy, but I can't seem to make it work so there is obviously something that I am missing.

Here's the script:

$NumArray = (1..10)
ForEach ($Item in $NumArray)
{
    $Item * 13
    $Item + 20
    $Item
}

In my mind, it should be doing 1 * 13 = 13 + 20 = 33, then 2 * 13  = 26 + 20 = 46, and so forth.  The output I am trying to get is:

   33

   46...

What I am getting is:

   13

   21

   1

   26

   22

   2...

Okay, I understand why I am getting that output.  I just can't figure out how to get the output that I want.  What am I doing wrong?

Thanks in advance for any help that you can offer!

--Tom

Script for Moving List of Computers to OU

$
0
0

I have a list of computer names in Excel. I want a Power Shell script, or any other type of script, that can grab that list of computer names, and move them into a specified OU.

The OU's name is encryption - my domain name is abc.abcdefg.com

Any help would be wonderful.

Windows.Forms event Handler from button click

$
0
0

Hi,

I'm trying to find a way to get an event from clicked button that could be saved in a variable and then perform an action from a second button depending on the precedent clicked button.

Also, I'd like to be able to call different function based on the first clicked button.

Here's an example of what I'm looking for:

This part is one of the function

Function DL{
$user=$Textboxemail.text
        $date = get-date 
        $Distrib = Get-Distributiongroup -Identity $user | Format-List DisplayName
        $DL = "##################################### Distribution List ##################################### "
        $Distrib2 = Get-DistributionGroup $user | Format-List Name, grouptype, Managedby, memberjoinrestriction, memberdepartrestriction, customattribute6, emailaddresses, maxsendsize, maxreceivesize
        $DLmember = "##################################### Distribution List member ##################################### "
        $Distrib3 = Get-DistributionGroupmember $user | out-string

}

Here, we have one of the many first button that needs to be clicked on

$buttonDL.Add_Click({
    $FormInformationUserWindows.controls.AddRange(@($blocmail))
    $blocmail.controls.AddRange(@($labelemail,$Textboxemail,$ButtonExport,$ButtonShow))
    })
From that, another button is Added with the action that needs to be performed based on the first clicked button

$ButtonExport.Add_click({
    If($ButtonDL is clicked…){
    $data = $Function:DL
        $ouvrir2 = New-Object -Typename System.Windows.Forms.SaveFileDialog
        $ouvrir2.initialDirectory = "C:\"
        $ouvrir2.DefaultExt = ".txt"
        $ouvrir2.Filter = "Text Files (*.txt)|*.txt"
        $retour2 = $ouvrir2.ShowDialog()
        if ($retour2 -eq "OK") { $Data > $ouvrir2.filename }
            else { ... }
            }
})

In that second button, I want it to execute the function DL and export it in the wished file if the buttonDL has been clicked on, but can't find what is the right way to do so. Also, it's seems the way I call my function doesn't seem to work correctly as my file countain the function cmdlts and not the result.

I have tried another way that works for the button, but that would require for me to repeat the same codes too many times:

#$buttonDL.Add_Click({
#    $FormInformationUserWindows.controls.AddRange(@($blocmail))
    $blocmail.controls.AddRange(@($labelemail,$Textboxemail,$ButtonExport,$ButtonShow))
    $ButtonExport.add_click({
        $ouvrir2 = New-Object -Typename System.Windows.Forms.SaveFileDialog
$ouvrir2.initialDirectory = "C:\"
        $ouvrir2.DefaultExt = ".txt"
        $ouvrir2.Filter = "Text Files (*.txt)|*.txt"
        $user=$Textboxemail.text
        $date = get-date 
        $Distrib = Get-Distributiongroup -Identity $user | Format-List DisplayName
        $DL = "##################################### Distribution List ##################################### "
        $Distrib2 = Get-DistributionGroup $user | Format-List Name, grouptype, Managedby, memberjoinrestriction, memberdepartrestriction, customattribute6, emailaddresses, maxsendsize, maxreceivesize
        $DLmember = "##################################### Distribution List member ##################################### "
        $Distrib3 = Get-DistributionGroupmember $user | out-string
        $Data = $Date, $Distrib, $DL, $Distrib2, DLmember, $Distrib3
            $retour2 = $ouvrir2.ShowDialog()
                if ($retour2 -eq "OK") { $Data > $ouvrir2.filename }
                else { ... }

Thank you for any help or ideas you might have

Nad

PASSWORD ON PDF FILE

$
0
0

Hello everyone,

I am trying to put a password on a PDF file via powershell but I can not do it because of an error message. Below, the code and the error message.
Thank you for your help

--Script

[System.Reflection.Assembly]::LoadFrom("C:\Users\MBODJI\Desktop\test_password_powershell\itextsharp.dll")

function PSUsing {
 param (
 [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
 [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
 )
 
 Try {
 &$scriptBlock
 }
 Finally {
 if ($inputObject.psbase -eq $null) {
 $inputObject.Dispose()
 } else {
 $inputObject.psbase.Dispose()
 }
 }
}

$file = New-Object System.IO.FileInfo "C:\Users\MBODJI\Desktop\test_password_powershell\exo_algo.pdf"
$fileWithPassword = New-Object System.IO.FileInfo "C:\Users\MBODJI\Desktop\test_password_powershell\exo_algo_password.pdf"
$password = "secret"
PSUsing ( $fileStreamIn = $file.OpenRead() ) {
 PSUsing ( $fileStreamOut = New-Object System.IO.FileStream($fileWithPassword.FullName,[System.IO.FileMode]::Create,[System.IO.FileAccess]::Write,[System.IO.FileShare]::None) ) {
 PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileStreamIn ) {
 [iTextSharp.text.pdf.PdfEncryptor]::Encrypt($reader, $fileStreamOut, $true, $password, $password, [iTextSharp.text.pdf.PdfWriter]::ALLOW_PRINTING)
 }
 }
}

--Error

PSUsing : Impossible de traiter la transformation d'argument sur le paramètre «inputObject». Impossible de convertir la valeur «
iTextSharp.text.pdf.PdfReader» du type «iTextSharp.text.pdf.PdfReader» en type «System.IDisposable».
Au caractère C:\Users\MBODJI\Desktop\test_password_powershell\cryptage.ps1:26 : 10
+  PSUsing ( $reader = New-Object iTextSharp.text.pdf.PdfReader $fileSt ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData : (:) [PSUsing], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,PSUsing

Search and Move Folder based on Content Count

$
0
0

Ok i need to search multiple folders and move the ones with multiple .bin files in them to a seperate directory. 

start with this

Folder Name
-gamename
--gamenametrack1.bin
--gamenametrack2.bin
--gamename.cue
-gamename1
--gamenametrack1.bin
--gamename1.cue
-gamename2
--gamename2track1.bin
--gamename2track2.bin
--gamename2track3.bin
--gamename2.cue

end with this

Folder Name
-gamename1
--gamenametrack1.bin
--gamename1.cue
New Folder Name
-gamename
--gamenametrack1.bin
--gamenametrack2.bin
--gamename.cue
-gamename2
--gamename2track1.bin
--gamename2track2.bin
--gamename2track3.bin
--gamename2.cue

Viewing all 21975 articles
Browse latest View live


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