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

Run Powershell script as Scheduled task, that uses Excel COM object

$
0
0

What am I missing here..

 

I have  Powershell script that uses the Quest AD cmdlets to get computer information from AD and populate an Excel spreadsheet with the data.

The script works fine, so I created a batch file and started the script from there (which works fine as well). It populates the excel spreadsheet, saves and closes the file.

If I run the script as a scheduled task, I can see from the logging that it supposedly gets the computers from AD, and runs through them. But a file is never saved, I have tried to run the scheduled task with admin credentials.

What am I forgetting?


powershell - add outlook appointment in other user mail box

$
0
0

Hello,

I am need to add appointments in other user mailboxes frequently. I need to achieve this using powershell script. 

What is the best way to automate this process using PS ?

Thanks You.


Prathap SV

Watch folder and email directory path if files added or changed

$
0
0

Hi,

Im looking all over the internet for a powershell script thats send me an email with a path in the body when a files in a specific folder has added or changed. 

The email has to be sent over SMPT with SSL enabled

Is there anybody who can help me?

ps: sorry for my bad english. 

outlook api response not valid json string

$
0
0

outlook api response include  

border=\"border:none;"0"\" alt=\"Microsoft\"

, it is not valid json string


I want to change local administrator password

$
0
0
I want to change local administrator password using power shell script. 

how to edit local gpo

$
0
0

Hello,

I'd like to edit local GPO which resides in:

gpedit.msc > Computer Configuration > Windows Settings > Security settings > Local Policies > Security Options

Then there is a GPO called:

Accounts: Administrator Account Status

I need to make it from Enabled to Disabled by Powerhsell and  I tried to do this by a means of Registry keys.

I have tried to compare registry files before and after changing this value to understand where this key is stored by doing something like that:

# PowerShell Compare-Object Registry Settings
$Pre = "C:\PShell\RegOwner.reg"
$After = "C:\PShell\NewOwn.reg"

Compare-Object $(Get-Content $Pre) $(Get-Content $After)

But the thing is Powerhsell is getting stuck when I do this.

Currently I'm in a dead end.

Does anybody know how to change this local GPO with powershell? Maybe there are some other options that Registry?

Thanks.

PowerShell remoting

$
0
0

I need to run PowerShell commands on a remote Windows Server 2008 R2 server from a Windows Client.

I have 2 different configurations:

  • Client and server are member of a workgroup
  • Client is member of a workgroup while the server is member of a domain

In both cases I do know the credentials of a user with Administrator's rights on the Windows Server 2008 R2 server.

I found several examples but none works for me.

WinRM is enabled on the Windows server 2008 R2 server.

Can anybody please provide a sample to start from?

Regards

marius

how to move files from one location to another location using powershell

$
0
0

Hi,

My files are present in D:\MFT .some checks are applied and if they pass those check I want the files to be transfered to aonther location ie D:\abc\batch.

How do i move the files from one location to another ?

Thanks


Use PS to create new local admin on clients (Servers)

$
0
0

We currently perform the following using GPO:

* Disable the local Administrator user on the client.

* Create a new user on the client named "AABBCCDD".

* Set the password for user "AABBCCDD" to "XXYYZZ123".

* Place the new user "AABBCCDD" into the local Administrators group on the client.

Microsoft have removed this functionality as the password it sent encoded but still retrievable so I'm looking for a new solution. I've looked at LAPS but that does not do all of the above. Can this be done using PowerShell?

The criteria is:

* The password for user "AABBCCDD" must not be accessible to anyone other than the Domain Admins.

* All client users called "AABBCCDD" will be given the same password.


| +-- JDMils |

count of Active Users

$
0
0

Hi Team,

