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

Script to get usernames based on email address

$
0
0

Hello Everyone,

We are having an issue with starting to clean up Active Directory in preparation for Azure AD Connect deployment. There are a number of user accounts that we do not need to sync (16,000), and we need to add a flag to them to not sync them. We have a list of email addresses that are linked to user accounts, but we don't have the user names. We could do and manually find these, but that's not realistic. The duplicated addresses were exported from IDfix, they have an associated contact that we still need. The user accounts those email addresses are listed on do not need to be synced. They are all different addresses, from yahoo, gmail. various other external addresses.

The goal would be to take the list of email addresses that we have, run a query to get the username on them, export and append to a csv, so we can run a different script to apply and AdminDiscription attribute change to prevent a sync. 

Here is what I have, 

$exportlocation = c:\sripts\useracct.csv
$importlocation = c:\scripts\emailList.csv

foreach ($line in $importlocation) {Get-ADUser -Filter {mail -eq $line.email}}  | Export-csv -Path $exportlocation -append

I keep getting an empty pipe error. I can run the get-aduser part no problem on its own, it just doesn't return the UPN or simply SamAccountName on its own to export. When I add the Export-csv to the standalone script with manual email address entry I return:

 Export-csv : Cannot append CSV content to the following file: C:\scripts\useracct.csv. The appended object does n
have a property that corresponds to the following column: . To proceed with mismatched properties, add the -Force
switch and retry.

Adding -Force simply puts the attributes in the csv on one line with nothing else.  Little stumped. I don't care if it exports everything as long as its in separate columns that I can copy and paste, but I'm as about as far as I know right now.


PS query all windows servers in AD and specific services

$
0
0
Trying to write script that goes out against AD and does a get-adcomputer looking for any Windows Server operating system, then goes and looks at 3 specific NT service names Healthservice, MsMpSvc, and Netbackup Client Service and report if installed or not as well as report if start or not with server name listed and exported to excel. I would be using elevated domain permissions to run the script. 

Matching Hostnames

$
0
0

Hello,

I have a powershell script (below) which works fine when I ask it to look up IP addresses.. The only criteria I have changes is for it to match the hostname field in the CSV opposed to the IPAddress.

The $Source contains hostnames like:

10000L

10001L

10002L

etc

Now the CSV Has the hostnames as 10002L.domain.co.uk

It only seems to match anything which has a blank hostname. I have pulled the hostname list directly from AD so I know there are no typing errors when matching and the DHCP information again directly from DHCP.

If I ask it to just write out the $_.HostName it gives me a list so I know its pulling information from the CSV file.

Does anyone know why its not matching?

$Source = Get-Content "C:\Temp_Storage\ip.txt"
Import-Csv 'C:\Temp_Storage\DHCP_Reservations.csv' |
where{$Source -Match $_.HostName} |
Select-Object IPAddress, HostName |
Export-Csv "C:\Temp_Storage\Matches.csv" -NoTypeInformation

Thanks


taking a power shell cmdlet and changing it into script by importing from file and applying to each name

$
0
0

In my other post I was helped out on using the command pwdlastset

https://social.technet.microsoft.com/Forums/windowsserver/en-US/ac4d4fb8-0780-4f0d-9e0e-9fec2ff87fbf/using-the-pwdlastset-attribute?forum=winserverpowershell

I decided I would then try to build on that. 

1. create a CSV file and import

2. take each value as it comes in and change it.

I came up with the following but something odd is happening:

its asking for an identity. (I got the idea from another script that I had which creates accounts, see below) any idea what I is wrong in my thinking here?

--------------------------

PS C:\Windows\system32> # Import from CSV
Import-csv c:\scripts\Book1.csv | Foreach-Object { Set-ADUser -Replace @{pwdLastSet=0}}
cmdlet Set-ADUser at command pipeline position 1
Supply values for the following parameters:
Identity:

--------------------------

