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

Use Powershell to check for pending certificate requests

$
0
0
Is there a relatively easy way to use Powershell to check for Pending Certificate Requests on an MS Certification Authority?

zarberg@gmail.com


Powershell get-childitem UnauthorizedAccessException

$
0
0

I am running the Get-ChildItem -recurse command against files on a remote file server and am getting an error that I can't explain (see below).  The account running the command has full control of all of the directories listed in the tree and can open/edit any file via Windows explorer.  The account in question (domain\_myservice_account) is a domain account and it can successfully run the command on my laptop or a different server.  This command started failing about 1.5 months ago but had worked successfully from that server for 2 years.

The command fails whether I try using the UNC name or a mapped drive to the directory.  It seems to successfully scan dir7 through dir12 with no issues the error comes once it reaches directory dir13 and it's children.

Is there some configuration that I need to change on the servers where this command is failing in order to get this working again?

Please help as I have been trying to figure this out for a while now with no progress.

Thanks,
Mike

Get-ChildItem : Access to the path '\\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\dir9\dir10\dir11\dir12\dir13' is denied.
At line:1 char:14
+ Get-ChildItem <<<<  \\Server\dir1\dir2\dir3\dir4\dir5\dir6\dir7\dir8\ -recurse -filter my_file_*.gz
    + CategoryInfo          : PermissionDenied: (\\Server...\dir12\dir13:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Take ownership of a registry key, and change permissions

$
0
0

Hello,

I am writing a powershell script to configure a W2008-R2 Server. In one of the steps, I need to take ownership of an existing registry key, and then give full control permissions to the administrators.

I have done this:

$acl= Get-Acl $key$me=[System.Security.Principal.NTAccount]"$env:userdomain\$env:username"$acl.SetOwner($me)$person=[System.Security.Principal.NTAccount]"Administrators"$access=[System.Security.AccessControl.RegistryRights]"FullControl"$inheritance=[System.Security.AccessControl.InheritanceFlags]"None"$propagation=[System.Security.AccessControl.PropagationFlags]"None"$type=[System.Security.AccessControl.AccessControlType]"Allow"$rule= New-Object System.Security.AccessControl.RegistryAccessRule($person,$access,$inheritance,$propagation,$type)$acl.AddAccessRule($rule)

 Set-Acl $key$acl

But it fails in "set-acl" command, with the message "Set-Acl : Requested registry access is not allowed."

 

Any ideas of how to do this? or if it is even possible?

 

Thank you!

hex to ascci converter

$
0
0

hello,

I have a little problem, I'm got a powershell script that should give me a windows to enter a hex and covert this to text or binary. I imported all the modules but when I start the script I get the following error:

New-Window : Exception calling ".ctor" with "5" argument(s): "AuthorizationManager check failed."
At C:\Users\joosterwaal\Documents\WindowsPowerShell\Modules\ShowUI.1.4\Power.ps1:12 char:11
+ New-Window <<<<  @Windowparam {
    + CategoryInfo          : NotSpecified: (:) [New-Window], CmdletInvocationException
    + FullyQualifiedErrorId : EmbeddedProcessRecordError,AutoGenerateCmdlets766548713.NewWindowCommand

what can I doe to fix this?

Start-Job without network connection

$
0
0

Hello!

I'm writing a network monitoring script. It sends pings every X seconds; if pings are failed, Windows Form with appropriate message is shown to user.

The form should be shown in separate thread in order not to stop pings while form is shown to user. So I use the next code:

function ShowForm
{
    [void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")

    $objForm = New-Object System.Windows.Forms.Form 
## Some code with discription and content of the form
## ...
##
    $objForm.Add_Shown( { $objForm.Activate() } )
    $objForm.ShowDialog()
}

start-job $Function:ShowForm

It works great until network connection of computer is down. In that case script hangs on Start-Job cmdlet and actually starts job only after network connection is recovered.

The script also hangs with a simple code such as:

Start-Job -ScriptBlock {Write-Host "Hello"}

How this message can be shown without "pausing" script in the case when network connection is down?




Help with file move

$
0
0

A colleague changed the location of some jpg files, and made a mistake. When he scripted the location change, he forgot a slash - so he changed the file name to folderfilename.jpg. He then repeated his mistake several times, winding up with folderfolderfolderfolderfilename.jpg.

Anybody have a tip for cutting the folderfolderfolder off the beginning of the names?

 

hash table in function - only works first time it's called

$
0
0

I'm using Forms and wanted a way to "refresh" the data; specifically the Text property of a Checkbox.  To accomplish this task I made the form generation a function, DrawForm.  When I want to refresh the data, $Form.Close(), $Form.Dispose(), DrawForm.  As part of the DrawForm function, I'm using a hash table to collect data dynamically for use in the form.  The hash table data works fine the first time the form function is called, but when I attempt to "refresh" the data is not updated. Every other part of the function works correctly (though it's all static information).  

I used write-host to echo variable and steps to console, and interestingly it does not process any of the of the steps in the hash table after the first time.

Here's some of my hash table:

$VMS = Get-VM

write-host " start checkboxes"
$CB = @{}
$j=0
For ($i=0; $i -lt $VMS.count; $i++) {
$i
$j
$j=$j+20
$CB[$i] = New-Object System.Windows.Forms.checkbox
$TEST = "$($VMS[$i].Name) - $($VMS[$i].PowerState)"
write-host "end checkboxes"

The "start" and "end" statements always write to console, but the $i $j $CB[$i] and $TEST variables only write to console the first time the function is called, so it appears this part of the script is not processed at all on subsequent calls.  The original data will always appear in the form when it is refreshed/redrawn; it does not lose the information, but it just won't update it.

Please advise...

importing Contacts from csv into AD

$
0
0

Hi,

i have a csv file with one name and 4 phone number columns. I want to import those data into AD as a Contact. I get an error when i import a contact that has an empty phone number (does not matter which column is empty).

So i tried to make an if statement to check if the variable has data in it, but i cant get it to work.

CSV content (Outlook export):

Name;Telefon geschäftlich;Telefon geschäftlich 2;Weiteres Telefon;Mobiltelefon
Test 123;+00 1234677;;;+00 1234677
Test 123 456;+00 1234677;;;+00 1234677

Powershell Script:

$contacts = import-csv .\contacts.csv -delimiter ";" -Encoding UTF8
For ($i=1; $i -le $contacts.count; $i++) {

    New-ADObject -name $contacts[$i-1].Name -Path "OU=Contacts,OU=ACPOOE,DC=acpooe,DC=demo" -ProtectedFromAccidentalDeletion $false -Type Contact -OtherAttributes @{
        if ($contacts[$i-1]."Mobiltelefon") {mobile=$contacts[$i-1]."Mobiltelefon";}
        if ($contacts[$i-1]."Telefon geschäftlich") {telephoneNumber=$contacts[$i-1]."Telefon geschäftlich";}
        if ($contacts[$i-1]."Telefon geschäftlich 2") {homePhone=$contacts[$i-1]."Telefon geschäftlich 2";}
        if ($contacts[$i-1]."Weiteres Telefon") {ipPhone=$contacts[$i-1]."Weiteres Telefon"}
    }
}

I get the following Error:

At C:\Users\Administrator\Desktop\test\Untitled1.ps1:6 char:11+         if ($contacts[$i-1]."Mobiltelefon") {mobile=$contacts[$i-1]."Mobiltelefo ...+           ~
Missing '=' operator after key in hash literal.
At C:\Users\Administrator\Desktop\test\Untitled1.ps1:2 char:42+ For ($i=1; $i -le $contacts.count; $i++) {+                                          ~
Missing closing '}' in statement block.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException+ FullyQualifiedErrorId : MissingEqualsInHashLiteral




Renaming Directory Issue

$
0
0

Hi Guys,

I have a specific requirements to re-profile some Citrix users, thing is, their profiles all have funny names and i'm struggling to concept how I can capture them all.

The profiles appear as: Username, Username.Domain, Username.UPM.var, Username.Domain.000, Username.Domain.001, Username.UPM.var.backup, Username.UPM.var.000, Username.UPM.var.001, Username.UPM.var.002... You get the picture...

The script I have so far is:

$Username = Read-Host -Prompt "Enter username"

$Servers = "Server1","Serv2",etc

Profiles = Foreach ($server in $servers) {"\\" + $server + "docs and settings" + $Username + "*"}

Obviously this wildcard is messing up when I come to Rename-Item, am I missing a really obvious method to do this?

The requirements are:

Locate the user directories that exist.

Rename them all to "OLD1_Username"

Have the ability to do this several times "OLD2","OLD3", etc.

Have the ability to track back and undo the changes made if need be.

Thanks In advance.

Adam

Using Import-StartLayout to a local system

$
0
0

Here is states, that this cmdlet can be used only to an image: http://technet.microsoft.com/en-us/library/dn283403.aspx

But his guy claims that this cmdlet can be used locally: http://stealthpuppy.com/customizing-the-windows-8-1-start-screen-dont-follow-microsofts-guidance/

I need to set a valid powershell script (ps1) or command line, which could work during task sequence.

1. If I run the command from location with the startscreen bin file as:

PS L:\Tools\W8Customize> Import-StartLayout -LayoutPath .\CustomStartScreenLayou
t.bin -MountPath %SystemDrive%\

I´ll get: Cannot find path 'L:\Tools\W8Customize\%SystemDrive%\

2. If I run it with C:\Windows instead of SystemDrive, I get:

PS L:\Tools\W8Customize> Import-StartLayout -LayoutPath CustomStartScreenLayout.
bin -MountPath "C:\Windows\"

I´ll get: The path C:\Windows\ did not resolve to a file.

I also tried to copy the bin file manually to C:\Windows\ and execute it locally, but that doesn´t work either.

Active Directory object propertie "ModifiedProperties"

$
0
0

Hello,

i use the Set-ADUser cmdlet to modify some properties for an active directory user and i'm treying to find a easy way to verify that the property was endeed  modified by the commad so i added the "-PassThu" switch.

the switch return an object of type "Microsoft.ActiveDirectory.Management.ADAccount".
the ISE intelisens autocomplete a property called "ModifiedProperties" - but it returns nothig when i read it.

i'm i using this in a wrong way ? or this property does'n do what i'm expecting to (return the modified properties) ?

PS C:\Admin\Scripts\DMA> $resultObject = Set-ADUser user1 -Manager user2 -PassThru

PS C:\Admin\Scripts\DMA> 
PS C:\Admin\Scripts\DMA> $resultObject.ModifiedProperties

PS C:\Admin\Scripts\DMA> $resultObject.GetType()

IsPublic IsSerial Name                                     BaseType                                                                  
-------- -------- ----                                     --------                                                                  
True     False    ADUser                                   Microsoft.ActiveDirectory.Management.ADAccount 

Thanks,
Marius

Need to Impend the Text file in to XML child NOdes

$
0
0

Hi All,

I am new toPowershell.I m trying to create a script.Where i have specified few email Id's in a Text file like :

abc@gmail.com

I want this Email ID's to be appended in to an XML File XML file has below data :

<?xml version="1.0"?>
<RULE_SET xmlns="x-schema:ruleset schema.xdr">
   <RULE NAME="Hello" >

<AUTHOR INCLUDES="ANY" ALLOWOTHERS="Y">
<EA>abc@yahoo.com</EA>  
<EA>rghi@hotmail.com</EA> 
<EA>hello@gmail.com</EA>
<EA>bye@gmail.com</EA>

"Here is where i want the Text file data to be placed with <EA> tags"

  </AUTHOR>
 </RULE>
 </RULE_SET>

Please do help me in getting the txt file data in to the XML file.

Get error (There is an error in XML document (3, 4)) when consuming web service HelpDesk_QueryList_Service with New-WebServiceProxy

$
0
0

Dear all,

I'm using the powershell cmdlt New-WebServiceProxy to query ITSM incidents. I'm able to get the WSDL definition ..

$uri='http://pitsm/arsys/WSDL/public/pitsmapp/HPD_IncidentInterface_WS'

$myitsm=New-WebServiceProxy -Uri $uri -Namespace ITSM -Verbose true

$auth= New-Object ITSM.AuthenticationInfo

$cred=get-credential

$auth.username=$cred.username

$auth.password= [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($cred.password))

$auth.authentication="Domain Authentication"

$myitsm.AuthenticationInfoValue=$auth

$myitsm.RequestEncoding =  [System.Text.Encoding]::UTF8

$tid="INC000002237910"

$criteria="'Incident Number' = ""$tid"""

When i'm consuming now the web service i get back an error messages:

$answer=$myitsm.HelpDesk_QueryList_Service($criteria,0,100)

Exception calling "HelpDesk_QueryList_Service" with "3" argument(s): "There is an error in XML document (3, 4)."

At line:1 char:1

+ $answer=$myitsm.HelpDesk_QueryList_Service($criteria,0,100)

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

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : InvalidOperationException

Has anybody an idea what could be wrong?

Any idea how to debug the commandlet New-WebServiceProxy?

Best Regards

Chris

Task Schedular with Powershell - 'run whether users is logged on or not'

$
0
0

Guys,

I have a Powershell script which runs on a server. It checks the services on a list of servers, which are set to 'Auto' and are 'not running'.

The script then creates a list of these services for me (in a report) from all the servers on my environment so i can look into it. The script runs fine when i run from console and when I 'right click and run with powershell'.

However, if i try to schedule it to 'run whether users is logged on or not', it doesn't run properly. If i run it like this, it completes, but it might only show results from one server for example.

Also, it works if i select the option, to 'run only when user is logged on'.

Any suggestions to make this script work regardless if user is logged on?

Thanks

Detect Single Path failure in HBA card using powershell for windows server 2003 and 2008

$
0
0

Hi All,

I would like to write a basic script for showing the SAN path health status for my physical servers.

I just able to find WMI classes MSFC_FCAdapterHBAAttributtes and MSFC_FibrePortHBAAttributes, however this two classes not able to show me the path failure and only showing the HBA status as 0 even though single path is failed.

Please advise further as i need to run it for 700+ servers to identified the failure.

Chun

===========

#Get server name
$strComputer = get-content -path C:\Users\xootzecadm\Desktop\test\server.txt

#Get Details
function GetDetails{

ForEach ($computer in $strComputer){
        
$Driveinfo = gwmi win32_volume -computername $computer      
        $HBAinfo = gwmi -namespace root\wmi -class msfc_fcadapterHBAattributes -computer $computer
        
        
        Foreach($Drive in $Driveinfo){
            $Size = $Drive.freespace/1024/1024
            $Sheet1.Cells.Item($intDrive, 1) = $computer
            $Sheet1.Cells.Item($intDrive, 2) = $Drive.driveletter
            $Sheet1.Cells.Item($intDrive, 3) = $Size
            $intDrive = $intDrive + 1
        }
        
        Foreach($HBA in $HBAinfo){
            if($HBA.HBAstatus -eq 0){ $status = "OK"}
            else { $status = "Failed"}
            $Sheet2.Cells.Item($intHBA, 1) = $computer
            $Sheet2.Cells.Item($intHBA, 2) = (($HBA.NodeWWN) | ForEach-Object {"{0:x}" -f $_}) -join ":"
            $Sheet2.Cells.Item($intHBA, 3) = $status
            $intHBA = $intHBA + 1
        }
        
        $intRow = $intRow + 1
}
}

$CurrentPath = $pwd.path
$file = $CurrentPath + "\Drive_HBA.xls"

#Create Excel Application
$Excel = New-Object -com Excel.application
$Excel.visible = $false
$Excel.displayalerts = $false

#Create Excel workbook and worksheet
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Add()
$Sheet = $Excel.Worksheets.Add()

#Assign each worksheet to variable and Name the worksheet
$Sheet1 = $Excel.Worksheets.Item(1)
$Sheet2 = $Excel.Worksheets.Item(2)
$Sheet1.Name = "Drive"
$Sheet2.Name = "SAN"

#create heading
$Sheet1.Cells.Item(1,1) = "Server Name"
$Sheet1.Cells.Item(1,2) = "Drive Letter"
$Sheet1.Cells.Item(1,3) = "Size(MB)"

$Sheet2.Cells.Item(1,1) = "Server Name"
$Sheet2.Cells.Item(1,2) = "WWN"
$Sheet2.Cells.Item(1,3) = "Status"

$intRow = 2
$intDrive = 2
$intHBA = 2

getdetails

$Excel.SaveAs($file)
$Excel.Close()

===========


Import Users via PowerShell to AD using CSV

$
0
0

Hi Guys,

I am trying to import users from a CSV into active directory. I have the following script but it doesn't do anything.

Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {New-ADUser -Path 'OU=Intake2013,OU=Students,OU=Users,OU=ASH,OU=Establishments,DC=Ashdown,DC=INTERNAL' -Description $_.Description -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) -SamAccountName $_.sAMAccountName -GivenName $_.FirstName -Surname $_.LastName -DisplayName $_.DisplayName -Name $_.Name -OtherAttributes @{pager=$_.Pager} -UserPrincipalName $_.UPN -ProfilePath $_.ProfilePath -HomeDrive N: -HomeDirectory $_.HomeDir}
Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {Add-ADGroupMember -identity 'CN=ASH Student Users,OU=Student Users,OU=User Groups,OU=Groups,OU=ASH,OU=Establishments,DC=Ashdown,DC=internal' $_.sAMAccountName}
Import-CSV "C:\PowerShell\User\import\Intake2013.csv" | ForEach-Object {Add-ADGroupMember -identity 'CN=ASH File Server 4,OU=General,OU=Groups,OU=ASH,OU=Establishments,DC=Ashdown,DC=INTERNAL' $_.sAMAccountName}

Does anyon ehave any idea what is going on?

Kind Regards

Tom Park


TPark IT Technician

Change email address on AD Contact (No Exchange)

$
0
0

Hi there - I need to create an Active Directory Contact via Powershell with an associated email address. I can figure out how to create the contact with the New-ADObject cmdlet. But I've been hitting my head against the proverbial wall trying to figure out how to set or change the email address.

Everything that I've come across assumes that you're using Exchange so there are Exchange specific cmdlets. We don't use Exchange in our company. 

Is there some way to set the Email Address field within the contact properties using standard applets?

If not, can I download and load the Exchange cmdlets even if I'm not running Exchange? Any recommendations on which version?

THANKS!


How to send email to Exchange 2010 Distribution group?

$
0
0
How to send email to Exchange 2010 Distribution group?

Hello every one!
I have Exchange Distribution groups with option "Require authentication from all senders"
I have a problem, when I try to send email via PowerShell (Send-MailMessage) I have a delivery error (Message not delivered because delivery to this address is restricted.)
I Try to use Send-MailMessage with credentials, but the error is still.

May somebody help me?

Thanks in advance!

DNs forwarders removal powershell

$
0
0

Hey guys below is the script that i am using to clean the forwarder luckily we have 2012 domain controllers. the scripts works partly We have around 30DC  which has different  Forwarder i exported them and create a csv file  below is the the Csv file and script the script just removes one ip addres instead of all the four 

Server,Ipaddress
SOUL1ADS002,"10.9.64.234, 10.9.64.235, 10.18.110.40, 10.18.46.41"
SOUL2ADS002,"10.18.1.144, 10.18.1.145, 10.9.160.33, 10.9.160.34"
$Forwarder  =import-csv forwardersstest.csv

$object = @()
Foreach ($entry in $Forwarder){
$object+= New-Object psobject -Property @{
Server = $entry.server
ipaddress = $entry.Ipaddress
}

}

foreach ($obj in $object) {

Remove-DnsServerForwarder -ComputerName $obj.Server -IPAddress $obj.ipaddress 

Write-Output "forwarder removed from $obj.Server"

}

Using New-WebServiceProxy for Soap requests.

$
0
0

I'm trying to send a Soap request through Powershell (and failing miserably at the moment).

Is the following approach on the right track?

$proxy = New-WebServiceProxy -uri "H:\vehicle.wsdl"

$namespace = $proxy.GetType().NameSpace

$registration = New-Object ($namespace +".GetVehicleDetailsRequest")

$registration.registrationNumber = "ABCDEF"

$request = $proxy.GetVehicleDetails($registration)

$request

I don't get any error, but the response just contains two properties.  replyContent and serviceOperationsStatus.

The replyContent seems to show the namespace with .replyContent on the end, instead of an XML response which I thought it would return.

Any comments, or links for further reading would be appreciated.

As previously mentioned.  Is this even the right approach?

The body of the soap request is pretty simple.

<soap:Body><get:GetVehicleDetailsRequest><get:registrationNumber>ABCDEF</get:registrationNumber></get:GetVehicleDetailsRequest></Soap:Body>



Viewing all 21975 articles
Browse latest View live


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