Please correct below script, looking count of active users.
Get-BrokerSession |?{$_.SessionState -eq "Active"| measure _.count


subu

SQLPS error related to powershell version

$
0
0

Hello,

After we've upgraded to SQL 2016 and deployed SQL management studio 2016 on some servers, SQLPS module stopped working. Once I try to launch SQLPS in powershell, it displays following error message:

Import-Module : The version of the loaded PowerShell is '2.0'. The module 'D:\Microsoft SQL Server (x86)\130\Tools\Powe
Shell\Modules\SQLASCMDLETS\SQLASCMDLETS.psd1' requires a minimum PowerShell version of '4.0' to execute. Please verify
the installation of the PowerShell and try again.
t D:\Microsoft SQL Server (x86)\110\Tools\PowerShell\Modules\SQLPS\SqlPsPostScript.ps1:8 char:33
 if($m -ne $null) { Import-Module <<<<  $m -Global }
   + CategoryInfo          : ResourceUnavailable: (D:\Microsoft SQ...LASCMDLETS.psd1:String) [Import-Module], Invalid
  OperationException
   + FullyQualifiedErrorId : Modules_InsufficientPowerShellVersion,Microsoft.PowerShell.Commands.ImportModuleCommand

Thing is, that the powershell version installed on the server is version 5.0:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  117

But once I invoke the SQLPS that ends with error, the command $PSVersionTable.PSVersoin throws following value:

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

This happened only on servers where the SQL Management Studio 2016 was deployed. Does anyone else experience this problem? Any idea how to fix it?

Thanks,

Daniel

Copy lines of text from one .txt to another .txt

$
0
0

Hi I am new to Powershell and understand very little about it. What i need to do is copy a line of text from one document to another. 

For example,

What i need to do is copy a MacAddress stored in a .txt and copy it into another .txt as part of a line already contained in that .txt 

Like this 

Example text "00-00-00-00-00-00" Example text 



$Image.DrawString centering string with left and right padding

$
0
0

I'm trying draw string on image in vertical middle, but I don't know how do padding from left and right of this text. If I have very big string, it does not fit on image, not making new line...

I have now second powershell code:

$swp_curr_dir = split-path -parent $MyInvocation.MyCommand.Definition[void][reflection.assembly]::loadwithpartialname("system.windows.forms")FunctionAddTextToImage{# Orignal code from http://www.ravichaganti.com/blog/?p=1012[CmdletBinding()]
    PARAM ([Parameter(Mandatory=$true)][String] $sourcePath,[Parameter(Mandatory=$true)][String] $destPath,[Parameter(Mandatory=$true)][String] $Title,[Parameter()][String] $Description = $null)Write-Verbose"Load System.Drawing"[Reflection.Assembly]::LoadWithPartialName("System.Drawing")|Out-NullWrite-Verbose"Get the image from $sourcePath"
    $srcImg =[System.Drawing.Image]::FromFile($sourcePath)Write-Verbose"Create a bitmap as $destPath"
    $outputIImg = new-object System.Drawing.Bitmap([int]($srcImg.width)),([int]($srcImg.height))Write-Verbose"Intialize Graphics"
    $Image =[System.Drawing.Graphics]::FromImage($outputIImg)
    $Image.SmoothingMode="AntiAlias"

    $Rectangle =New-ObjectDrawing.Rectangle0,0, $srcImg.Width, $srcImg.Height
    $Image.DrawImage($srcImg, $Rectangle,0,0, $srcImg.Width, $srcImg.Height,([Drawing.GraphicsUnit]::Pixel))Write-Verbose"Draw title: $Title"
    $Font = new-object System.Drawing.Font("Bauhaus 93",130,"Bold","Pixel")#get font size
    $font_size =[System.Windows.Forms.TextRenderer]::MeasureText($Title, $Font)
    $font_size_width = $font_size.Width
    $font_size_height = $font_size.Height# calc text in middle
    $text_in_middle_top_offset =($srcImg.Height- $font_size_height)/2
    $text_in_middle_left_offset =($srcImg.Width- $font_size_width)/2#styling font
    $Brush =New-ObjectDrawing.SolidBrush([System.Drawing.Color]::FromArgb(255,255,255,255))#lets draw font
    $Image.DrawString($Title, $Font, $Brush, $text_in_middle_left_offset, $text_in_middle_top_offset)Write-Host $text_in_middle_left_offsetWrite-Verbose"Save and close the files"
    $outputIImg.save($destPath,[System.Drawing.Imaging.ImageFormat]::jpeg)
    $outputIImg.Dispose()
    $srcImg.Dispose()}AddTextToImage-sourcePath ($swp_curr_dir +"\image.jpg")-destPath ($swp_curr_dir +"\output.jpg")-Title"Some long long long long long long long long long long long long string here"

cmd /c pause

Powershell cant pass string in ConvertTo-SecureString to connect-msonline.

$
0
0

When we try to pass "password" as string shown below to connect-msonline fails.

$password = "password" | ConvertTo-SecureString -asPlainText -Force
$username = "user@msonline.com"
Import-Module MSOnline
$credential = New-Object System.Management.Automation.PSCredential ($username,$password)
Connect-MsolService -Credential $credential

But sending password as string succeeds.

$password = 'password' | ConvertTo-SecureString -asPlainText -Force
$username = "user@msonline.com"
Import-Module MSOnline
$credential = New-Object System.Management.Automation.PSCredential ($username,$password)
Connect-MsolService -Credential $credential

We have application already designed passing string as it shown in all MS technet and we cant modify it accept string. Can any one help us to understand why it works for character in our case ?

Script will throw error when a value is empty

$
0
0

Hello,

I have a simple script which sets a VM to have an availability set if one is specifies, and does not if there isn't one specified.  The script works, but it throws and error.  I have tried using -erroraction runsilent but I still see an error. I would imagine there is a much better way to accomplish this but I'm new to PowerShell:

 
#Check to see whether or not an Availability Set will be used.
    $AVstatus = Get-AzureRmAvailabilitySet -ResourceGroupName $RGname -Name $AVset -ErrorAction Ignore
    if ($AVStatus -eq $null)
    {"No Availabilty set was specified.  This VM will be deployed without one."
        $vm = New-AzureRmVMConfig -VMName $vmName -VMSize $vmsize
    }
    else
    {"Machine will be deployed to the following Availability set: $AVset "
        $vm = New-AzureRmVMConfig -VMName $vmName -VMSize $vmsize -AvailabilitySetID "/subscriptions/$subscriptionID/resourceGroups/$RGname/providers/Microsoft.Compute/availabilitySets/$AVset"
    }

When there is no AVset specified in the excel spreadsheet I receive the error below, but ultimately the script works in either case:

Get-AzureRmAvailabilitySet : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try

the command again.

At line:1 char:61

+ ... zureRmAvailabilitySet -ResourceGroupName $RGname -Name $AVset -ErrorA ...

+                                                            ~~~~~~

    + CategoryInfo          : InvalidData: (:) [Get-AzureRmAvailabilitySet], ParameterBindingValidationException

    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Compute.GetAzureAvailabilitySetCommand


Backup GPO Link and Import it in the new one

$
0
0

Hey guys,

I am able to import everything from a GPO, settings, security filtering but the OUs linked to it I am still not able to "replicate" from the imported GPO

Do you have any smart way to do it?

Thanks

Help Me Add An Output Telling Me Host is Down When Unable to Ping

$
0
0

Hi all, I have the following code that works perfectly well when retrieving a list of servers from a list and then outputting the domain name and the IP address in a comma seperated list.

Can someone please help me give a blank output when server cannot resolve an IP?

My problem however is that when the Server is down and cannot not resolve an IP, my output writes the IP of the previous working Server's IP instead of giving me a blank output. Can someone help me resolve this issue? It would be much appreciated!

$servers = get-content "C:\Users\Ly\Desktop\Servers.txt"
$serversAndIps ="C:\Users\Ly\Desktop\IPAddresses.csv"

$results = @()
foreach ($server in $servers)
{
    $result = "" | Select ServerName , ipaddress
    $result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
    $addresses = [System.Net.Dns]::GetHostAddresses($server)

    foreach($a in $addresses) 
    {
        "{0},{1}" -f $server, $a.IPAddressToString
        $result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
    }

    $result.servername = $server
    $result.ipaddress = $a.IPAddressToString
    $results += $result
}

$results | export-csv -NoTypeInformation $serversandIps


Hash Table - Create copy to Edit, so as to not edit original Hash Table

$
0
0

Hello all,

I'm currently baffled by this one. I'd like to create a copy of a Hash Table to edit, while leaving the original Hash Table intact. Seems like a simple task, yet I cannot figure out how to do it. Here is some code that illustrates what I'm seeing. I create what I think is a copy of the original Hash Table, but when I edit a value in the "Copy", it also edits a value in the original. I'd like to edit the value in the copy, while keeping the original Hash Table intact. What am I missing here?

cls

#Create Hash Table and create entry
$HashTable = @{}
$HashTable[1] = "one"

#Create "copy" of original Hash Table
$HashTableCopy = $HashTable

#Edit value in "copy" of original Hash Table
$HashTableCopy[1] = "two"

#Display contents of "copy" and original Hash Table
write-host "Hash Table Copy"-ForegroundColor Yellow
$HashTableCopy

write-host "`n`nHash Table Original" -ForegroundColor Cyan
$HashTable

How to retrieve a list of users who have the 'write ServicePrincipalName' right

$
0
0

Hello All

Can someone please help me with the following problem

On the surface of it this would not appear to be too difficult, however, it is proving more difficult than I first thought

If you looked a various documentation like the following 

https://www.alexandreviot.net/2014/09/30/sql-server-could-not-register-the-service-principal-name-spn/

(and I have seen several other documents which say the same thing)

if you want the add an SPN (service principal name) record to AD you need the following 'two' rights

'Validate write to service principal name" and "write service principal name"

now if you look at a computer object using Active Directory Users and Computers (dsa.msc) then click on the 'Security' tab you can see the first right Validate write to service principal nameon the initial list of permissions. In order to see the other right "write service principal name"you need to click on 'Advanced' then select a user from the list and select 'Edit' then select the 'Properties' (now this is important thing which I will come to later) Tab

So basically when you look at 'Advanced rights' there is a tab for 'Object' and another for 'Properties' e.g. rights to the 'object' and rights to the 'properties' of the object.

Using PowerShell I can retrieve a list of users/computers/groups who have rights to the "Validate write to service principal name"(e.g. users who have Allow Read or Allow Write etc.. to this right for the 'object') 

However, I cannot obtain a list of users etc who have the  "write service principal name" right. 

I think the problem is PowerShell is only returning rights to 'objects' and not rights to 'properties' of those objects

for example here is a simple piece of code to get the "Validate write to service principal name"rights as these <g class="gr_ gr_4968 gr-alert gr_spell gr_disable_anim_appear ContextualSpelling" data-gr-id="4968" id="4968">writes</g> are represented by GUIDs and 'f3a64788-5306-11d1-a9c5-0000f80367c1'<g class="gr_ gr_4969 gr-alert gr_spell gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="4969" id="4969">equats</g> to Validate write to service principal name

https://msdn.microsoft.com/en-us/library/ms684417(v=vs.85).aspx

$ComputerName="Server01"

$ADObject=Get-ADObject-Identity$ComputerName.distinguishedName-Properties*

$ADObject.nTSecurityDescriptor.Access|where {$_.ObjectType-eq'f3a64788-5306-11d1-a9c5-0000f80367c1'

I have another script that translates these GUIDs via the Schema and shows them all. However again I cannot see to get the <g class="gr_ gr_4970 gr-alert gr_spell gr_run_anim ContextualSpelling" data-gr-id="4970" id="4970">write</g> service principal name via a script and match this up to what I see in the GUI (dsa.msc)

I need to do a scan of my AD and check who has 'both' the above rights and at the moment  I can only get one right e.g. "Validate write to service principal name"

Any help most welcome

Thanks

__AAnotherUser




AAnotherUser__

How to retrieve a list of users who have the 'write ServicePrincipalName' right

$
0
0

Hello All

Can someone please help me with the following problem

On the surface of it this would not appear to be too difficult, however, it is proving more difficult than I first thought

If you looked a various documentation like the following 

https://www.alexandreviot.net/2014/09/30/sql-server-could-not-register-the-service-principal-name-spn/

(and I have seen several other documents which say the same thing)

if you want the add an SPN (service principal name) record to AD you need the following 'two' rights

'Validate write to service principal name" and "write service principal name"

now if you look at a computer object using Active Directory Users and Computers (dsa.msc) then click on the 'Security' tab you can see the first right Validate write to service principal nameon the initial list of permissions. In order to see the other right "write service principal name"you need to click on 'Advanced' then select a user from the list and select 'Edit' then select the 'Properties' (now this is important thing which I will come to later) Tab

So basically when you look at 'Advanced rights' there is a tab for 'Object' and another for 'Properties' e.g. rights to the 'object' and rights to the 'properties' of the object.

Using PowerShell I can retrieve a list of users/computers/groups who have rights to the "Validate write to service principal name"(e.g. users who have Allow Read or Allow Write etc.. to this right for the 'object') 

However, I cannot obtain a list of users etc who have the  "write service principal name" right. 

I think the problem is PowerShell is only returning rights to 'objects' and not rights to 'properties' of those objects

for example here is a simple piece of code to get the "Validate write to service principal name"rights as these writes are represented by GUIDs and 'f3a64788-5306-11d1-a9c5-0000f80367c1' equats to Validate write to service principal name

https://msdn.microsoft.com/en-us/library/ms684417(v=vs.85).aspx

$ComputerName="Server01"

$ADObject=Get-ADObject-Identity$ComputerName.distinguishedName-Properties*

$ADObject.nTSecurityDescriptor.Access|where {$_.ObjectType-eq'f3a64788-5306-11d1-a9c5-0000f80367c1'

I have another script that translates these GUIDs via the Schema and shows them all. However again I cannot see to get the write service principal name via a script and match this up to what I see in the GUI (dsa.msc)

I need to do a scan of my AD and check who has 'both' the above rights and at the moment  I can only get one right e.g. "Validate write to service principal name"

Any help most welcome

Thanks

__AAnotherUser

posted again as the first one did not appear to come out correctly




AAnotherUser__

Viewing all 21975 articles
Browse latest View live