I got the idea from another script that I had which creates user accounts.  it was similar type of item using the new_ADUser instead of the set-ADuser but the important thing I wanted was to create a for loop but was not sure how in power shell and this seemed to use that.

-----------------------------

# Import from CSV
Import-csv c:\scripts\PSBulkAccountCreation.csv | ForEach-Object {
              
                New-ADUser -Path "OU=users,DC=somename" -Name $_.Name -SamAccountName $_.SamAccountName -Description $_.Description -emailaddress $_.emailaddress -AccountPassword (ConvertTo-Securestring -AsplainText $_.AccountPassword -Force) -Enable $true -ChangePasswordatlogon 0 -PasswordNeverExpires:$true

}

}

-----------------------------

Silent Install of .net 4.5 in powershell issue

$
0
0

Hi All,

I am trying  to install dot netframework 4.5.2 on remote machine also getting 16389 error

$DotNetInst="E:\temp\IE11andPowershellv4\NDP452-KB2901907-x86-x64-AllOS-ENU.exe"

$process = (Start-Process -FilePath $DotNetInst -Argumentlist "/q /norestart" -Wait -Verb RunAs)
Write-Host -Fore Red "Errorcode: " $process.ExitCode

 $process.ExitCode returns 16389

Invoke-Command -ComputerName "Server01" -ScriptBlock { Start-Process -FilePath $DotNetInst -ArgumentsList "/q /norestart" } -Crdential $cred

Can anyone help me out on the same?

MobileIron automation via API v2 in PowerShell

$
0
0

Dear Colleagues, 

I wonder if anybody have encountered challenge with automating Mobile Iron device provisioning ?

I was told to use API v2 for mobile iron device enrollment, but i dont know how to start. 

Can someone advice? 

Format a number with two decimals

$
0
0

I see there's a method for the Double type called .ToDecimal()

I was wondering how that can be used. I am trying to output a number with lots of decimals to a number with only two decimals so that it will be easier to read

Generate a GUI progress bar for DISM or ImageX

$
0
0
We are creating a custom recovery environment, and we're almost done. One of the last things we need to do generate a progress bar for either DISM or ImageX that simply displays the progress in a simple GUI. I know we'll have to start by building a form, but the main question is how to get at the very least the percentage complete on either. The second question is what is a good way of displaying the progress bar. 

Get SQL Agent Job EnumHistory via Powershell

$
0
0

Hi guys!!

I  am using Powershell through DollarU (Workload automation software) to execute SQL Agent job (all steps) or one specific step at a time.  So far so good, everything is working!!  However, when it gets to the point where I want to get the History log information, I can't seem get what I want.

Here is my program:  

param ([parameter (Mandatory = $true)][string]$ServerName,

       [parameter (Mandatory = $true)][string]$JobName,

       [string]$StepName = "")



write-host "Starting SQL Agent Job $($JobName) on Server $($ServerName)"

$date=Get-Date

write-host "It is now: $($date)"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

$srv = New-Object Microsoft.SqlServer.Management.SMO.Server("$ServerName")

$job = $srv.jobserver.jobs["$JobName"]
$jobstart="No"

if (($job))
{

   if ($StepName -ne '')
      {
        $job.Start($StepName)
        $jobstart="Yes"
        Start-Sleep -s 5  # Pause for 5 seconds (optional) - was 30 seconds (v1); v2=5
      }

   else
      {
        $job.Start()
        $jobstart="Yes"
        Start-Sleep -s 5
      }
}

else
{
   $jobstart="Not found"
}

