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

PS export with columns.

$
0
0

 Having trouble getting the below script to export column header data to a file. If I run it as it exports without column header info. When I change the last line to this it doesn't export correctly. What am I doing wrong?

$strEmails |select-object DayOfweek, Date, Sent,Sent Size,Received,Received Size |Export-Csv -Path C:\temp\PSlogs\”SentRecEmail_$(Get-Date -f 'yyyyMMdd').csv”

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

$From = Get-Date "09/22/2016" 
$To = $From.AddDays(1) 

[Int64] $intSent = $intRec = 0
[Int64] $intSentSize = $intRecSize = 0
[String] $strEmails = $null 




Do 

    # Start building the variable that will hold the information for the day 
    $strEmails = "$($From.DayOfWeek),$($From.ToShortDateString())," 

    $intSent = $intRec = 0 
    (Get-TransportServer | % {$_.name}) | Get-MessageTrackingLog -resultsize unlimited -Start $From -End $To | ForEach {



        # Sent E-mails 
        If ($_.EventId -eq "RECEIVE" -and $_.Source -eq "STOREDRIVER")
{
$intSent++
$intSentSize += $_.TotalBytes
}

        # Received E-mails 
        If ($_.EventId -eq "DELIVER")
{
$intRec++
$intRecSize += $_.TotalBytes
}
    } 

$intSentSize = [Math]::Round($intSentSize/1MB, 0)
$intRecSize = [Math]::Round($intRecSize/1MB, 0)

    # Add the numbers to the $strEmails variable and print the result for the day 
    $strEmails += "$intSent,$intSentSize,$intRec,$intRecSize" 
    $strEmails 

    # Increment the From and To by one day 
    $From = $From.AddDays(1) 
    $To = $From.AddDays(1) 


While ($To -lt (Get-Date))



 $strEmails >> C:\temp\PSlogs\”SentRecEmail_$(Get-Date -f 'yyyyMMdd').csv”

                      

Joel



IIS server throws "wsman fault" exception

$
0
0
I am working mvc application. I have used remote connection using system.management.automation.dll and used run space and pipeline to invoke script files. I have published the application from visual studio and host in IIS Express. its working fine. But in IIS server it throws "wsman-fault" error. 
please find the details:

OS: windows server 2012 R2
IIs version: IIS version 8

please anyone help to execute remote connection command in IIS server.

   
param    (     [Parameter(Mandatory = $true,HelpMessage="Ip address or domain name")]        [String]        $hostName,    	[Parameter(Mandatory = $true,HelpMessage="port number of winrm service")]        [String]        $portNumber,	        [Parameter(Mandatory = $true,HelpMessage="username for remote machine")]        [Int]        $userName,	    	[Parameter(Mandatory = $true,HelpMessage="password for remote machine")]        [String]        $password,    )    winrm quickconfig -force    Enable-PSRemoting -SkipNetworkProfileCheck -Force    Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*"  -force    $securepassword = ConvertTo-SecureString -string $password -AsPlainText -Force    $cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $userName, $securepassword    $remoteconnectionuri="http://$hostName"+":"+$portNumber    Invoke-Command -ConnectionUri $remoteconnectionuri.ToString() -Credential $cred -ScriptBlock{    new-item -path C:\ -name SS64.txt -type "file" -value "some text"    }



and in mvc application 

   
 public string TestIis(string hostName,string portNumber,string userName,string password)            {                var scriptFile = "test";                var addParametersToScriptFile = new Command(scriptFile);                var runspaceConfiguration = RunspaceConfiguration.Create();                var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);                runspace.Open();                var scriptInvoker = new RunspaceInvoke(runspace);                scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned");                var pipeline = runspace.CreatePipeline();                    //Here's how you add a new script with arguments                        addParametersToScriptFile.Parameters.Add(new CommandParameter("hostName", hostName));                addParametersToScriptFile.Parameters.Add(new CommandParameter("portNumber", portNumber));                addParametersToScriptFile.Parameters.Add(new CommandParameter("userName", userName));                addParametersToScriptFile.Parameters.Add(new CommandParameter("password", password));                pipeline.Commands.Add(addParametersToScriptFile);                    // Execute PowerShell script                pipeline.Invoke();                runspace.Close();                        return "success";            }


cannot run powershell command to make one user e-mail password to never expire

$
0
0

