Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

PS Script - Creating Multiple Printer Ports (Newbie Errors)

$
0
0
Mass Printer Port Creation

Note: I'm a complete newbie when it comes to Powershell.  I haven't even touched it prior to this week.

I need to create a bunch of printer ports (about 400).  I found a script that will let me create one at a time and it works flawlessly (http://gallery.technet.microsoft.com/fc636246-c4a4-4aa1-b25d-ce2449b28a05).  I have been trying to modify it so that I can import a list of IP addresses from a CSV file and step through the creation of each printer port.  This has proven to be easier said then done.

My CSV File looks like this:  192.168.0.1,192.168.0.2, 192.168.0.3, etc etc...

My 'modified' script looks like this:
#Import the CSV list
$IPList=IMPORT-CSV C:\Users\administrator.AD\Downloads\portips.txt
#For testing Lists each item in the above file
#$IPList | FOREACH-OBJECT {$_}

FOREACH ($ip in $IPList) {
print $ip
#From Original Script - $ip = "192.168.0.1"
$port = [wmiclass]"Win32_TcpIpPrinterPort"
$port.psbase.scope.options.EnablePrivileges = $true
$newPort = $port.CreateInstance()
$newport.name = "$ip"
$newport.Protocol = 1
$newport.HostAddress = $ip
$newport.PortNumber = "9100"
$newport.SnmpEnabled = $false
$newport.Put()
}


When I run the original script it creates the one port.  When I run my modified, it fails with the following error:
No file to print
Exception calling "Put" with "0" argument(s): "Invali
At C:\Users\administrator.AD\Downloads\test.ps1:30 ch
+ $newport.Put <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], M
    + FullyQualifiedErrorId : DotNetMethodException
    
I'm guessing I'm making a newbie mistake, but I'll be darned if I can find a solution.  Anyone able to help me out here?  Thanks a bunch!
Jon



split on comma, but skip comma's for text encapsulated in quotations..

$
0
0

So I am using a simple split to split a string of text open..

$split = $output.split(",")

My problem is that sometimes comma's are part of the actual data, in those cases it will be surrounded by quotes.. so here would be a sample value I am splitting..

Warren, Harry,"Smith,Thomas",Johnson,Hardly

When I reference $output[2] I want it to equal "Smith, Thomas", not ""Smith"

Distribute a script to the Servers in AD

$
0
0

Hello,

I am a newbie in Powershell scritpting.

We have about 500 Servers with Windows Server 2003, 2008, and 2008 R2 in AD, and need to add to all of the servers a regsitry value to disble SSL2.0. I created a registry file to apply those servers, but I just wonder if there is a way that I can use a Powershell command to distribute this registry file (or a reg script) into the computers in AD.

Would you help me to figure this out?

Thanks in Advance.

New-MCITP-EA 

How do you execute a exe file in PowerShell that is saved to a thumb drive?

$
0
0

I need to run an .exe file saved on my thumb drive in this location E:\copypst\copypst.exe

I have tried to use a few different methods cant seem to get it to work just right.

error of new-pssession -authenticate CredSSP

$
0
0

I ran the following lines on both the client and server.

Enable-WSManCredSSP -Role client -DelegateComputer *
Enable-WSManCredSSP -Role server

Then the "new-pssession -authenticate CredSSP ..." command always returned:

"New-PSSession : [serverB] Connecting to remote server serverB failed with the following error message : There are currently no logon servers available to service the logon request."

Later I ran this command on the server side:

winrm quickconfig -transport:https -force

Then the "new-pssession -authenticate CredSSP ..." command always returned:

[serverB] Connecting to remote server serverB failed with the following error message : The WinRM client received an HTTP server error status (500), but the remote service did not include any other information about the cause of the failure.

I tried all kind of settings on both of the client and server but no any success. The PowerShell is V3. The client machine is a Windows 7 and the server machines I tried are Windows 2008 R2 and Windows 8 RP. All machines are in the same domain.

What else I can do? Thanks for any advice.


Solved - How to take ownership and change permissions for blocked files and folders in Powershell

$
0
0