if ($jobstart -eq "Yes")
{
   write-host "Job $($JobName) on Server $($ServerName) started"
   $i=0

   do
   {
     $job.Refresh();
     $iRem = $i % 5;
     $jobrunning=$job.CurrentRunStatus.ToString();

     if ($iRem -eq 0)
     {
       $date=Get-Date
       write-host "Job $($JobName) Processing--Run Step:$($job.CurrentRunStep) Status:$($job.CurrentRunStatus.ToString())... at $($date)"
     }

     Start-Sleep -s 10; # Pause for 10 seconds  - was 60 seconds (v1); v2=10
     $i++;
   }

   while ($job.CurrentRunStatus.ToString() -ne "Idle")
     if ($job.LastRunOutcome -ne "Cancelled")
     {
       write-host "Job Processing done"
     }
     else
     {
       write-host "Job Processing cancelled/aborted"
     }

     #   $jobRunning="TRUE"
     write-host "$($srv.name) $($job.name)"
     write-host "Last job outcome $($job.LastRunOutcome)"
     write-host "Last job outcome $($job.LastRunDate)"

        if ($job.EnumHistory().Rows[0] -ne $null)
        {
           write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
        }

        if ($job.EnumHistory().Rows[1] -ne $null)
        {
           write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
        }


        $LastRun=$job.LastRunOutcome

        if ($StepName -ne '')
        {
           $JobStep = $Job.JobSteps[$StepName]
           Write-Host "Name: $($JobStep.Name) RunDate: $($JobStep.LastRunDate) Status: $($JobStep.LastRunOutCome)"
        }

        else
        {
          $StepCount = $job.JobSteps.Count - 1

        for ($i=0;$i -le $StepCount;$i++)
        {
         $m = $job.JobSteps[$i].LastRunDate
         write-host "Name: $($job.JobSteps[$i].Name) RunDate: $($job.JobSteps[$i].LastRunDate) Status: $($job.JobSteps[$i].LastRunOutCome)"

         if ($job.LastRunDate -gt $m)
             {
                   $LastRun="FailedOrAborted"
             }
       }
     }


     if ($LastRun -eq "Failed")
     {
       write-host "Job returned with Failed status"
       exit 2
     }

     if ($LastRun -ne "FailedOrAborted")
     {
       if ($LastRun -ne "Cancelled")
           {
             exit 0
           }

       else
           {
             write-host "Job Cancelled xxxxx"
             exit 3
           }
        }

     else
     {
             write-host "Job Failed or Aborted"
             exit 2
      }
}

else
{
  write-host "Unable to Start Job $($JobName) on Server $($ServerName)"
  write-host "Reason: Job may not exist or not enabled."
  exit 1
}


When there are no specific step to execute...  when only the jobName is provided, I get the proper information.  When it is only a specific step, the second line (YYYY) returns information from past executions.

 if ($job.EnumHistory().Rows[0] -ne $null)
    {
       write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
    }

    if ($job.EnumHistory().Rows[1] -ne $null)
    {
       write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
    }


In the following picture, you will see the lines of History log information that I got in return for run executed at 10:42 on August 15th (???)

What I would like to get are the following lines of information:

So I tried the following lines of code without any success...

if ($job.EnumJobStepLogs($StepName).Rows[0] -ne $null)
{
  write-host "xxxx $($job.EnumJobStepLogs($StepName).Rows[0].Message)"
}

if ($job.EnumJobStepLogs($StepName).Rows[1] -ne $null)
{
  write-host "yyyyy $($job.EnumJobStepLogs($StepName).Rows[1].Message)"
}

and this...

if ($job.EnumHistory($stepName).Rows[0] -ne $null)
{
   write-host "xxxx $($job.EnumHistory($stepName).Rows[0].Message)"
}

if ($job.EnumHistory($stepName).Rows[1] -ne $null)
{
   write-host "yyyyy $($job.EnumHistory($stepName).Rows[1].Message)"
}

