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

Create Local Admin based off of CSV

$
0
0

I have a CSV that has the following data:

ComputerName,Password

computer1,Password1

computer2,Password2

My ultimate goal is the following: Run this script as a GPO, where it creates a local user on the computer (all the same username), adds it to the Administrators group, and sets its password BASED on the computername filed in the CSV.

Example:

Computer1 will get a local admin of KI.Admin and a password of Password1

Computer2 will get a local admin of KI.Admin and a password of Password2

Any help? Whenever i try to assign variables to each column (computername and password) it only ever returns the last record in the csv.


Problem with new-AdUser

$
0
0

Hello I have a problem with the New-AdUser command

here is my code

It's in French because I'm French :) Sorry

cls

# Importation du fichier .CSV
$utilisateur = Import-Csv -path  C:\Temp\ETACH_RUB_Users_Migration.csv -delimiter ';'
$path = "OU=Standard,OU=Users,OU=RUB,OU=Companies,DC=swatchgroup,DC=net"
foreach($utilisateurs in $utilisateur)
    {
         $Nom = $utilisateurs.Nom
         $Prenom = $utilisateurs.Prenom
         $Description = $utilisateurs.Description
         $Username = $utilisateurs.Username
         $Bureau = $utilisateurs.Bureau
         $Telephone = $utilisateurs.Telephone
         $Email = $utilisateurs.Email
         $Fonction = $utilisateurs.Fonction
         $Service = $utilisateurs.Service
         $EmployeeNumber = $utilisateurs.employeeNumber
         $division = $utilisateurs.division
         # $Name = $($utilisateurs.Nom + ", " + $utilisateurs.Prenom)

         # Write-Host($Name)
         # Nom, prenom marche pas avec virgule
         New-ADUser -Name "$($utilisateurs.Nom) $($utilisateurs.Prenom)" -GivenName $Prenom -SurName $Nom -Description $Description -SamAccountName $utilisateurs -UserPrincipalName $utilisateurs -Office $Bureau -MobilePhone $Telephone -EmailAddress $Email -Title $Fonction -ServicePrincipalNames $Service -EmployeeNumber $EmployeeNumber -Division $division -Path $path -PassThru | Enable-ADAccount
    }

the error is the folowing 

New-ADUser : Le nom fourni n’est pas un nom de compte formé correctement
Au caractère C:\Temp\Users_Excel.ps1:23 : 10
+          New-ADUser -Name "$($utilisateurs.Nom) $($utilisateurs.Preno ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=Test_N Test_...tchgroup,DC=net:String) [New-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser

Thanks you for you help !

Reuse some columns in a CSV, adding missing data

$
0
0
Hello

I made a CSV and now need to add some more columns, since I forgot one. I don't want to run the original again, since it takes 8 hours to run, it is O365 ps. 

I need to get the OU for all, and since it is against our local AD, it should take minutes to get the missing data.

How do I import the CSV, reuse all the colums already there but add the missing data?

So import csv, identity the users using the e.g. upn column, run a "foreach" and then export the missing + what I already have in the CSV? :-)

BR
Steen

Copy file to Folder using Powershell..

$
0
0

Hi,

I have a Problem. I have almost 50000 files (.txt, .pdf, . csv)etc . All the files has specific name like ( Customer.txt, car.txt, Customer.pdf). And i have also 50000 folder named like file name (Customer, Car, House) etc. Now how can i copy those files to specific folder eg (Customer.txt & pdf to Customer folder ) and (Car.txt &.pdf to Car folder) and so on. is any powershell command to copy all the files to specific folder compare to file name.  If anyone can help then it would be bit easier.

Thanks to all

AArif Chowdhury

add a new email domain to 40+ distribution list as alias

$
0
0

I'm just wondering if I can ask for some assist? 

We are using O365 Exchange and it's synced with our AD. 

Basically we have purchased a new domain and I'm trying to add the new domain to about 40+ of our distribution list under the proxyaddresses as smtp:email. 

We have the groups setup as follows. 

Group Name: Test 1

Email: test1@test.com

I have tried with the below though it only puts the domain in not with the part before the @test.com 

$Distros = import-csv C:\Output\test.csv

