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

Azure VPN - How can I export and import client certificate using PowerShell script without password-error?

$
0
0

<Problem>

 I tried to install client certificate to client computer. But password error was displayed. 

 Procedure that I performed is following.
  1. I exported the pfx file using PowerShell script with the password.(*1)
  2. I copied the pfx file to client computer.
  3. I double-clicked the pfx file of the client computer. (Import-wizard has started).
  4. Select Current User and pushed "NEXT" button.
  5. Pushed "NEXT" button.
  6. Enter password and Pushed "NEXT" button (Then the dialog box with "The password you entered is incorrect." was displayed.

 Is it because that PowerShell's export-pfxCertificate command can not includes Secret key?

 In the case that pfx file is exported by certificate-export-wizard, certificate-import-wizard  is succeeded and my application works fine. Following is detail of the error.

Best regards.

<Detail of Error>

Import-PfxCertificate : The PFX file you are trying to import requires either a different password or membership in an Active Directory principal 

to which it is protected.

At C:\Work\TestService2\test_import.ps1:11 char:1

+ Import-PfxCertificate -Password $secure_pwd -FilePath "${client_cert_ ...

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

    + CategoryInfo : NotSpecified: (:) [Import-PfxCertificate], Win32Exception

    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.CertificateServices.Commands.ImportPfxCertificate

<C# Source Code>

            cf.Credentials.ClientCertificate.SetCertificate(
                                        StoreLocation.CurrentUser, StoreName.Root,
                                        X509FindType.FindBySubjectName, "FirstClientCert"
                                        );

<Power Shell Script for exporting>*1

$current_directory = 'D:\Work\TestService2'
$root_cert_name = 'FirstRootCert'
$client_cert_name = 'FirstClientCert'
#$imd_sert_name = 'FirstImdCert'
$pwd = 'xxxxxxxx'
$port_no = 5000
$service_guid = '541eea84-c788-4d23-b6b2-f5210xxxx5c5'

#1. Change the current directory.
Set-Location $current_directory

#2. Encrypt the password.
[System.Security.SecureString]$secure_pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText

#3. Create a root certificate.
$root_cert = New-SelfSignedCertificate -Type Custom -KeySpec Signature -Subject "CN=${root_cert_name}" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -KeyUsageProperty Sign -KeyUsage CertSign

#4. Export personal information exchange file and private key from root certificate.
[String]$rootCertPath = Join-Path -Path 'cert:\CurrentUser\My\' -ChildPath "$($root_cert.Thumbprint)"
Export-PfxCertificate -Cert $rootCertPath -FilePath "${root_cert_name}.pfx" -Password $secure_pwd
Export-Certificate -Cert $rootCertPath -FilePath "${root_cert_name}.crt"

#5. Create a client certificate.
$client_cert = New-SelfSignedCertificate -Type Custom -DnsName $client_cert_name -KeySpec Signature -Subject "CN=${client_cert_name}" -KeyExportPolicy Exportable -HashAlgorithm sha256 -KeyLength 2048 -CertStoreLocation "Cert:\CurrentUser\My" -Signer $root_cert -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2")

#6. Export personal information exchange file and private key from client certificate.
[String]$rootCertPath = Join-Path -Path 'cert:\CurrentUser\My\' -ChildPath "$($client_cert.Thumbprint)"
Export-PfxCertificate -Cert $rootCertPath -FilePath "${client_cert_name}.pfx" -Password $secure_pwd
Export-Certificate -Cert $rootCertPath -FilePath "${client_cert_name}.crt"

<Power Shell Script for Importing>*2

$current_directory = 'C:\Work\TestService2'
$client_cert_name = 'FirstClientCert'
$pwd = 'xxxxxxxx'

#1. Change the current directory.
Set-Location $current_directory

#2. Encrypt the password.
[System.Security.SecureString]$secure_pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText

#3. Import PFX file.
Import-PfxCertificate -Password $secure_pwd -FilePath "${client_cert_name}.pfx" -CertStoreLocation 'Cert:\CurrentUser\My'





IE Proxy Setting for all users instead of Current User

$
0
0

Hello All,

I am working on creating a Ps script to check IE Proxy Enable value from registry.

The Key that I am checking is this :  HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings

I assigned this to a Variable and then later check value of ProxyEnable key which is in above mentioned path and I get output which is good.

The issue is that it only gives for Current user, I want to check proxy value for all users profiles on server.

Any idea how can I get same results for all users profiles that are on Windows server.

Any help would be great here..

Thanks!

How to Bulk AD users update/modify attributes in AD and Exchange Mailboxes

$
0
0

Hi,

How to update/modify the AD-Users(Bulk users) in AD as well as Exchange 2013-2016. It had more than 230 users and attributes needs to change. Kindly suggest.

1.Display name

2.First name

3.Last name

4.Email id

5.Employee ID

6.Contact no.

Thanks-Sami


Thanks-Sami

Label.Text New line

$
0
0

I have added label text in PS1 form, and it get value but ffor new word show in same line not go to next line, i have tried adding (\n) but its does help in PS1 script.

Foreach($lt in $selectd)
 {
  $Resource = Get-CMDevice -Name $lt | Where-Object{$_.ResourceID} -ErrorAction SilentlyContinue

  $ResourceID = $Resource.ResourceID
  
  If($ResourceID -ne $null)
  { 
    $lbl1.Text +=  "Device Exist $ResourceID \n" 
  }
  $oReturn=[System.Windows.Forms.Messagebox]::Show($Resource.ResourceID)
   
 }


Support@Mytechnet.me


Get-ADUser - no code runs after that stage

$
0
0

Hi All.

I am writing a script to send an email to a user.

I have the user login Id but I am going onto AD to get the users email address, my script does a few things and then gets the users email from AD before attempting to send them an email.

What I am noticing is that within my code, any line of code after the lines before fails to execute.

import-module ActiveDirectory

$details = Get-ADUser -identity $owner -Properties * | Select Name, GiveNname, SamAccountName, EmailAddress $email_address = $details.EmailAddress $name = $details.GiveNname


Anything before the 4 lines runs fine, I can print out debug messages etc, but after these 4 lines, nothing runs.

Am I missing something here.

Escaping HTML

$
0
0

Hi All.

I am looking to send an email out using PS, the html sample that i want to use has a lot of double quotes, i am thinking of the best way to escape it. Is it possible to do a single escape or do I have to escape every double quote with a backtick ?

As a small example, not full.

<tr><td align="center" valign="top"><table id="templateBody" border="0" width="600" cellspacing="0" cellpadding="0"><tbody><tr><td class="bodyContent" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="20"><tbody><tr>

$body = "<tr><td align="center" valign="top"><table id="templateBody" border="0" width="600" cellspacing="0" cellpadding="0"><tbody><tr><td class="bodyContent" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="20"><tbody><tr>"


help with set-alias command

$
0
0

Hello,

     I am just learning Power Shell , and I have a question regarding set-alias that I wish to get your help and expertise.

I am trying a very simple set-alias command that I learn from the book such as :

PS C:\Users\umktdm> set-alias -name gi -value set-item

The system come back and give me an error message saying that 

set-alias : Alias is not writeable because alias gi is read-only or constant and cannot be written to.
At line:1 char:1
+ set-alias -name gi -value set-item

Could I ask if the error means that I am not having permission to write on the computer ? since I am working from one of computer from our school so it may prevent me from changing any of its configuration. I may be wrong  on my assumption since i am just learning Power Shell.

Thank you so much for all of the help.


 



Student at Georgia Tech

Need to remove all but 5 newest files, matching name, leave all files that don't match.

$
0
0

Using examples from other sources, I have the following script.  It finds the five newest files in Arguement1, matching an string from Arguement2, and deletes the rest. 

$Zpath = $args[0]
##write-host $Zpath

$Zfile = $args[1]
##write-host $Zfile

# Get all the items in Zpath
Get-ChildItem -Path $Zpath |

# Skip directories
Where-Object { -not $_.PsIsContainer } |

# Only get files that match certain format
Where-Object { $_.Name -match $Zfile } |

# Sort them by name, from most recent to oldest
Sort-Object -Descending -Property CreationTime  |

# Keep the first five items
Select-Object -Skip 5 |

Remove-Item #-WhatIf

The problem is some folders are storing mutliple files in the same folder.  
For Example, in the folder we have:
Eggs_20191101
Eggs_20191102
Eggs_20191103
Eggs_20191104
Eggs_20191105
Eggs_20191106
Eggs_20191107
Bacon_20191101
Bacon_20191102
Bacon_20191103
Bacon_20191104
Bacon_20191105
Bacon_20191106
Bacon_20191107
Bacon_20191108
Bacon_20191109

If $Zfile is Eggs, I want to delete all but the five newest Egg files and leave all the Bacon files alone.


-Al H


Display memory used by a given process

$
0
0

From Task Manager I see that a process whose name is "OUTLOOK" uses 83,33 MB of memory.

I issued the following command:

Get-Process -name "OUTLOOK" |select ProcessName, Path, VirtualMemorySize, PrivateMemorySize, NonpagedSystemMemorySize, PagedMemorySize, PeakPagedMemorySize

and the result is:

ProcessName              : OUTLOOK
Path                     : C:\Program Files (x86)\Microsoft Office\Office16\OUTLOOK.EXE
VirtualMemorySize        : 1085014016
PrivateMemorySize        : 152788992
NonpagedSystemMemorySize : 117008
PagedMemorySize          : 152788992
PeakPagedMemorySize      : 224669696

Non of the date reported is at least similar to the value reported by task manager.

Which value should I select to get the same value reported by Task Manager?

Regards

Mario

Start-Transcript for all powershell sessions on a machine

$
0
0

Hi,

Is it possible to enable something like Start-Transcript for all powershell sessions (Globally for one machine)?

I have a windows service that execute powershell script, i would like to record the sessions that are opened from that service. in event viewer i can see it executed powershell, but since the window is hidden, i cant trace the powershell output.

Thank you

Automate creation of accounts using powershell from a webbase tool

$
0
0

I'm looking for a way on how I can automate creation of accounts for our users. it is one of the daily task that I do and I wanted to make it more efficient by doing an automation. I already got an automation for the AD and Exchange part done but can't figure it how I can do this for a web base application. Here's an example. I go to https://internalip/ enter my username and password, click login. After logging in, I would click on user management tab then create an account. Is there a way for me to automate this work via powershell? Any tutorials or ideas is much appreciated.

Thanks,

Neo

A parameter cannot be found that matches parameter name 'InformationAction'

$
0
0
I'm trying to remotely rename a list of PCs in parallel but I keep getting the error "Microsoft.PowerShell.Utility\Write-Error : A parameter cannot be found that matches parameter name 'InformationAction'" in the Rename function. I've only been working with powershell for a couple of days so I am still not sure what Im doing wrong here. Below is my code minus the Verify function, which is long and has bed formating when pasted into the code block. It seems to work fine as far as I can tell however
function main{
    $DomainCredential = Verify
    $computers = GetComputers
    Rename -computers $computers -DomainCredential $DomainCredential
}
function GetComputers{
    $userinput = Read-Host "Enter the PC numbers to be named. Do not include 'PC' only type the following numbers. Type 'end' when finished"
    $oldnames = New-Object System.Collections.ArrayList
    while($userinput -ne "end"){
        $userinput = "$('PC')$($userinput)"
        [void]$oldnames.Add($userinput)
        $userinput = Read-Host
    }
    return $oldnames
workflow Rename{
    Param 
    ($computers, 
    $DomainCredential)
    foreach -parallel ($computer in $computers){
        $newname = "$($computer)$('MK')"
        Rename-Computer -InformationAction Ignore -PSComputerName $computer -NewName $newname -DomainCredential $DomainCredential
    }
}

main

how to export csv without doublequote

$
0
0

I ran the following comand

ls |export-csv "d:\a.csv"

The result is like the following, every field is double quoted, is there any way to not export double quote. Currently the silly approach I used is to first export-csv, and then read the file in and replace all the double quote with empty string.

#TYPE System.IO.DirectoryInfo

"PSPath","PSParentPath","PSChildName","PSDrive","PSProvider","PSIsContainer","BaseName","Mode","Name","Parent","Exists","Root","FullName","Extension","CreationTime","CreationTimeUtc","LastAccessTime","LastAccessTimeUtc","LastWriteTime","LastWriteTimeUtc","Attributes"

"Microsoft.PowerShell.Core\FileSystem::C:\Users\Daniel.Wu\.fcm","Microsoft.PowerShell.Core\FileSystem::C:\Users\Daniel.Wu",".fcm","C","Microsoft.PowerShell.Core\FileSystem","True",".fcm","d----",".fcm","Daniel.Wu","True","C:\","C:\Users\Daniel.Wu\.fcm",".fcm","10/6/2010 10:33:39 AM","10/6/2010 2:33:39 AM","10/15/2010 3:28:57 PM","10/15/2010 7:28:57 AM","10/15/2010 3:28:57 PM","10/15/2010 7:28:57 AM","Directory"


How to use powershell script to close ipv6 for multiple virtual network cards?

$
0
0

Hi everyone,

I'm trying to use powershell script to turn off ipv6 for my multiple virtual network cards, but I failed.

Could anyone tell me what I did wrong?

Thank you in advance.

$vmnets=Get-NetAdapter | Where-Object {$_.name -like "*vmnet*"} | Select-Object name
foreach ($vmnet in $vmnets){
    Disable-NetAdapterBinding -Name "$vmnet" -ComponentID "ms_tcpip6"
}

Best regards,

Yuxiang


Please remember to mark the replies as answers if they help. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

Adding SIP attributes to ProxyAddresses Field

$
0
0

Hello,

I'm trying to add SIP attributes to everyone's ProxyAddresses field based on their UPN.

I'm using the following script:

Set-SIP.ps1 -OU "OU=Development,OU=Users,DC=company,DC=Group"

[CmdletBinding()]

    Param( 
       [Parameter(Mandatory=$True,Position=1)]
       [ValidateScript({Get-ADOrganizationalUnit $_})]
       [string]$OU
    ) 

 $results = Get-ADUser -Filter * -Properties DisplayName, SamAccountName , UserPrincipalName , proxyaddresses -SearchBase $OU | 
	    Select DisplayName , SamAccountName , UserPrincipalName , @{Name='SIPproxyaddresses';Expression={($_.proxyaddresses | Select-String -Pattern "SIP:")}} | 
	    Where-Object {$_.SIPproxyaddresses -eq $null} 
 ForEach($user in $results)
 		{
		$samAccount = $user.SamAccountName
		$SIP = "SIP:$($user.UserPrincipalName)"
		Write-Host "Setting $samAccount -  SIP; $sip "
		Set-ADUser -Identity $samAccount -Add @{proxyAddresses=$SIP}
		}  

When I run it, I'm getting:

"Cannot validate argument on parameter 'Identity". The argument is null."

I don't understand why it's Null though.

Also, any way to edit the script to run it across the whole domain and to not have to specify an OU?

Thank you.


Help with write-host or write-output

$
0
0

Hello,

   I am trying to debug my Power Shell Script, and I try write-host, write-output but they are not working.

I am using Power Shell ISE , I wonder if there is a way to display output to the console.

Thanks,


Student at Georgia Tech

Adding an image as an overlay to an existing image

$
0
0
Hi All,

One of my customers is looking towards adding a branded screen saver to their fleet. I have their corporate logo as a PNG with transparency.

Rather than working with a fixed set of static images that we would have added the PNG to ahead of time... I had the idea to suck down Microsoft's spotlight images, add the overlay to those, and then use the modified image/s as a part of the standard Windows slideshow screensaver. Thus the screen savers dynamically change day to day and always feel fresh and new.

Pretty sure I am across what I need to do to access the source images, but where I am stuck on is adding the corporate logo to these images.

Found a number of examples online of how to use powershell to add a text based overlay/watermark... But nothing on how to insert one image into another.

Is it possible to accomplish this in powershell? To add one image to a specified position on another image?
If it is possible would the transparency of the logo be maintained or would it be replaced with white space?
Or would this require the use of third party tools?

Running a PS script against each servers logical drive(s)

$
0
0

Hi All,

I'm trying to create a script to enumerate the logical disks of a list of servers and run a script against each drive, how is this done in powershell?

E.G.

$cim = new-cimsession -comp server1, server2, server3,server4
Get-CimInstance -ClassName Win32_LogicalDisk -filter 'DriveType=3' -CimSession $cim  |
Select PSComputerName, DeviceID | Invoke-Command -ComputerName PSComputerName -FilePath "C:\admin\RunScript.ps1" -ArgumentList DeviceID

Thanks in advance.


Server parameter not found in New-PSdrive

$
0
0

I am trying to connect to a PSdrive in another domain, however it says:

New-PSDrive: A parameter cannot be found that matches parameter name 'Server'

Earlier this command used to work:

I am running the below:

New-PSDrive -Name AB -PSProvider ActiveDirectory -Scope Global -root "//RootDSE/" -Server "Server1.anotherdomain.local"

Compare-Object returns only one match of many

$
0
0

I have 2 spreadsheets that I have imported to PowerShell arrays.

They BOTH have USERNAME as a property, but otherwise they have different properties.

In one of them (array1) the USERNAME is unique among 300 entries; in the other (array2), a given USERNAME may have multiple entries among 30,000 entries, & not all of the USERNAMEs will appear in both.

Cycling thru the smaller array1 picking out the matches in array2 takes hours to complete:

foreach ($item in $array1)
{
    $matches += @($array2 | where {$_.USERNAME -eq $($item.USERNAME)})
}

However, using Compare-Object is much quicker (a matter of a few seconds) BUT only gives the 1st match from array2:

$matches = Compare-Object -ReferenceObject $array2 -DifferenceObject $array1 -Property USERNAME -ExcludeDifferent -IncludeEqual -PassThru

...so I lose the multiple matches from array2; if I remove the -ExcludeDifferent switch then the SideIndicator results for multiple matches show the 1st of the multiple matches "==" but the subsequent multiple matches as "<=".

Is there a way to get Compare-Object to correctly return all the array2 matches? Or is there a better way?

Thanks in advance for your replies! :)

Eddie


Viewing all 21975 articles
Browse latest View live


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