I really don't understand...  and don't know what to try anymore :-(

Can you help me?

Mylene


Mylene Chalut

Passing string array to function creates error

$
0
0

I am trying to call a function with the following parameter signature:

      Param (
        [Parameter(Mandatory=$true)][string]$Subject,
        [Parameter(Mandatory=$true)][string]$JobResult,
        [Parameter(Mandatory=$true)]$Body,
        [Parameter(Mandatory=$true)][System.String[]] $Recipients
      )


I invoke it with:

[string[]] $ToAddresses = @("abc@xyz.com", "sa@xyz.com")
Send-HtmlEmail -Subject "Save to Server" -JobResult "Results" -Body "New Body", -Recipients  $ToAddresses

which returns the error

 A positional parameter cannot be found that accepts argument 'System.String[]'.

If I change the Recipient argument to

Send-HtmlEmail -Subject "Save Outlook to Server" -JobResult "Results" -Body "New Body", -Recipients  (,$ToAddresses)

the error is 

A positional parameter cannot be found that accepts argument 'System.Object[]'
How can I do this correctly? 

WMF 5 Prerequisites for Windows 7

$
0
0

Is it still necessary to install WMF 4 before installing WMF 5 on Windows 7 SP1 machines (PS Version 2.0)?  I thought that requirement was not supposed to be needed with the production release of WMF 5, but from what I've been reading folks are saying WMF 4 is still needed.

Thanks!

IndexOf - Case insensitivity errors

$
0
0

Can't seem to get the IndexOf overload to work to support case insensitive lookups.  Can you help me understand what I'm doing incorrect?

$a = 'a','b','c'
$a.IndexOf('B',[System.StringComparison]::CurrentCultureIgnoreCase)

I receive this error...

Cannot find an overload for "IndexOf" and the argument count: "2".
At line:1 char:1
+ $a.IndexOf('B',[System.StringComparison]::CurrentCultureIgnoreCase)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

The Get-Member shows that there is an overload to adjust the comparisonType

($a | Get-Member -Name IndexOf).Definition
int IndexOf(char value), int IndexOf(char value, int startIndex), int IndexOf(char value, int startIndex, int count), int IndexOf(string value), int IndexOf(string value, int startIndex), int IndexOf(string value, int startIndex, int count), int IndexOf(string value, System.StringComparison comparisonType), int IndexOf(string value, int startIndex, System.StringComparison comparisonType), int IndexOf(string value, int startIndex, int count, System.StringComparison comparisonType)

PSVersion                      5.0.10586.494                                                                                                                                            

Need help with script to change local administrator password

$
0
0

Hi I am trying to create/run a script to change the local administrator password on a list of servers off of a text file. I have had no success and I thought this would be pretty easy. Below is the script I foraged from different users trying to do the same thing. Please excuse me I am still learning PS so this might be an easy answer or just a stupid mistake on my part. Thanks for any help or advise it is much appreciated!

$computers=Get-Content-PathC:\Temp\serverlist.txt


$user

="administrator"


$Password

=Get-Content-PathC:\Temp\password.txt


Start-Transcript

c:\temp\pwlogging.txt


$PasswordCount

=0


Foreach

($computerin$computers) {


$newpass

=[adsi]"WinNT://$computer/$user"


$newpass

.SetPassword($Password[$PasswordCount])


$newpass

.SetInfo()


$PasswordCount

++


echo

"Setting password for$computer$userto$($Password[$PasswordCount])"


}


Stop-Transcript

Creating SharePoint List from template using client runtime

$
0
0

I'm using the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime assemblies and I'm trying to create a list in SharePoint from a custom template I have created.

The template info is as follows:

BaseType             : GenericList
Description          : Pending Reboots
FeatureId            : 00bfea71-de22-43b2-a848-c05709900100
InternalName         : PendingRebootsTemp.stp
IsCustomTemplate     : True
Name                 : PendingRebootsTemp
ListTemplateTypeKind : 100

I can create a new blank list via the following code, but I can't figure out how to create it from the template listed above. I'd like to use the template as I already have the fields set up the way I need.

$listinfo =New-Object Microsoft.SharePoint.Client.ListCreationInformation
$listinfo.Title = 'PendingRebootsTemp'
$ListInfo.TemplateType = "100"
$list = $web.Lists.Add($listinfo)
$context.ExecuteQuery()

I'm thinking this shouldn't be too difficult, but I Can't find it anywhere. Any tips?

PowerShell ISE - NuGet-anyCPU Initialization Failed

$
0
0

I installed the module browser for the ISE but am unable to browse modules on the PowerShell gallery. 

When launching the ISE I receive a message indicating that the module browser requires NuGet-anycpu.exe to interact with NuGet based galleries. Shortly after clicking the Accept button I receive a message that "Initialization failed. Unable to find package provider 'NuGet'.

Any ideas on how to get past this?

I've tried the following:

- Setting 32-bit and 64-bit execution policies to unrestricted
- Launching ISE as administrator
- Successfully installed the NuGet provider via Install-PackageProvider -name NuGet -Force


Get-VM Details from Hyper-V Server

$
0
0

Dear All ,

Could we get Hyper-V VMs Details like VMname,IP Address,operating system,CSV path, memory ,hard disk,virtual FC etc. in Cluster environment .


Best Regards, Hussain

Remove-ADObject -- Access Is Denied

$
0
0

I have an array of computer objects which need to be deleted from Active Directory. This is going to be setup as a scheduled task, so I will not be able to interact with the script once it is fully deployed.  I am doing my testing within PowerShell ISE and the following are the steps I have gone through so far. 

1)