Hello,
I was trying to take ownership & fix permissions on Home Folder/My Documents structures, I ran into the common problem in PowerShell where Set-Acl & Get-Acl return access denied errors. The error occurs because the Administrators have been removed from file permissions and do not have ownership of the files,folders/directories. (Assuming all other permissions like SeTakeOwnershipPrivilege have been enabled.

I was not able to find any information about someone successfully using native PS to resolve the issue.  As I was able to solve the issues surrounding Get-Acl & Set-Acl, I wanted to share the result for those still looking for an answer.
----
Question: How do you use only Powershell take ownership and reset permissions for files or folders you do not have permissions or ownership of?
----

Problem: 
Using the default function calls to the object fail for a folder that the administrative account does not have permissions or file ownership. You get the following error for Get-Acl:

PS C:\> Get-Acl -path F:\testpath\locked
Get-Acl : Attempted to perform an unauthorized operation.
+ get-acl <<<<  -path F:\testpath\locked
+ CategoryInfo          : NotSpecified: (:) [Get-Acl], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetAclCommand

If you create a new ACL and attempt to apply it using Set-Acl, you get:

PS C:\> Set-Acl -path F:\testpath\locked -AclObject $DirAcl
Set-Acl : Attempted to perform an unauthorized operation.
At line:1 char:8
+ Set-Acl <<<<  -path "F:\testpath\locked" -AclObject $DirAcl
+ CategoryInfo          : PermissionDenied: (F:\testpath\locked:String) [Set-Acl], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand

Use of other functions like .GetAccessControl will result in a similar error: "Attempted to perform an unauthorized operation."

How do you replace owner on all subcontainers and objects in Powershell with resorting to external applications like takeown, icacls, Windows Explorer GUI, etc.?

Tony

Monitoring Long Running Scheduled Tasks

$
0
0

Hi Everyone!

I found a fantastic ps script that will monitor a long running scheduled task...the link is here: Original Script

After a bit of tweaking, I got this running perfectly...but can only set it up for watching one scheduled task. The script looks at the $server and pulls in the scheduled tasks information into a CSV and puts that CSV into the $scriptpath. It looks for the $scheduledtask value and if it exceeds the $maxminutes it sends an email. I'd like to be able to have the script look at several scheduled tasks but do not know enough about powershell to "loop" through a list of tasks and send an email out for any of those tasks that meets the criteria for sending an email alert.

So basically I need some help tweaking this script to monitor a few scheduled tasks instead of just one.

Thank you so much for looking at this with me. Here's the working script for monitoring one task:

$server = "Server_Name"
$scheduledtask="Test Task"
$maxminutes="5"
$scriptpath = "C:\Path_To\Script"

# Send email function

function sendEmail {

$from = New-Object System.Net.Mail.MailAddress "abc@def.com";

$to = New-Object System.Net.Mail.MailAddress "abc@def.com";

$mail = New-Object System.Net.Mail.MailMessage $from, $to;

$mail.Subject = "Scheduled Task ( $scheduledtask ) on $server has been running for longer than $maxminutes minutes.";

$mail.Body = "Scheduled Task ( $scheduledtask ) on $server has been running for longer than $maxminutes minutes. Total Runtime for ( $scheduledtask ): $datediff .";

# Connect to mail relay

$smtpserver = "smtp.server.com"

$smtp = New-Object System.Net.Mail.SmtpClient ($smtpserver);

# Send Email

$smtp.Send($mail);

}

schtasks /query /s $server /FO CSV /v > "$scriptpath\ScheduleTaskMon.csv";

$longrunning = Import-Csv "$scriptpath\ScheduleTaskMon.csv" |

Where-Object {[DateTime]$_."Last Run Time" -and $_."Status" -eq "Running" -and $_."TaskName" -eq "$scheduledtask"};

$datediff=([DateTime]::Now)-([DateTime]$longrunning."Last Run Time");

if ($datediff -le 0)

{exit}

if (($datediff.TotalMinutes) -gt $maxminutes)

{sendemail};


Execute user input in ScriptBlock

$
0
0

So I am trying to get [1] this code to work. What I would like is to have is a script that, when run, asks for a command. I would enter the command I want run on the computers I specify, and the script would execute that command on computers in a remote session.

Right now, I either get an error (varies) or no error (but the code doesn't run). Here are the iterations of the specific line I have tried (with "$cmd" being the command to execute):

Invoke-Command -Session $session -ScriptBlock {$cmd}

Invoke-Command -Session $session -ScriptBlock {invoke-expression $cmd}   

Invoke-Command -Session $session -ScriptBlock {$args[0]} -ArgumentList $cmd

I have also tried creating a ScriptBlock before hand using different commands, but no combination has worked. So far for all my searching I have yet to find someone discuss passing user input into "Invoke-Command." Everyone seems to only pass pre-defined commands, which I have no problems running.

Here is the code I am using:

#Get Credentials
$name = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential $name

#Get Computer(s)
$comp = read-host "Enter the computer name you would like to run commands on"

#Open Session with specified computer(s)
$session = New-PSSession -ComputerName $comp -Credential $cred

#Execute remote command
$cmd = read-host "Enter the command string to run"
Invoke-Command -Session $session -ScriptBlock {$cmd}

#Close Session
Remove-PSSession $session
In this instance I am trying to run the command "slmgr.vbs /ato" on the remote machine. I know that the command itself works when initiated manually. Do I need to escape the "/"? Also I have tried to use parameters and creating the ScriptBlock separately, but none of these things have worked. Thanks in advance.

PS Remoting - Failed to connect to an IPC port: Access is Denied

$
0
0
I am trying to configure some deployment steps in our build process.  This involves using powershell to remotely execute MSTEST.EXE.  The remoting works fine for things like {Get-Process} or writing a file to the remote local drive.  However, MSTEST fails with the following error:

Failed to connect to an IPC port: Access is Denied

The account that powershell runs under is a domain account, and is a local admin on both the local and remote boxes.

Script looks like:
==================
invoke-command -computername BUILD01 -scriptblock {
d:
cd "D:\BuildDrop\Testing_20091210.4"
$exe = "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\mstest.exe"
$vsmdi = "D:\BuildDrop\Testing_20091210.4\Release\WebTests\MyProject.Tests.vsmdi"
& $exe /testmetadata:$vsmdi /testlist:AllWebTests

}
===================

I've tried using the -Credential option too, but that made no difference.  I'm not sure what security to tweak where to fix this error.

Suggestions?

Use Powershell to check whether and AD user exists

$
0
0

We're trying to clean up roaming profile folders, and as part of the task I need to check whether the user actually exists in AD.  I have tried 3 different methods and so far none of them work.

Either the empty result of the search doesn't equal $null (e.g. If ($objUser -eq $null) resolves to false) or Powershell crashes (like when I try to run that If statement).  So is there an AD User equivalent to Test-Path?

RF

Direct un-buffered writes in Powershell

$
0
0

Currently I am trying to run a test that will power-down the machine abruptly when a file is being written. When power-down occurs the last part of data is not present as it is never flushed to disk before power down.

Perl (in Linux) allows direct un-buffered writes when a file is opened in the following manner.

sysopen(F, $file, O_WRONLY|O_DIRECT) or die "Couldn't direct open file $file\n";

This allows data to be written till the last character in-case machine crashes due to some reason. Likewise, for windows, C++ allows direct writes when a file is opened for writes using "FILE_FLAG_NO_BUFFERING" flag.

How can I allow direct/un-buffered writes to disk using powershell ?


-Pranav

Powershell Backup script, but leaves 12 files

$
0
0
I'm trying to get a backup script to delete ALL files older than 24 hours in a directory, but leave at least 12 behind.

This for the case where backups stopped producing and we don’t want the last 12 to get deleted until there are newer.

string and line question

$
0
0

Hi

I feel confuse, soemtime, when I get attribute from AD, if i just echo $user.properties.name , it can display correct,

but if i redirect to txt file,  it will become echo $tmp=  $user.properties.name+","  >> file.txt

In the txt file , it will become,

UserNamw

,

UserName2

,

But if i do echo $tmp=  "," + $user.properties.name+","  >> file.txt

It will display correctly, any ideas?

DiskWriteBytesPersec in Win32_PerfRawData_PerfDisk_LogicalDisk is very huge

$
0
0
Using the following script, I found the DiskWriteBytesPersec is so high (the last column), and actually it is running on my laptop, so the result should be wrong, but what's the correct way to get Disk Write Bytes Per sec ?
Clear-Host
$numLoop=10
$sleep=5
$diskHash=@{}
$counters=1,2,3,4
$disks =Get-WmiObject -class Win32_PerfRawData_PerfDisk_LogicalDisk 
for ($i=1;$i -le $numLoop;$i++){
"{0:d} {0:hh}:{0:mm}:{0:ss}" -f (Get-date)
foreach ($disk in $Disks){
    $diskHash.($disk.name)=1
  $counters[0]=$disk.DiskReadsPersec
  $counters[1]=$disk.DiskReadBytesPersec
  $counters[2]=$disk.DiskWritesPersec
  $counters[3]=$disk.DiskWriteBytesPersec
  #"{0:10} {1:10} {2:10} {3:10} {4:10}" -f $disk.name ,$disk.DiskReadsPersec,$disk.DiskReadBytesPersec,$disk.DiskWritesPersec, $disk.DiskWriteBytesPersec
  "{0,20} {1,10} {2,10} {3,10} {4,10}" -f $disk.name, $disk.DiskReadsPersec,$disk.DiskReadBytesPersec,$disk.DiskWritesPersec, $disk.DiskWriteBytesPersec
}
start-sleep $sleep
}

8/26/2010 12:50:50
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:50:55
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:00
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:05
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:10
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:15
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:20
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:25
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:30
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848
8/26/2010 12:51:35
     HarddiskVolume1          2      20480         24     116736
                  D:        884   18373632       2496   10381312
                  C:     207049 4095621632     137922 2935244800
              _Total     207935 4114015744     140442 2945742848

send mail on script failure

$
0
0

Hi Friends,

I have a simple script which makes nw connection, copies files from source to destination & closes the connection.

net use \\destinationpath\IPC$ "passwod" /user:domain\username
robocopy "sourcepath" "\\destinationpath" /MIR /IS
net use \\destinationpath\IPC$ /delete

Idea is to get an email if the above script fails in execution, any advise please...


Rgds, Minesh


winrm quickconfigu and connectionURI

$
0
0

Hi,

I want to configure Powershell Remoting using HTTS. As a certificate i use a self-signed certificate. But I only get the errormessage 500 without any furtherr entries in eventlog.

Is it possible to configure Powerrshell remoting using SSL with a selfsigned certificate?

And how can I configure this?

Kind regards

  Thomas



Scheduled Jobs, Receive-Job and results in Powershell 3

$
0
0

A job is scheduled to run at logon of the regular user, but using an account of the local administrator.
The script is executed from the file and contains/produces errors. For example:
*) Join-Path uses $home, but $home is null (local administrator is not logged on);
*) NET USE doesn't succeed and gives an error message.

