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

Creating Local (non-domain) admin user on remote computers

$
0
0

Hello,

We are working with moving a number of our virtual servers and once the migration is completed for each server, the server is not on the domain so local admin access is required to get it back on the domain.  To that end I want to add a local user account to these servers that is in the administrator group.  I've found a post that's getting me half-way there...it allows me to create a local user via Powershell (I'm using version 3) on my computer (localhost), but when I try to do this to a remote server where I do have administrative priviledges it says the local user account already exists (I think it's ignoring the remote server name and only looking at my local computer).

Any tips, ideas on how I can take this code to read through an input list of servers and add a local user id (that is Admin and has a password that never expires) to those servers.  I'd prefer to not have to run this as a function but to load up the script in Powershell ISE.  I'll hardcode in the username and password in the script instead.

function create-user($username, $password)
 {

$computer = [ADSI]“WinNT://serverA”
foreach ($user in $computer.psbase.children)
 {
 if ($user.Name -eq $username)
 {
 Write-Host $user.Name “already exist.”
Return
 }
 }
 $user_obj = $computer.Create(“user”, “$username”)
 $user_obj.Put(“description”, “$username”)
 $user_obj.SetInfo()
 $user_obj.SetPassword($password)
 $user_obj.SetInfo()
 $user_obj.psbase.invokeset(“AccountDisabled”, “False”)
 $user_obj.SetInfo()
 if ($user.Name -eq $username)
 {
 Write-Host “$username created.”
Return
 }
 else
 {
 Write-host “Error Creating $username”
}
 }
Thank you.

Override Default Error Message in Function Parameters

$
0
0

Hello ,

          Is there a way to override the Default Error Message that i get for a validation error in parameter that i being passed by the user. In most of the cases the user will not be understanding what exactly is the mistake he has done by reading the error Message.

Any ideas?


S.Arun Prasath HP ARDE TEAM

Event Handler Between Reboot states using Powershell

$
0
0

Hi,

I need some help writing an event handler for a powershell script that would meet the following requirement:

1.  Continue Upon a restart

2.  Continue Upon a sleep state

3.  Continue Upon a hibernation state.

WPF UI application using powershell cmdlets

$
0
0

Hi,

I plan to create a C# WPF UI application which uses my own powershell cmdlets to do all the works like adduser, addgroup, getmachineinfo...

I have foresee some issues in this model. For example, cmdlets' asynchronous call using background job and Powershell eventing do not fit the C# UI's event model. To handle a background job's result, the main thread need to query the result proactively. For handle the events (engine/.net object/wmi), UI need to have a thread to wait for the events. This could be an ill-formed workflow and might cause a big pain for UI to handle asynchronous call and eventing.

Could anybody share your experience on the Pros and Cons of using powershell cmdlets for a WPF application's backend calls?

Appreciate any input.

 

Thanks

Leon

 

 

 

 

 

How to get all records using Invoke-webrequest?/Why Invoke-webrequest returns only first 2000 Records?

$
0
0
invoke-webrequest content returning only 2000 records though it has around 4000 records in web api.
The same url if I give in excel oData Data feed I am getting all the records.

See the below script
Script:
$QueryResult= (Invoke-WebRequest -Uri $ODataURI -UseDefaultCredentials)

[xml]$xmlResult=$QueryResult.content

foreach($obj in $xmlResult.feed.entry.content.properties)
{   
    $Name=$obj.Name;
    $IsAvail=$obj.isAvail.'#text';   
    $PGroup=$obj.PGroup
...
...
}

I am exporting the above result as a CSV file and my CSV file contains only 2000 records. 
But,  $xmlResult.feed.Count --> it Shows 4000 Records.

The same Odata url if I give in excel oData Data feed I am getting all the 4000 records.

So Please help me how can I get all the records using power shell.


Thanks
A Pathfinder..
JoSwa


If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"Best Online Journal

Last added to Security Group

$
0
0

Hello All,

i am trying to get the last added users to security Group X but i don't know how to achieve this ? anyone worked with solution before ?

any help please ?

Excell empty cell

$
0
0

Any idea why below doesnt work???

$virtualNetwork = $csdWorkBook.worksheets.item("Virtual Network")

$test=$virtualNetwork.cells.item(4,7)  #check if this cell is empty

if ($test -eq "") {
write-host "Blank"
} else {
write-host "Not blank"

}

WSUS and PowerShell

$
0
0

Hello Everyone,

       I have a Windows 2008 R2 WSUS server with WSUS 3.0 sp2 installed. Recently Microsoft released an update for the IE vulnerability (KB2964358) which affects all versions of Internet Explorer. I have released the update to all our windows machines and would like to report on which machines still need the update. The problem is the built in reporting does not have the ability to produce such a report. Does anyone have any ideas on how to accomplish this task with PowerShell? Any assistance would be greatly appreciated.