foreach ($computer in $inactiveComputers)
{
  Remove-ADComputer -Identity $computer.Name
}

Opens a dialog box asking to confirm to delete objects.  Will not work as I require it to run with no user interaction.

2)

foreach ($computer in $inactiveComputers)
{
  Remove-ADComputer -Identity $computer.Name -Confirm:$false
}

Error Caught:

The directory service can perform the requested operation only on a leaf object

3)

foreach ($computer in $inactiveComputers)
{
  Get-ADComputer $computer.Name | Remove-ADObject -Recursive
}

Opens a dialog box asking to confirm to delete objects.  Will not work as I require it to run with no user interaction.

4)

foreach ($computer in $inactiveComputers)
{
  Get-ADComputer $computer.Name | Remove-ADObject -Recursive -Confirm:$False
}

Error Caught:

Access is Denied

5)

Reopened PowerShell ISE as an administrator and ran the same set of commands again

Error Caught:

Access is Denied

Note: 

The computer objects are NOT protected by accidental deletion. 

Some thoughts on how to accomplish this would be great. 



Colin Domansky


Powershell to Inject Hostname into a Hyper-V based VM before Network Configuration

$
0
0

Hello Team,

I am looking for a powershell way of Injecting Hostname [Or lets say computer name rename] of a VM running on a Hyper-V Host. There is no Network Configuration on this VM, so PSremoting is not the option here, and not looking for unattended answer file injection into VHD.

I am looking for any Hyper-V WMI Class method to inject hostname into the vms running on top of this hyperv host or if there is any other way, please mention.


Thank You.

Regards,

Subhash


Regards,
Subhash Konduru
------------------------------------------------------------------------------------
Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Remove-Item Requested registry access is not allowed

$
0
0

Help please,

I have written a Powershell script that is trying to use Remove-Item to delete some Registry keys. I am running under Admin. if I go into Regedit it will let me delete the keys but if I run the Powershell script I get "Remove-Item Requested registry access is not allowed."

I have checked the permissions for the key and it says I have Delete permission. I am using the PowerShell ISE and am on Windows 7. I have tried -Force and -Recurse but makes no difference, neither does reducing UAC to minimum. It also makes no difference if I start PowerShell ISE with Administrator privileges. Why can I delete from within Regedit but not from PowerShell?

Be grateful for some help.

Dave

Regular Expression for a string in a line

$
0
0

Hi 

Using PowerShell 5

I have a text file:

$mytextfile = get-content c:\myfile.txt

The file contains a lot of lines with text.

I want to find all lines that have the words "catch me" in the text.

Any tips?

brgs

Bjørn


Viewing all 21975 articles
Browse latest View live


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