foreach ($d in $distros)
{
    $DistroName = $d.name
    $group = get-adgroup $distroname -properties proxyaddresses

    set-adgroup $group -add @{proxyaddresses="smtp:" + "test.com"}

running scripts from network shares

$
0
0

i have a hypv-2016 core server which has mapped a file server share (\\FS\Powershell)

BUT nothing from that share will run.  Files cannot be loaded because they are not digitally signed.

The files are our own, not from the internet and not blocked

The default domain policy and as shown by Get-Executionpolicy  is RemoteSigned

I have followed the advice in "https://blogs.technet.microsoft.com/heyscriptingguy/2012/10/29/how-to-run-powershell-scripts-from-a-shared-directory/" . But this a core server I'm not sure how relevant IE enhanced security is. Anyway i set the "Intranet Sites: Include all network paths (UNCs)" as described, made no difference

What must i do to allow running from this share ??

thanks

DSC - Remove all software not part of baseline

$
0
0

I have a Windows 10 computer that was imaged with our base software. I do not want any configuration drifts from what was already installed on the computer. Sometimes someone with elevated privileges will install an unapproved software and we have to uninstall it.

Is DSC able to uninstall all software that is not part of the mof when generated?

A parameter cannot be found that matches parameter name

$
0
0

Hi, I was working on creating a powershell module that will create a login and user with a role for SQL server for automation purpose and it was successful. The error arises when i try to add extra purpose to the module which is sending email to the user for which the account is created for.i am getting the below error

"A parameter cannot be found that matches parameter name 'to'."

There is no issue with the SMTP server etc. it is all checked.

Thank you in advance for all your help. The code i used is



Function Createuser {

[cmdletbinding()]

Param(
[string]$instanceName,
[string]$loginName,
[string]$dbUserName,
[string]$databasename,
[string]$roleName,
[string]$to,
[string]$subject
)

$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

New-DbaLogin -SqlInstance $instanceName -Login $loginName
Write-Host("Login $loginName created successfully.")

foreach($databaseToMap in $databasenames)  
{
    $database = $server.Databases[$databaseToMap]
    if ($database.Users[$dbUserName])
    {
        Write-Host("Dropping user $dbUserName on $database.")
        $database.Users[$dbUserName].Drop()
    }

    $dbUser = New-Object `
    -TypeName Microsoft.SqlServer.Management.Smo.User `
    -ArgumentList $database, $dbUserName
    $dbUser.Login = $loginName
    $dbUser.Create()
    Write-Host("User $dbUser created successfully.")

    #assign database role for a new user
    $dbrole = $database.Roles[$roleName]
    $dbrole.AddMember($dbUserName)
    $dbrole.Alter()
    Write-Host("User $dbUser successfully added to $roleName role.")
}



$smtpServer = "xxxxxx.xxxxx.xxxxx.com"
$smtpFrom = "xxxxxx@xxxx.com"
$smtpTo = $to
$messageSubject = $subject
$messageBody = "your account is created in the server. Plase reply to this email for any question you may have."
 
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)

}


Server Monitoring

$
0
0

Hi all

I am looking for some Powershell Scripts that I can run to build a picture of our server's performance and health. 

I am looking for an alternative to Performance Monitor, and I would like to ask if anyone has any Powershell options that I can run as part of my daily and weekly reporting functions.

Realtime performance metrics are not of real use to me (in this case), I am looking to build a general performance picture, as well as isolate spikes and other important events. 

If Powershell is not the right environment, perhaps someone can suggest another option? We already use Check_MK but the interface and navigation is really not very user friendly.

Many thanks

Protocols Numbers returned by get-tlsciphersuite

$
0
0

The get-tlsciphersuite is a great command; but, what are the numbers returned in the Protocols value?

KeyType               : 0
Certificate           :
MaximumExchangeLength : 256
MinimumExchangeLength : 0
Exchange              : PSK
HashLength            : 256
Hash                  : SHA256
CipherBlockLength     : 1
CipherLength          : 0
BaseCipherSuite       : 176
CipherSuite           : 176
Cipher                :
Name                  : TLS_PSK_WITH_NULL_SHA256
Protocols             :{771, 65277}

Do these correspond to specific TLS versions?  If so, where can I find the mapping table?


TBrennan

Cant make work with variable in Get-ADuser command to get UPN

$
0
0

I cant seem to figure this out, any help would be appreciated.

$users=Import-Csv-PathC:\Scripts\UPNUserlookup.csv

ForEach

($userin$users){Get-ADUser-identity$user|Select-ObjectName,UserPrincipalName}


pipeline error when creating a script to change teams upgrade policy

$
0
0

Hello, 

I am relatively new to creating powershell content, although I have been a user for some time. I have been asked to modify a script that drops a single user into the teams upgrade policy group into one that can do batches of users at one time. 

Here is the original functioning script