Check if drive exists, If not map

$
0
0

I want to check for the existance of a drive mapping (called X in this example) and if it does not exist, I want to map it. Here is what I have so far:

$driveCheck = Get-PSDrive | Where-Object { $_.Name -match "X" } | Select-Object name

# This provides the following output:

# Name
# ----
# X

$map = new-object -ComObject WScript.Network
$map.MapNetworkDrive("X:", "\\Server\Share", $true, "Domain\user", "password")

Exchange Edge clone config import in Exchange Management shell throws error "You cannot call a method on a null-valued expression"

$
0
0

Hi All,

During the Coexistence of Exchange 2007 to 2010 Migration..

I have create new Edge Scubscription in Edge Server 1 and Export the Edge Configuration File from Edge Server 1.

While trying to Import Edge configuration to Edge Server 2 in Exchange Management Shell, I am getting the below Error.

I have tried importing on both Exchange 2007 and 2010 Edge Servers, getting the same error.


"Importing Edge configuration information Failed.
Reason: You cannot call a method on a null-valued expression."

Please help in resolving this issue...

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?

IE & powershell

$
0
0

hi everyone,

i try to add a website as trusted into internet explorer and at the same time authorize all the ActiveX option on all the trusted websites... actually i added the website to the trusted list but i don't find a way to authorize ActiveX on it.

this is the code i am using :

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item *.domain.com
set-location *.domain.com
new-itemproperty . -Name http -Value 2 -Type DWORD

thank you for help : :)

get-messagetrackinglog Distribution Group Expand Group

$
0
0

Hi All,

Is there a way, to get the logs form a Distribution Group. I would like to view the users that were in the group at the time the email was sent?

The below command is useful, but I would like to see which users recieved an email. i.e on Monday a user/email could be a member ofDG@xyz.com, but on Tuesday they could have been removed and therefore wouldnt have received the email sent to the DG. 

Get-TransportServer | get-messagetrackinglog -Recipients DG@xyz.com -EventId RECEIVE -Start 12/04/2014 -ResultSize Unlimited | ft -AutoSize

Thank you in advance

32 bit vs 64 bit odbc connection problems

$
0
0

Good morning,

I am trying to connect a powershell script that worked fine on a 32 bit system, but now will not work on a 64 bit system.  This script connects to a odbc connection and connects to a remedy ticket system and pulls information to move over to my Outlook calendar.

The error am getting is:

Exception calling "Open" with "0" argument(s): "ERROR [IM014] [Microsoft][ODBC Driver Manager] The specified DSN contains an architecture mismatch between the Driver and Application"
At C:\Users\Public\Documents\RemedyCRQ.ps1:25 char:17
+ $connection.Open <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

***********************************************************************************

The code that is running this is below:

$script:showWindowAsync = Add-Type –memberDefinition @”
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
“@ -name “Win32ShowWindowAsync” -namespace Win32Functions –passThru

$null = $showWindowAsync::ShowWindowAsync((Get-Process –id $pid).MainWindowHandle, 2)


$connection = New-Object System.Data.Odbc.OdbcConnection
$command = New-Object System.Data.Odbc.OdbcCommand
$command.Connection = $connection

$remedyTickets = @()

$connectionString = "DSN=remedy"

$connection.ConnectionString = $connectionString

$connection.Open()

I would appreciate it if someone had some insight to offer.  I've looked around and have created the ODBC connection on the 32 bit odbc version c:\windows\sysWOW64\odbcad32.exe.  Doesn't seem to have changed anything.  Ive created it both as a user and system DSN.

Powershell is auto logging me into website?

$
0
0

I ran this code and it allowed me to login to the website and it downloaded everything into a text file, but after the first try it as been giving me an error: "Property 'value' cannot be found on this object make sure it exists and is settable." It's been about an hour since I ran it and it worked and I didn't change the code. I cleared the cookies in internet explorer and deleted everything out of the appdata cookies folder (Only reason I could figure it was doing this was because I was already logged into the page).

I just edited the script so that it doesn't try to login first and just grabs the page and for some reason the script it automatically logging me in now, because it's returning the information that is only view able once you login. What could cause this and how do I make it where it has to login each time?

Here is the powershell code:

$username = "user" 
$password = "pass" 
$ie = New-Object -com InternetExplorer.Application 
$ie.visible=$false
$ie.navigate("website") 
while($ie.ReadyState -ne 4) {start-sleep -m 100} 
$ie.document.getElementById("username").value = "$username" 
$ie.document.getElementById("password").value = "$password" 
$ie.document.getElementById("click").click()
start-sleep 20 
$ie.Document.body | Out-File -FilePath c:\web.txt 

Here is the website code:

form method="POST" action="login.php" name="loginform"><div class="login" align="center"><p class="indent">Sign-in to your account</p></div><div class="loginbot"><div class="email">Email Address: <br /><input name="username" type="text" value="" size="25" /><br /><input type="checkbox" name="remember" value="checkbox" class="small_chk1" value="ON"/>Automatically sign-in<br /></div><div class="pass">Password:<br /><input name="password" type="password" size="25" /><br /><a href="login.php?ti=password">Forgot your password?</a><br /></p></div></div><div class="logbut"><input type="hidden" name="ti" value="do_login"><input type="submit" value="Login ->" name="click" style="border-style: outset; border-width: 1; font-family:Verdana; color:#FFFFFF; font-size:10pt; background-image:url('images/clickbg.gif')"></div><br /><br /></form>



Pin items to Windows 8 Taskbar

$
0
0

Guys.

I found this powershell function on the internet for adding items to the taskbar on Windows 7\8 The function works fine when running it against a single item

for example

Pin-Taskbar -Item "C:\Windows\System32\mspaint.exe" -Action Pin

What I am trying to do is add multiple items to the taskbar in one go. As an example a user over time adds many items. I have another script that backs everything that is in C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar up to a network share. I would then like the script below to add everything in say\\Servername\some_share and add them to the Taskbar.

Have been playing around with the script but not quite getting there. Can anyone help? Thanks in advance

function Pin-Taskbar([string]$Item = "",[string]$Action = ""){
    if($Item -eq ""){
        Write-Error -Message "You need to specify an item" -ErrorAction Stop
    }
    if($Action -eq ""){
        Write-Error -Message "You need to specify an action: Pin or Unpin" -ErrorAction Stop
    }
    if((Get-Item -Path $Item -ErrorAction SilentlyContinue) -eq $null){
        Write-Error -Message "$Item not found" -ErrorAction Stop
    }
    $Shell = New-Object -ComObject "Shell.Application"
    $ItemParent = Split-Path -Path $Item -Parent
    $ItemLeaf = Split-Path -Path $Item -Leaf
    $Folder = $Shell.NameSpace($ItemParent)
    $ItemObject = $Folder.ParseName($ItemLeaf)
    $Verbs = $ItemObject.Verbs()
    switch($Action){
        "Pin"   {$Verb = $Verbs | Where-Object -Property Name -EQ "Pin to Tas&kbar"}
        "Unpin" {$Verb = $Verbs | Where-Object -Property Name -EQ "Unpin from Tas&kbar"}
        default {Write-Error -Message "Invalid action, should be Pin or Unpin" -ErrorAction Stop}
    }
    if($Verb -eq $null){
        Write-Error -Message "That action is not currently available on this item" -ErrorAction Stop
    } else {
        $Result = $Verb.DoIt()
    }
}

Script will not work

$
0
0

Hello,

I am running this following script:-

# Bulk Mailbox Export for users selected from CSV File

 
# Script Starts here
$Users = Import-Csv c:\users.csv
 
foreach ($Users in Import-Csv ./users.csv)
{ New-MailboxExportRequest -Mailbox $Users.Alias -Filepath"\\Server\c$\exportpst\$($Users.Alias).pst }
{
}

I keep getting the same error:- Cannot validate argument on parameter 'Mailbox'. The argument is null. Supply a non-null argument and try the command a
gain.
    + CategoryInfo          : InvalidData: (:) [New-MailboxExportRequest], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,New-MailboxExportRequest

Please can you help?

Kind Regards,

PenDraKon


If statement to join users to AD groups

$
0
0

Hi All,

I'm trying to create a script that does the following:

1. Copies AD group memberships from a source user to the target user

2. Checks whether the target user is a member of GroupA or GroupB

3. Then says If target user is a member of GroupA remove membership & If user is a member of GroupB remove membership.

Copying groups from other users saves a lot of work but it also puts them in a few groups they should not be in i.e. directors! If someone could help me with this I would be most grateful!

Thanks

Add domain user as sysadmin in SQL Server 2012 using PowerShell

$
0
0

Hi,

I am using the following PowerShell script to add a domain user to SQL Server 2012 as sysadmin, but I encounter an exception.

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null; $svr = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "SQL2012"; $svrole = $svr.Roles | where {$_.Name -eq 'sysadmin'}; $svrole.AddMember("domainname\username");

The exception it throws is as follows:

Exception calling "AddMember" with "1" argument(s): "Add member failed for ServerRole 'sysadmin'. "
At line:1 char:237
+ [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null; $svr = New-Object ('Microsof
t.SqlServer.Management.SMO.Server') "SQL2012"; $svrole = $svr.Roles | where {$_.Name -eq 'sysadmin'}; $svrole.AddMember
 <<<< ("domainname\username");
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Please could someone possibly help?


Admin QuikView Solution for CRM 2013

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.

Viewing all 21975 articles
Browse latest View live


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