To anyone I connected to Exchangeonline Office 365 no problem but when I run the command 

Set-MsolUser -UserPrincipalName bugs@brightidea.com -PasswordNeverExpires $true 

I get this error message.  It use to work before when I ran this command.

SQLCMD Invalid Argument Error

$
0
0

Hi, I ve been trying to get my head around with a script but in vain. Apparently, I have a SQL procedure script file that I am compiling in a db using PowerShell script. The procedure has a dynamic sql text that stores a parameter in db with double quotes.
When reading this file using Get-Content and executing it in DB, I get an invalid argument exception. Below query mimics my scenario.
PowerShell script:

$query = [IO.File]::ReadAllText($_.FullName)
$result = SQLCMD -S $FullDBServer -E -I -Q $query -d $Database 

SQL Query from my file:

SELECT '"hi"'

Result:

SQLCMD : Sqlcmd: 'hi"'+ $result = SQLCMD -S $FullDBServer -E -I -Q $query -d $Database+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo: NotSpecified: (Sqlcmd: 'hi"':String) [], RemoteException+ FullyQualifiedErrorId : NativeCommandError" -d local': Unexpected argument. Enter '-?' for help.
I have tried enclosing the string in double single quotes, tried using here string. None of these work. Any thoughts?



DFS Backlog Check and Alerting script

$
0
0

Plagiarized most of this (credit to Kamal - no last name posted that I could find).  Shared this before but I added some email alerting if the backlog count is over 1000.  Sharing again for others.

Pulls all the DFS replication folders and groups on domain.  Checks all directions.  I set this up on one of the DFS servers to run ever 2 hours.  Takes about 10-15 minutes to run but so far so good.   This does require the firewall to be open between the DFS servers (or from where you run the script).  This would not run on my computer since DFSRDIAG uses dynamic RPC ports.  Best best is to just run it on DFS server.  If you have any issues I would make sure that dfsrdiag works locally.

Also other issue I ran into - the scheduled task - cant use a regular user because it needs WMI etc access on all DFS Servers.  Easiest solution is to make your domain user a member of the local admins group on the servers.  If one of the DFS servers is a DC... well then it would need domain admin rights.  I found a few articles on giving a regular user access to dfsrdiag... and none have worked.  Couldn't get around it.. the user you use for scheduled task needs to have permissions on all DFS servers.

Also not sure why this shows that half the script is comments but it isn't...

# Get Start Time
# For testing - commented out for Prod
# $startDTM = (Get-Date)

#SMTP Settings
$smtp = "mail.company.local"
$to = "IT Helpdesk <helpdesk@company.com>"
$from = "DFS Monitoring Script<donotreply@company.com>"

# Get all replication groups
$replicationgroups = dfsradmin rg list;

# Reduce loop by 3 lines to filter out junk from dfsradmin
$i = 0;
$imax = ($replicationgroups.count -3);