Import-Module SkypeOnlineConnector
$sfbSession = New-CsOnlineSession
Import-PSSession $sfbSession
$credential = Get-Credential
$session = New-CsOnlineSession -Credential $credential -Verbose
Import-PSSession $session
Grant-CsTeamsupgradePolicy -Identity mfa.test@domain.com -PolicyName upgradetoteams

here is the modified one as it currently sits

Import-Module SkypeOnlineConnector -scope currentuser

Import-CSv -Path "C:\scriptpath\GlobalProtect_Import.csv" 
| ForEach { $UPN=$_.UserPrincipalName


$sfbSession = New-CsOnlineSession 
Import-PSSession $sfbSession 
$credential = Get-Credential 
$session = New-CsOnlineSession -Credential $credential -Verbose 
Import-PSSession $session 
Grant-CsTeamsupgradePolicy -Identity $UPN -PolicyName upgradetoteams }

this is the error I get when I try to run it. 

At C:\scriptpath\Teams_Upgrade.ps1:6 char:1
+ | ForEach { $UPN=$_.UserPrincipalName
+ ~
An empty pipe element is not allowed.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EmptyPipeElement

Can anyone tell me what character seems to be missing or where the issue lies in this script?

Generating an MSI Transform file from PowerShell

$
0
0

So near, and yet so far...

I've been trying to find a way to generate an MST file on-the-fly as part of deployment automation.  The script below works, in that it generates an MST file, which - when I open it in Orca - looks just the part, has the right variables set to the right values etc...

Unfortunately, when I try to apply it to an MSI file, I get a complaint that it's an invalid transform.

If I open the transform in Orca and save it again, it works, no problem.  That additional step appears to add some binary headers to the file, from a quick side-by-side comparison.

So, what am I missing...  Anyone?

Thanks,

Stuart

$signature = @' 
using System.Text;
using System.Runtime.InteropServices;
using System;
using System.Collections.Generic;

public static class Msi
{
	[DllImport("msi.dll", SetLastError = true)]
	private static extern uint MsiOpenDatabase(string szDatabasePath, IntPtr phPersist, out IntPtr phDatabase);
	[DllImport("msi.dll", CharSet = CharSet.Unicode)]
    private static extern uint MsiDatabaseOpenView(IntPtr hDatabase, [MarshalAs(UnmanagedType.LPWStr)] string szQuery, out IntPtr phView);

    [DllImport("msi.dll", CharSet = CharSet.Unicode)]
    private static extern uint MsiViewFetch(IntPtr hView, out IntPtr hRecord);

    [DllImport("msi.dll", CharSet = CharSet.Unicode)]
    private static extern uint MsiViewExecute(IntPtr hView, IntPtr hRecord);

    [DllImport("msi.dll", CharSet = CharSet.Unicode)]
    private static extern uint MsiRecordGetString(IntPtr hRecord, int iField, System.Text.StringBuilder szValueBuf, ref int pcchValueBuf);

    [DllImport("msi.dll", CharSet = CharSet.Unicode)]
    private static extern uint MsiRecordSetString(IntPtr hRecord, int iField, string szValue);

    [DllImport("msi.dll", ExactSpelling = true)]
    private static extern IntPtr MsiCreateRecord(uint cParams);

    [DllImport("msi.dll", ExactSpelling = true)]
    private static extern uint MsiViewModify(IntPtr hView, uint eModifyMode, IntPtr hRecord);

    [DllImport("msi.dll", SetLastError = true)]
    private static extern uint MsiDatabaseGenerateTransform(IntPtr hDatabase, IntPtr hDatabaseReference, string szTransformFile, uint iReserved1, uint iReserved2);

    [DllImport("msi.dll", ExactSpelling = true)]
    private static extern uint MsiCloseHandle(IntPtr hAny);

	private static readonly Dictionary<string,string> replacements = new Dictionary<string,string>();
	private static readonly Dictionary<string,string> additions = new Dictionary<string,string>();
	private static readonly List<IntPtr> openHandles = new List<IntPtr>();

    private static string tempFile = System.IO.Path.GetTempFileName();

	public static void ClearReplacements()
	{
		replacements.Clear();
	}
	
	public static void AddReplacement(string key, string value)
	{
		replacements.Add(key, value);
	}
	
	public static void ClearAdditions()
	{
		additions.Clear();
	}
	
	public static void AddAddition(string key, string value)
	{
		additions.Add(key, value);
	}
	
	public static void CreateTransform(string msiPath, string mstPath)
	{		
		IntPtr msiInputHandle;
		IntPtr msiAlteredHandle;
		IntPtr msiDatabaseView;
		IntPtr currentRecord;
		uint result;
		bool shouldContinue = true;
		
		System.IO.File.Delete(tempFile);
		System.IO.File.Copy(msiPath, tempFile);
		
	    if ((result = MsiOpenDatabase(msiPath, (IntPtr)0, out msiInputHandle)) != 0)
        {
            CleanUp("ERROR MsiOpenDatabase " + result);			
			return;
        }

		openHandles.Add(msiInputHandle);
		
		if ((result = MsiOpenDatabase(tempFile, (IntPtr)2, out msiAlteredHandle)) != 0)
        {
            CleanUp("ERROR MsiOpenDatabase " + result);			
			return;
        }
		openHandles.Add(msiAlteredHandle);
        if ((result = MsiDatabaseOpenView(msiAlteredHandle, "SELECT Property, Value FROM Property", out msiDatabaseView)) != 0)
        {
            CleanUp("ERROR MsiDatabaseOpenView " + result);			
			return;
        }		
		openHandles.Add(msiDatabaseView);
		if ((result = MsiViewExecute(msiDatabaseView, IntPtr.Zero)) != 0)
		{
			CleanUp("ERROR MsiViewExecute " + result);			
			return;
		}
	    while (shouldContinue)
        {
            result = MsiViewFetch(msiDatabaseView, out currentRecord);
            if (result == 259)
            {
                shouldContinue = false;
            }
            else if (result == 0)
            {
				openHandles.Add(currentRecord);
				StringBuilder builder = new System.Text.StringBuilder(256);
                int count = builder.Capacity;

                if ((result = MsiRecordGetString(currentRecord, 1, builder, ref count)) != 0)
                {
                    CleanUp("ERROR MsiRecordGetString " + result);
					return;
                }

				string key = builder.ToString().Trim();

                if (replacements.ContainsKey(key))
                {
                    if ((result = MsiRecordSetString(currentRecord, 2, replacements[key])) != 0)
                    {
                        CleanUp("ERROR MsiRecordSetString " + result);
                        return;
                    }
                    if ((result = MsiViewModify(msiDatabaseView, 2, currentRecord)) != 0)
                    {
                        CleanUp("ERROR MsiViewModify " + result);
						return;
                    }                        						
                }                
                MsiCloseHandle(currentRecord);
				openHandles.Remove(currentRecord);
            }
            else
            {
                CleanUp("ERROR MsiViewFetch " + result);
				return;
            }
        }
        foreach (KeyValuePair<string,string> item in additions)
        {
            IntPtr newRecord = MsiCreateRecord(2);
			openHandles.Add(newRecord);

            if ((result = MsiRecordSetString(newRecord, 1, item.Key)) != 0)
            {
                CleanUp("ERROR MsiRecordSetString " + result);
				return;
            }

            if ((result = MsiRecordSetString(newRecord, 2, item.Value)) != 0)
            {
                CleanUp("ERROR MsiRecordSetString " + result);
				return;
            }

            if ((result = MsiViewModify(msiDatabaseView, 1, newRecord)) != 0)
            {
                CleanUp("ERROR MsiViewModify " + result);
				return;
            }

            MsiCloseHandle(newRecord);
			openHandles.Remove(newRecord);
        }
		
	    if ((result = MsiDatabaseGenerateTransform(msiAlteredHandle, msiInputHandle, mstPath, 0, 0)) != 0)
        {
            CleanUp("ERROR MsiDatabaseGenerateTransform " + result);
			return;
        }
		CleanUp("OK Created Transform File " + mstPath);
	}
	private static void CleanUp(string message)
	{
		Console.WriteLine(message);
		foreach(IntPtr handle in openHandles)
		{
			MsiCloseHandle(handle);
		}
		openHandles.Clear();
		System.IO.File.Delete(tempFile);
	}
}
'@

Add-Type -TypeDefinition $signature

function GenerateMST(
	[string]$MsiPath,
	[string]$MstPath,
	$Replacements,
	$Additions
)
{

	[Msi]::ClearReplacements()
	[Msi]::ClearAdditions()

	foreach($item in $replacements)
	{
		[Msi]::AddReplacement($item.Property, $item.Value);
	}

	foreach($item in $additions)
	{
		[Msi]::AddAddition($item.Property, $item.Value);
	}

	[Msi]::CreateTransform($msiPath, $mstPath)
}

MULTIPLE COPIES OF A FILE

$
0
0

Hi. I an completely new to scripting.

I found an answer on your site for making multiple copies of a known file :

1..10 | % { copy-Item "C:\filename*.tif" "C:\filename$_.tif"}

However, the name of the file I need to copy is different each time.

Can you please show me how I can get the filename each time?

And also a user input for the number of copies?

Most obliged. Simon.

Compile an powershell script to DLL

$
0
0

Hi,

I have some powershell functions I would like to embed in an .dll file I can share with my teams.
I think that .dll is a good choice, because no one can edit the code and for security reason, nobody can read the code without specfic tools.

How Can I compile my .ps1 in an dll I could use for batch script after?

The only way I find is to create an C# project and embed my powershell script in to make my .dll.

Regards


Using Powershell to convert .CSV to .XLSX on PC without Excel installed

$
0
0

On PC with Excel installed I wrote a short script to convert .CSV to XLSX files. I want to run this script on PC without Excel. My question - what is the module name for the command: 

$xl = New-Object -COM "Excel.Application"

Where I can find this file? How can I execute this command in case I will find a file name?

Here is my script:

Param(
  [string]$CSV_IN ) 

Write-Host "--- Start ----"

$XLS_out =  $CSV_IN.ToUpper().Replace(".CSV",".XLSX")

$FileExists = Test-Path $XLS_out

If ($FileExists -eq $True) 
{ 
    Remove-Item $XLS_out
}
 
$xl = New-Object -COM "Excel.Application"

$xl.Visible = $false 

$Wb = $xl.workbooks.Open($CSV_IN) 

$ws = $wb.Worksheets.Item(1)

$ws.Columns.item(1).columnWidth = 40
$ws.Columns.item(2).columnWidth = 15
$ws.Columns.item(2).Numberformat="0.00"
$ws.Columns.item(3).columnWidth = 15 
$ws.Columns.item(4).columnWidth = 15  
# Save & close the Workbook as XLSX. 
$Wb.SaveAs($XLS_out, 51) 

$Wb.Close() 

$xl.Quit()
   
Write-Host "--- End ----"

Thanks,

zb

Headers error - Powershell

$
0
0

Hi ,

While running the

 $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"

        $headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))

       $headers.Add('Accept','application/json')

     $headers.Add('Content-Type','application/json')