Question: why are all the errors, that occur during the execution of the script, added together at the end of the results, regardless of when and where the errors actually happened? Is there a workaround/setting for this behaviour?

For example, the following script:

Echo "Before Join"
$a = Join-Path -Path $home -ChildPath "somestring"
Echo "After Join"
Echo "a is:" $a 
Echo "The end."


produces the following results, when examined with Receive-Job:

Before Join
After Join
a is:
The end.
Receive-Job : Cannot bind argument to parameter 'Path' because it is an empty string.
At line:1 char:1
[...]

Question: what is the recommended/good way of logging the activity of the Scheduled Jobs in actual execution order, including errors?

Regards!

Measure scheduled task execution time on w2k3

$
0
0

Hi

Do you have any suggustions to measure the execution time of each shceduled task?

Thanks a lot.

Best regards

XML parsing

$
0
0

Hopefully I an explain this all correctly.

I am trying to read an XML file that is being generated from our servers hardware BIOS manufacturer (HP).  The xml output's member properties varies by object. 

If I read in my xml object
[xml]$file1 = get-content 'c:\temp\h1bios.xml'

I can walk through the objects and many have a different set of attributes
$file1.conrep.section[4] | get-member

If I just list below the properties are different
$file1.conrep.section| get-member

What I want to do is list each object and its properties value as I work towards running a compare-object between two different servers BIOS.