# Loop through each replication group
foreach ($replicationgroup in $replicationgroups) {

    # Exclude first and last two lines as junk, and exclude the domain system volume
    if (($i -ge 1) -and ($i -le $imax) -and ($replicationgroup -notlike "*domain system volume*")) {

        # Format replication group name
        $replicationgroup = $replicationgroup.split(" ");
        $replicationgroup[-1] = "";
        $replicationgroup = ($replicationgroup.trim() -join " ").trim();

        # Get and format replication folder name
        $replicationfolder = & cmd /c ("dfsradmin rf list /rgname:`"{0}`"" -f $replicationgroup);
        $replicationfolder = (($replicationfolder[1].split("\"))[0]).trim();

        # Get servers for the current replication group
        $replicationservers = & cmd /c ("dfsradmin conn list /rgname:`"{0}`"" -f $replicationgroup);

        # Reduce loop by 3 lines to filter out junk from dfsradmin
        $j = 0;
        $jmax = ($replicationservers.count -3);

        # Loop through each replication member server
        foreach ($replicationserver in $replicationservers) {

            # Exclude first and last two lines as junk
            if (($j -ge 1) -and ($j -le $jmax)) {

                # Format server names
				$sendingserver = ($replicationserver.split()| where {$_})[0].trim();
				$receivingserver = ($replicationserver.split()| where {$_})[1].trim();
                # Get backlog count with dfsrdiag
				$backlog = & cmd /c ("dfsrdiag backlog /rgname:`"{0}`" /rfname:`"{1}`" /smem:{2} /rmem:{3}" -f $replicationgroup, $replicationfolder, $sendingserver,  $receivingserver);
                $backlogcount = ($backlog[1]).split(":")[1];

                # Format backlog count
				if ($backlogcount -ne $null) {
    	                $backlogcount = $backlogcount.trim();
       	        }
           	    else {
                    	$backlogcount = 0;
               	}
   	            # Create output string to <replication group> <sending server> <receiving server> <backlog count>;
       	        $outline = $replicationgroup + " From: " + $sendingserver + " To: " + $receivingserver + " Backlog: " + $backlogcount;

				# This is for testing - commented out for Prod
                $outline;

                if ([int]$backlogcount -gt 1000) {
					$subject = "High DFS Backlog Alert for $replicationgroup"
                    $datetime = Get-Date
					$body = "There is a high back log count detected for $outline . This was detected at $datetime CST"
					send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high
				}
			}

 			#}
            $j = $j + 1;
        }

    }

    $i = $i + 1;
}

# Get End Time
# For testing - commented out for Prod
# $endDTM = (Get-Date)

# Echo Time elapsed
# For testing - commented out for Prod
# "Elapsed Time: $(($endDTM-$startDTM).totalseconds) seconds"



PowerShell type not displayed on monitor

$
0
0
I'm in a PowerShell class and a newbie to PowerShell. I am using PowerShell 5.1 on Windows 10 and have an issue with the command line interface (The ISE interface works just fine). I had an assignment that required that I change the background color to yellow and the text color to dark blue. This worked just fine. I then was trying different shortcuts to see if they would work and they didn't seem to be working and then I started getting error messages so I exited and rebooted and went back in and now when I type some things will show on my monitor but most things do not show on my monitor. Very strange and after searching Google for hours I am no closer to a solution other than a system restore which I would rather not due. Is there possibly a solution to whatever the issue may be? The commands work just fine but I can't see what I am typing and it does not matter what color combination I use including the default colors. Thanks in advance for any assistance.

Script Stopped Working After an upgrade of PowerShell from 2.0 to 3.0

$
0
0

The script stopped working after an upgrade from PowerShell v2.0 to v3.0.

I used following command to save a password in a file (securestring.txt)

read-host -assecurestring| convertfrom-securestring | out-file C:\securestring.txt

The script has following command which read password from C:\securestring.txt file

$password= cat C:\Shutdown-Restart\securestring.txt -TotalCount 1 | convertto-securestring

$cred= new-object -typename System.Management.Automation.PSCredential -argumentlist $password

Later in the script I used following to pass the password

$smtp.Credentials = New-ObjectSystem.Net.NetworkCredential($username, $cred)

Here is an error message I am getting:

Cannot find an overload for "PSCredential" and the argument count : "1"

 


Virus Total - Hash Scan

$
0
0
I am trying to create a script that would take hashes that are saved on a text file and retrieve scan reports for each hash. The test file has four hashes. When I try to run it, I encounter the following error: 

Invoke-RestMethod : A positional parameter cannot be found that accepts argument '.\test_hash.txt'.

+     return Invoke-RestMethod -Method $method -Uri $hashUri -Body Get- ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeRestMethodCommand


Below is what I currently have: 


$method = 'POST'
$VTAPIKey = '*****MY API KEY PLACED HERE******'
$hashUri = 'https://www.virustotal.com/vtapi/v2/file/report'

return Invoke-RestMethod -Method $method -Uri $hashUri -Body Get-Content .\test_hash.txt | ForEach-Object {@{Resource = $_ ; APIKey = $VTAPIKey}}

I also tried to run the following code: 

$method = 'POST'
$VTAPIKey = '*****MY API KEY PLACED HERE******'
$hashUri = 'https://www.virustotal.com/vtapi/v2/file/report'

$body = Get-Content .\test_hash.txt | ForEach-Object {@{Resource = $_ ; APIKey = $VTAPIKey}}


return Invoke-RestMethod -Method $method -Uri $hashUri -Body $body


And I receive the following error: 

Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At line:1 char:8
+ return Invoke-RestMethod -Method $method -Uri $hashUri -Body $body
+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], Web
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand


I am aware that the code is really basic and I am trying to build it step by step. Please note that I am a newbie, so any assistance will be appreciated. Thank you. 

Outlook does not send a mail

$
0
0

Hello dear
I wrote a script, in that I can create a mail.

I checked it now and wrote a mail to myself.
Now I realisied, it does not send a mail or the mail never reached me.

Why?

What should I Change?

#Layout Mail
$o = New-Object -com Outlook.Application

$script = {

    $mail = $o.CreateItem(0)
    $mail.Subject = "xxx"
    $mail.Body = "xxxxx"
    $mail.Recipients.Add("** xxx")
    $mail.importance = 2
    $mail.Display()

}

    #form
$form = New-Object Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(900,500)
$Form.StartPosition = "CenterScreen"
$Form.Text = "GUI MH"

#Button:
$Cbuttonb = New-Object System.Windows.Forms.Button
$Cbuttonb.Text = "createMail"
$Cbuttonb.Left = 100 #Grössenangabe
$Cbuttonb.Top = 300 #Grössenangabe
$Cbuttonb.Width = 250 #Grössenangabe
$Cbuttonb.Height = 50 #Grössenangabe
$Cbuttonb.Add_Click( {&($script)} )
#Hier wird die Kontrollform hinzugefügt
$form.Controls.Add($Cbuttonb)
$form.ShowDialog() | Out-Null


mohamedhassan_99@hotmail.com


How do I pass an argument for a parameter of a PoSh script that uses dynamic compilation of C# code from a console. Based on a sample usage code for FileSystemWatcher class

$
0
0

Howdy,

I am trying to use the sample C# code provided in the usage example for the FileSystemWatcher class on MSDN. The script allows you to subscribe to the Changed event to monitor changes in file system.

I wrap this up in PoSH like this:

$watch = @"
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
    Run();

    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}"@