$bodyJson = $body | ConvertTo-Json 

Invoke-WebRequest -Headers $headers -Method $methodPut -Uri $uriPOST -Body $bodyJson  

I am getting the below error .

Error Message = The 'Accept' header must be modified using the appropriate property or method.

Parameter name: name

Fully Qualified Error ID = System.ArgumentException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

How to resolve this ?

Get-ChildItem : Could not find a part of the path.

$
0
0

Hi team!

  Is there a path limit to Get-ChildItem cmdlet? May someone help me on the follow error?

Get-ChildItem : Could not find a part of the path 'Y:\dados\departamentos\- DIV. DE FISC. DE ATOS DE PESSOAL E GESTÃO PREVIDENCIÁRIA\ICAP\Joao Filho\Backup\09-09-2017\Joao Carlos\Cursos do TCE\FISCALIZAÇÃO DAS COMPRAS GOVERNAMENTAIS JUNTO ÀS MICRO E PEQUENAS EMPRESAS À
LUZ DA LEI COMPLEMENTAR Nº 1232006 E SUAS ALTERAÇÕES'.
At C:\downloads\shell\dedupe.ps1:16 char:5
+     Get-ChildItem -Path $path -File -Recurse | Where-Object {($_.Leng ...+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ReadError: (Y:\dados\depart...SUAS ALTERAÇÕES:String) [Get-ChildItem], DirectoryNotFoundException
    + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
Thanks.


Doria

Access C# API in PS

$
0
0

I downloaded a C# API package and installed it in C:\QuestradeAPI\CSharp folder, which has the following files:

samples
EULA.pdf
QuestradeAPI.Net.dll
QuestradeAPI.Net.tlb
ReadMe.txt
unins000.dat
unins000.exe

As the instruction, I run the below successfully.

C:\windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe /codebase /tlb QuestradeAPI.Net.dll

And also there are *.cs files (text) under samples folder.

I need to call these API functions in PS scripts but not sure how to Add-Type in ? Thanks.

How to create new Excel file and write to it using openXML in powershell

$
0
0

I'm trying tocreate new .xlsx file and write to it usingopenXML.

i have found reference for Reading the excel throughopenXML but not for Writing to it. 

kindly Do the needful.

Thanks in Advance.

Viewing all 21975 articles
Browse latest View live


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