Question 1) is how can I list each individual objects value from the changing set of properties?
Question 2) Can I list what object count number I am on by the ParametirizedProperty of the object?

[xml]$file1 = get-content 'c:\temp\h1bios.xml'
$file1.conrep.section |    foreach-object {  }

TIA

Paul

FTP .net question

$
0
0

Hi,

Have written some code today to get the contents of an FTP folder, so far its looking good except the string that is returned from the ListDirectory command doesn't appear to be something I can send into a foreach statement.  Here is my code.

#$files = "_MigrationReport_Files.zip" # needs to pull from $outputbuffer
$ftpFolder = 'ftp://ftp.abc.org'
$ftpUsername =  "sdfsdfs"
$ftppassword = "sdfsdfs"
$outputfolder = "c:\FTPDownloads"

# Get a list of folders in the path given
$ftp = [system.net.ftpwebrequest] [system.net.webrequest]::create($ftpFolder)
$ftp.Credentials = New-Object System.Net.NetworkCredential($ftpusername, $ftppassword)
$ftp.method = [system.net.WebRequestMethods+ftp]::listdirectory
$response = $ftp.getresponse()
$stream = $response.getresponsestream()

  $buffer = new-object System.Byte[] 1024
  $encoding = new-object System.Text.AsciiEncoding

  $outputBuffer = ""
  $foundMore = $false

  ## Read all the data available from the stream, writing it to the
  ## output buffer when done.
  do
  {
    ## Allow data to buffer for a bit
    start-sleep -m 1000

    ## Read what data is available
    $foundmore = $false
    $stream.ReadTimeout = 1000

    do
    {
      try
      {
        $read = $stream.Read($buffer, 0, 1024)

        if($read -gt 0)
        {
          $foundmore = $true

 $outputBuffer += ($encoding.GetString($buffer, 0, $read))
        }
      } catch { $foundMore = $false; $read = 0 }
    } while($read -gt 0)
  } while($foundmore)

  $outputBuffer

foreach ($file in $outputBuffer) {

echo test + $file
}

I guess its something to do with this line and the way it in encoded:

$outputBuffer += ($encoding.GetString($buffer, 0, $read))

But I don't know much .net....


Alter De Ruine

Viewing all 2562 articles
Browse latest View live


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