$Assemblies = ("System")

Add-Type -ReferencedAssemblies $Assemblies -TypeDefinition $watch


If I call Main() and pass path value in the command line, I get:

PS C:\Users\Admin> [Watcher]::Main() C:\Users\Admin\AppData\Local\Temp\Watcher
At line:1 char:19+ [Watcher]::Main() C:\Users\Admin\AppData\Local\Temp\Watcher+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'C:\Users\Admin\AppData\Local\Temp\Watcher' in expression or statement.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException+ FullyQualifiedErrorId : UnexpectedToken

If I call Main() with a null argument, I get:

PS C:\Users\Admin> [Watcher]::Main()
Usage: Watcher.exe (directory)

As a brute workaround I output the code into an EXE file, so I changed:

Add-Type -ReferencedAssemblies $Assemblies -TypeDefinition $watch

to

Add-Type -ReferencedAssemblies $Assemblies -TypeDefinition $watch -OutputAssembly 'C:\Test\PowerShell\watcher.exe'
How do I pass a path right from the Powershell console without having to output a ngen'ed file?

Thank you.


Well this is the world we live in And these are the hands we're given...


Check 3 conditions inside

$
0
0

Hi, ask you for a little help

How can i check these 3 conditions inside $server ?

There are 2 differents results for vms: W10-H1 and W10-H2  but only one write-host is written on the screen. :-(

could definitely be errors in my code

$server = 'HOST1' | foreach-object {get-vm -computername $_ } | where {$_.replicationstate -notmatch "Disabled"} | get-VMreplication | select primaryserver, replicaserver, name, replicationmode, State, replicationhealth, ReplicationState, @{Expression={"{0:0.0}" -f ($_.FrequencySec / 60)};Label="Target Freq (min)"}, @{Expression={"{0:N0}" -f ((get-date)-($_.lastreplicationtime)).TotalMinutes};Label="Delta (min)"} ,AutoResynchronizeIntervalStart,LastReplicationTime,ReplicaPort, AuthTypeif ($server.ReplicationHealth -eq 'Normal'){ if ($server.ReplicationHealth -eq 'Normal')

{Write-Host -ForegroundColor Green "Lo stato è Ok Replicating"}

elseif ($server.ReplicationHealth -eq 'Warning')

{Write-Host -ForegroundColor Yellow "Lo stato è Warning"}

elseif ($server.ReplicationHealth -eq 'Critical')

{Write-Host -ForegroundColor Red "Lo stato è Error"}


How to display Popup in GUI during script execution?

$
0
0

Hello

I created a script where I am reading the contents from hard coded folder. Now I want to display some kind of GUI where user will enter or select folder Path, but this should not appear before beginning of script it should appear after some process.

I also want to display some kind of alert/notification with better GUI.

How this can be achieved?

Avian

Script to locate non-archived user folders

$
0
0

Here is what i have so far,

$Check=get-aduser -filter 'enabled -eq $false'  | where { $_.samaccountname -eq ((Get-ChildItem '\\ROOT\share\users\').name) }

I have a test account set as disabled in AD, and it is checking against folders in our share, it should come back with disabled accounts that still have folders in share/users/.

At this point the output is not showing any output. 

Grabbing Cert Thumprint to create SSLCertificateSHA1Hash registry key on mulitple computers

$
0
0

We have a need to grab a Certificate Thumbprint in order to create a SSLCertificateSHA1Hash registry key on multiple computers as outlined in the KB article.  https://support.microsoft.com/en-us/kb/2001849

The registry creation portion of the script worked once but now does not for some reason. The script will look like it runs successfully but the registry key never gets created.  I believe its failing trying to import the data in the reg key.  The thumbprint needs to be converted to hex format (0x34,0xa2, etc) in order to be able to import the data properly.

Import-Module psremoteregistry
$computers = Get-Content c:\scripts\ssl\computer.txt
$cert = Invoke-Command -ComputerName $computers -ScriptBlock {Get-ChildItem Cert:\LocalMachine\My}
$data = $cert.Thumbprint
$formated= $data -replace '(..)','0x$1' -replace'(....)','$1,'
$newdata = $formated.Substring(0,$formated.Length-1)-split","
Set-RegBinary -ComputerName $computer -Hive LocalMachine -Key "system\currentcontrolset\control\terminal Server\WinStations\RDP-Tcp" -Value SSLCertificateSHA1Hash -Data $newdata

For the 2nd part I need help granting Network Service account Read perms to the local cert on each of the computers.

any help greatly appreciated.


Bruno Frisan

PSCredential in binary cmdlet

$
0
0

I am writing my first binary cmdlet (written in C#). I want to use the credential parameter like most Microsoft cmdlets. The issue is I cannot find an example of how to use it.

I implemented some Windows identity impersonation, using the credential Username and Password properties. Unfortunately, even though the user context says it is using the supplied credentials, I receive an unauthorised exception from the remote machine I am connecting to.

I am trying to use ServiceController and ServerManager to control services and IIS sites.


Modify existing permissions on folders / sub-folders

$
0
0

Hi,

I am not a programmer and not familiar with PowerShell Scripting.

My target: modifying of IUSR permissions (IIS user) on the folders (also for sub-folders and files) WITHOUT any negatively effect to existing permissions of other users and Groups, AND without any effect to top-level folder.

Folder structure:

E:\TESTDATA (that is top-level Folder. On this level NO permission modifying)

E.\TESTDATA\Folder1 (on this Level AND all sub-Folders / files, IUSR permissions should be set to MODIFY. Existing permissions of other users/groups MUST exist as.

E:\TESTDATA\Folder2 (the same like Folder1)

E:\TESTDATA\Folder3 (the same like Folder1)

E:\TESTDATA\Folder(n) (the same like Folder1, (n) is the arbitrary number)

How can I realize it?

I applied following script:

$Acl = Get-Acl (Get-ChildItem E:\TESTDATA -Recurse | where-object {($_.PsIsContainer)})
$Rule = New-Object  system.security.accesscontrol.filesystemaccessrule("IUSR","Modify","Allow")
$Acl.SetAccessRule($Rule)
Set-Acl E:\TESTDATA $Acl

I get error:

Get-Acl : Cannot find path 'Upload' because it does not exist.
At line:1 char:15+ $Acl = Get-Acl <<<<  (Get-ChildItem E:\TESTDATA -Recurse | where-object {($_.PsIsContainer)})+ CategoryInfo          : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException+ FullyQualifiedErrorId : GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand

And error:

Set-Acl : Cannot bind argument to parameter 'AclObject' because it is null.
At line:1 char:8+ Set-Acl <<<<  E:\TESTDATA $Acl+ CategoryInfo          : InvalidData: (:) [Set-Acl], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetAclCommand

Best Regards

Birdal

VM Inventory from multiple sources

$
0
0

Hi All,

I'm trying to get some statistics on my VMs from <g class="gr_ gr_114 gr-alert gr_gramm gr_run_anim Grammar multiReplace" data-gr-id="114" id="114">a SCVMM</g> Managed bunch of hosts/clusters AND a separate cluster that is not managed by SCVMM and export it all into one CSV.

If I do a simple 

Get-Vm -ComputerName uk-clstr-031, uk-clstr-032
get-VM | select TotalSize, Status, ComputerNameString, CreationTime, CPUCount, Memory, Cloud, Owner | export-csv "C:\Temp\HVExport.csv"

OR

Get-SCVMMServer -ComputerName "uk-vmmgmt-vmm"
get-VM | select TotalSize, Status, ComputerNameString, CreationTime, CPUCount, Memory, Cloud, Owner | export-csv "C:\Temp\HVExport.csv"
They will work but I cannot find a way to combine the two sources - when I try it seems to just reject Computer name from the separate unmanaged hosts.

I tried to do a <g class="gr_ gr_237 gr-alert gr_spell gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="237" id="237">foreach</g> statement (not that I fully understood it) but I get the same results. Any help and guidance would be appreciated. 

Azure Automation User Onboarding

$
0
0

Dear TechNet,

I am following the tech presented here https://365lab.net/2016/01/09/create-ad-users-with-help-from-azure-automation-and-sharepoint-online/ to create AD Users with Azure Automation and SharePoint Online.

I have followed al the steps from the link.

The code CreateADUserfromSPO.ps1 I have adjusted to my domain, and if I try the code from PowerShell ISE it executes, it creates the user in my AD. All the tests that I did appear in Azure, at the runbooks job details. So if I trigger the runbook from PowerShell, through that link that I received when I created the runbook it works, it triggers it. If I do the same from SharePoint nothing happens.

With a firebug, I have noticed that SharePoint does execute a POST operation. However what firebug shows me is encrypted, I cannot tell much of it other that it is a POST. Yet nothing reaches Azure, and the user is not created.

 Does anyone have any ideas?


Script stops on Access Denied!!

$
0
0

Hi ,

Power shell stops as soon as any error  "access denied " occurs. 

How can i continue my script by passing such errors .


Getting the Lease already present“,”message“:”Lease already present“ exception in PowerShell while executing the ”Set-AzureRmResource -Force" command

$
0
0

Getting the following exception in PowerShell while executing the "Set-AzureRmResource -Force"

command parallel for multiple web tests in Azure environment. Please help on this issue.

The pipeline has been stopped.      + CategoryInfo          : CloseError: (:) [Set-AzureRmResource], PipelineStoppedException      + FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet      + PSComputerName        : localhost   {"code":"Lease already present","message":"Lease already   present","innererror":{"diagnosticcontext":"2a3350d9-c78f-4572-9385-24ed387070b3","time":"2016-09-26T12:09:30.8564457Z"}}      + CategoryInfo          : CloseError: (:) [Set-AzureRmResource], ErrorResponseMessageException      + FullyQualifiedErrorId : Conflict,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet     + PSComputerName        : localhost

 

   Please find the code below.

 workflow workflow1{   
"======================================================="  

functionDoRequest($webTestName){       

Login-AzureRmAccount     

Set-AzureRmContext-SubscriptionID"cb83ec7a-4da9-4509-90ef-    1041ff23aab2"
        $PropertiesObject
=Get-AzureRmResource-ResourceGroupName"Default-        ApplicationInsights-CentralUS"-ResourceType'Microsoft.Insights/WebTests'-ResourceName $webTestName  -ApiVersion"2015-05-01"

        $PropertiesObject
.Properties.Enabled="False"   #Disable Web Test.

        $PropertiesObject
|Set-AzureRmResource-Force         

}  
 # "Serial"
    "======"
    $startTime = get-date
    foreach($row in $DataTable)
    {
      DoRequest $row
     }
    $serialElapsedTime = "elapsed time (serial foreach loop): " + ((get-date) -   $startTime).TotalSeconds
   
    "=======================================================" 

#  "======================================================="  
"Parallel"  
"========"
   $startTime
= get-date
   foreach
-parallel ($rowin $DataTable)  
{   
# Start-Sleep -seconds 5    
DoRequest $row.WebTest_Name    

}
   $parallelElapsedTime
="elapsed time (parallel foreach loop): "+((get-date)- $startTime).TotalSeconds  
   $parallelElapsedTime
"======================================================="

}

Thanks

Vijay




Viewing all 21975 articles
Browse latest View live


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