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

Why does my script ignore values in variable only some of the time?

$
0
0

Hello,

I'm a beginner at Powershell and am writing a script to gather the deployment details on all Azure Cloud Services attached to a Azure Subscription, including the info for any service that does not have a deployment.  

I understand that the way I'm going about this may be wrong and I am NOT looking for any help creating a final script.  Some of my script is written specifically so that I can better understand what it's doing (for learning purposes).

What I am looking for is help understand why my current script behaves the way it does.

Here's my current script:

###
#Create a report that shows the created date and latest deployment date for all
#hosted services (cloud services)deployments in MyAzureSubscription
###
Select-AzureSubscription MyAzureSubscription
$ServiceNames = Get-azureservice

foreach ($service in $ServiceNames){

        $ServiceName = $service | select -ExpandProperty ServiceName
        $ServiceDateModified = $service | select -ExpandProperty DateModified
        $service |
        get-azuredeployment -ErrorAction SilentlyContinue -ErrorVariable NoDeployment |
        Select @{Name="ServiceName";Expression={$ServiceName}}, DeploymentName, Status, CreatedTime, LastModifiedTime, @{Name="ServiceDateModified";Expression={$ServiecDateModified}}, @{Name="NoDeployment";Expression={$NoDeployment}} |
        Sort-Object -Propert DeploymentName |
        export-csv "outputfile.csv" -notypeinformation -append

        #Test statements below
        #Write-Host "NoDeployment Below:"
        #$Service | select ServiceName | Write-Host
        #Write-Error $NoDeployment
        Write-Host $ServiceName
        }

The output file only contains a list of servicenames and deployment details for services that do have a deployment.  None of the services that have no deployments are added/exported to the csv file.  However, the "write-host $ServiceName" writes ALL the service names in the powershell window, regardless of whether there's a deployment or not.

What I don't understand is why the Select @{Name="ServiceName";Expression={$ServiceName}} only outputs the service names of services that have deployments instead of ALL service names regardless of whether they have a deployment or not.

I've already proven that the variable $ServiceName does, at some point, save the ServiceName into the $ServiceName variable by writing it to host on each iteration of the foreach loop.  So why is it ignoring some ServiceNames when outputting/exporting to the csv file?

Thanks!


Use Variables created in script block outside of script block

$
0
0

hello

I have a code like:

$command= { param($p1,$p2)

if (Test-Path "D:\$p1") {

$s=$p1+ "_" +$p2

}

} Invoke-Command -session $sesion-ScriptBlock $command -ArgumentList 1,2

here session is already created with remote server. Invoke-Command runs that script block on a remote server.

Now I want to use that variable $s after invoke-command like

$command= {

param($p1,$p2)

if (Test-Path "D:\$p1") {

$s=$p1+ "_" +$p2

}

} Invoke-Command -session $sesion-ScriptBlock $command -ArgumentList 1,2

write-host $s

if ($s -eq "ZTE_3G") {

Write-host True

} else {

write host false

}

But here value of variable $s comes as null.

Could you please help me how can i use value of that vairable?




get-wmiobject remote machine getting access denied

$
0
0

I am trying to run a get-wmiobject to a remote machine like this

get-wmiobject -classname win32_operatingsystem -computername machinename

but getting this

access is denied error. I am running as domain admin and should have all rights. Also I can verify winRM is running on remote machine

get-service -computername remotemachine works just fine

Run perl script on remote server

$
0
0

Hello

I have 2 servers, server 1 and server2.

I have a perl script on server2 and I want to execute that perl script so my code is like

$command= { param($p1,$p2)

cmd /c test.pl $p1 $p2

} Invoke-Command -session $sesion-ScriptBlock $command -ArgumentList 1,2

session is already created with server2 from server1. 

perl script kept on server2 spawn another cmd which interacts with server3.

When I run above code that perl script start executing but it stays in executing step for infinite time..as per observation, I have found that it stucks when it tried to spawn another cmd which interacts with server3 from server2.

How can I handle this?

What is your preferred import format and why?

$
0
0
Just curious as to what people like to use for importing information into PowerShell. It obviously depends on the format of the information, like lists, single text fields and lists of lists.

zarberg@gmail.com

pwrshell noob

$
0
0

i was left some code that performs clean up on a remote storage location. it is to delete files older than 30 day in a folders named 'FULL' that exist is various paths. the code has as some bugs.

$arr = gci \\somedomain.com\folder\ | Where-Object {$_.PSIsContainer} | 
Foreach-object {$_.Name} $directory = $arr | Foreach-object{ '\\somedomain.com\folder\'+$_+'\FULL' }
foreach ($dir in $directory) {$a = gci $dir foreach($x in $a) {$y = ((Get-Date) - $x.CreationTime).Days
     if ($y -gt 30 -and $x.PsISContainer -ne $True)
      {$x.Delete()}
    }
}

At C:\Users\xxxxxx\pwrshell\deleteFULL.ps1:6 char:56
+ foreach ($dir in $directory) {$a = gci $dir foreach($x in $a) {$y = ((Get-Date)  ...
+                                                        ~~
Unexpected token 'in' in expression or statement.
At C:\Users\xxxxxx\pwrshell\deleteFULL.ps1:6 char:55
+ foreach ($dir in $directory) {$a = gci $dir foreach($x in $a) {$y = ((Get-Date)  ...
+                                                       ~
Missing closing ')' in expression.
At C:\Users\68604\pwrshell\deleteFULL.ps1:6 char:30
+ foreach ($dir in $directory) {$a = gci $dir foreach($x in $a) {$y = ((Get-Date)  ...
+                              ~
Missing closing '}' in statement block.
At C:\Users\xxxxxx\pwrshell\deleteFULL.ps1:6 char:61
+ foreach ($dir in $directory) {$a = gci $dir foreach($x in $a) {$y = ((Get-Date)  ...
+                                                             ~
Unexpected token ')' in expression or statement.
At C:\Users\xxxxxx\pwrshell\deleteFULL.ps1:10 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

Get-Content to msg, special characters

$
0
0

So, I'm trying to use the following line to display the content of test.txt as a pop up on a few computers;

Get-Content C:\Powershell\test.txt  | Invoke-Command -ComputerName <Computer01>,<Computer02> {msg *}

This works fine with the exception of that characters like the Swedish "å","ä","ö" along with more common ones like "é" end up as "?" in the popup.

Just running "Get-Content C:\Powershell\test.txt" displays the correct text in the powershell window.

Running "Invoke-Command -ComputerName <Computer01>,<Computer02> {msg * åäö}" works and also displays the correct text in a pop up on the remote computers as intended.

So my question is simple, is there something I'm missing, or is there some other way to solving the problem?

Need script can switch Offfice 365 plan E1 to E3 and enable litigation hold from CSV file

$
0
0

Dear all,

Currently, i need a script can switch Office 365 plan E1 to E3 and enbale litigation hold from the list email in CSV file. I don't know why Microsoft is not enable litigation hold for E3 user by default? Please help me.

Many thanks.


Which WMI query can show offline disk?

$
0
0
Hi,
If a disk offline, I can use DISKPART > list disk to find it. Is it possible
in PoSH? I tried to use:
 
Win32_DiskDrive
Win32_DiskPartition
Win32_DiskDrivePhysicalMedia
 
But no property member can show Online or Offline status. Can anybody give
an advice?
 
Thanks,
MG
 
 

Appending a csv column exported from Active Directory

$
0
0

Hi Guys

We have a new access control system. The DB of the control system needs to be updated with new people from Active Directory. It has an import tool to this. I want to automate it to do it every hour. So I started writing a powershell script to export any users that have changed in the last day. Here is what I have so far:

Get-ADUser -Filter * -Properties * | Where {$_.Modified -ge $(Get-Date).AddDays(-1)} | select rcscardcode | Export-Csv -path C:\Users\johncolfer\Desktop\TempStuff\Active-dir\export12.csv

So as you can see I have selected a property "rcscardcode". It is a custom attribute in AD. An example of 1 of these numbers in the exported csv file is "1141410511000000" I need to be able to change this number to "1141410511" and all subsequent numbers in that column of the csv file. Is this possible? 

Any help would be great.

Thanks

John

How to make sure the user is entering the correct data I want to

$
0
0

Hello scripting guys!

I become desperate while creating a script - It must be foolproof and this is why I created this:

$days = @(0..31)
$month = @(0..12)
$years = @(2000..3000)

$ag = $true

while($ag)
{
    $y = Read-Host "Date"
    if($y.Length -eq "10")
    {
        if(($y.split(".")[0] -gt 31) -or ($y.Split(".")[1] -gt 12) -or ($y.Split(".")[2] -gt 3000))
        {
            Write-Host "no valid date!"
            $ag = $true
        }
        elseif(($days -contains $y.Split(".")[0]) -and ($month -contains $y.Split(".")[1]) -and ($years -contains $y.Split(".")))
        {
            $ag = $false
            Write-Host "$y is your VALID Date!"
        }
    }
    else
    {
        Write-Warning "Try it again."
        $ag = $true
    }
}

The point is to create a script which keeps the conditions for a date.

The format I try to do is "dd.MM.yyyy".

Another nice thing would be if the user types in something like "9.7.2016" and the script automatically puts the 0 before it like "09.07.2016".

How to parse out the DC value from distinguishedname entry in the adgroupmember commandlet

$
0
0

I’m brand new to powershell and am working with the adgroupmember commandlet. I want to create a table with the DC value from distinguishedname and the samaccountname. So far I’ve got the samqaccountname worked out (see below) and I can get the distinguishedname value without a problem; but, how do go about getting the DC value from distinguishedname?

Thanks

Ron

get-adgroupmember fahq-gu-ccdba -recursive | Sort-object -property samaccountname| format-table -property samaccountname

certreq -submit run locally returns successful but run remote via invoke-command hangs

$
0
0

Good morning I have been struggling with a certificate request script.

The requesting server is in the dmz and I have a management server internally.

I successfully create the Inf file, as well as the req file then copy the req file to my internal management server. Once copied internal I attempt to run the following command from my laptop executing as my admin account

$Fqdn = "server.dmz.com"
$managementServer = "InternalServer"
$Path = "C$\Test\CertRequests"

Invoke-Command -ComputerName $Managementserver -ScriptBlock {param($CertificateAuthority,$FQDN,$Managementserver,$Path) certreq.exe -submit -attrib "CertificateTemplate:DVNOfflineComputer" -config "$CertificateAuthority"  "\\$Managementserver\$Path\$FQDN.req" "\\$Managementserver\$Path\$FQDN.crt"} -ArgumentList $CertificateAuthority,$FQDN,$Managementserver,$Path


This exact command pasted into a powershell window locally on the management server returns the crt file.
Run via invoke-command just hangs forever. I even tried to the Silent=True in inf file as well as -q but neither worked.

Any help is greatly appreciated.

Creating new accounts via Powershell and importing a .csv

$
0
0
I'm trying to create a group of service accounts in AD my importing a CSV using Powershell. It worked...halfway. The test account was created in the right OU but it was disabled and missing some other information. I have a column in my CSV that says enable witha  value of $true.

Powershell to create COM+ Applications fails when run remotely.

$
0
0

Hi,

I have a power shell script to create COM+ Applications on Windows 2008 server. We need these for some of our legacy apps.

I tried using the COMAdmin object and also tried executing MSI file. Both fail.

For MSI i get the below exception

MSI (c) (E0:74) [12:42:33:215]: Failed to connect to server. Error: 0x80070005

and when used COMAdmin,

the exceptions reads as : Could not load object COMAdmin...

I am using PSExec remotely to run this ps1 file.

Note

1. The account under which psexec runs, is admin on the Windows 2008 box.

2. I have several other powershell scripts that run fine remotely. The others are writing to the registry etc.

3. The particular script runs fine locally.

Can someone from Microsoft work with me on this issue. I have been trying to resolve this from a long time.


RMK_P



Powershell Script Updating/Replacing AD Fields and Logging

$
0
0

I consider myself a powershell begginer and I am having trouble with getting logging going for my powershell script.

The goals of my script

  •  import fields from a csv file that works fine. Fields match up with AD Attributes
  • Set variables for each field.
  • Use the Set-ADUser command to update the fields. This works fine
  • I have not been able to capture all the changes or errors into a log file and I am not sure I am understanding what to do when reading online. 
  • I added a line at the end to pretty much show what information has been taken from the csv file but this is not true logging because it is not recording errors such as if the username is not found in ad, a field is null, etc

I am posting a sample of the script if needed so please be kind ..... :)

param($Filearg) iF ( ! $Filearg ) {

         echo “Need to supply csv File as argument!!”

            exit 1

}


#####Mapped Fields to From CSV to Active Directory#####################
#####Field0  = Surname (Last Name)
#####Field2  = Employee Number
#####Field4  = Phone Number
#####Field5  = Title
#####Field7 = Start Date
#####Field8  = AD Username
#####Field14 = Department Number
#####Field19 = Fax Number
#####Field21 = Street Address
#####Field23 = (l) City
#####Field24 = State
#####Field25 = Zip Code
########################################################################


Import-csv $filearg | select-object Field0,Field2,Field4,Field5,Field7,Field8,Field14,Field19,Field21,Field22,Field23,Field24,Field25 -unique | Foreach-object  {
$today = Get-Date -format yyyyMMdd 
$sn = $_.Field0
$employenm = $_.Field2
$phone = $_.Field4
$title = $_.Field5
$date = $_.Field7
$name = $_.Field8
$department = $_.Field14
$Fax = $_.Field19
$Street = $_.Field21
$City = $_.Field23
$State = $_.Field24
$Zip = $_.Field25
$Faxnum = $_.Field19
$Suite = $_.Field22

echo “#########  Updating User Accounts #############”




Set-ADUSER -Identity $name -replace @{sn=$sn} 
Set-ADUSER -Identity $name -replace @{EmployeeNumber=$employenm} 
Set-ADUser -Identity $name -replace @{telephonenumber=$phone} 
Set-ADUSER -Identity $name -replace @{title=$title}  
Set-ADUser -Identity $name -replace @{extensionAttribute1=$date} 
#Set-ADUSER -Identity $name -replace @{department=$department}
Set-ADUSER -Identity $name -fax $Fax 
#Set-ADUSER -Identity $name -replace @{streetAddress=$Street;$Suite}
Set-ADUSER -Identity $name -streetAddress $Street$Suite 
Set-ADUSER -Identity $name -replace @{l=$City} 
Set-ADUSER -Identity $name -replace @{st=$State} 
Set-ADUSER -Identity $name -replace @{postalcode=$Zip}

Write-Output "Updating $name" Surname=$sn,EmployeeNumber=$employenm,Phone=$phone,Title=$title,UserId=$name,Fax=$fax,Street=$street,Suite=$Suite,City=$City,State=$state,ZipCode=$Zip _______________ >> E:\ADSync\Logs\ADSync_$today.log

}

Any help would be appreciated

Parallel processing using Scriptblock not working from windows task scheduler

$
0
0

Hi,

I am using scriptblock to run parallel commands. My code is working correctly when I am running directly from PowerGUI IDE, but when I schedule it inwindows task scheduler or Visualcron, it's only processing first 4 commands and then stopping. Why this happening? Is there any conflict with Scriptblock with windows task scheduler? Is there anything that is destroying the Scriptblock after running the first instance of 4 threads? Feeling helpless, no way I am able to make it working from task scheduler. Any help?

-----

## Run commands in parallel
$MaxThreads = 4
$SleepTimer = 1000

## Array contains 20 commands
$Commands = @()

## Parallel run block
## ===================================================
ForEach ($Command in $Commands)
{
   While (@(Get-Job -state running).count -ge $MaxThreads)
   {      
   Start-Sleep -Milliseconds $SleepTimer
   }

   Start-Job -scriptblock {
   $objProcess = New-Object System.Diagnostics.Process
   $objProcess.StartInfo = New-Object System.Diagnostics.ProcessStartInfo
   $objProcess.StartInfo.FileName = "C:\Program Files (x86)\SPSS\perfcalc.exe"
   $objProcess.StartInfo.Arguments = $args[0]
   $objProcess.StartInfo.UseShellExecute = $shell
   $objProcess.StartInfo.WindowStyle = 1
   $objProcess.StartInfo.RedirectStandardOutput = $true
   $null = $objProcess.Start()
   $objProcess.WaitForExit()
   $exitcode = $objProcess.ExitCode
   $objProcess.Dispose()

   if ($exitcode -ne 0)
   {
   throw "Error{0}" -f ([string] $exitcode)
   }
   } -ArgumentList $Command -Name $Command | Out-Null

}

While (@(Get-Job -State Running).count -gt 0)
{
    Start-Sleep -Milliseconds $SleepTimer
}

$Results = ""
foreach ($Job in Get-Job)
{
    if ($Job.State -eq 'Failed') 
{
$Results += $Job.Name + ($Job.ChildJobs[0].JobStateInfo.Reason.Message)
}
else
{
        Write-Host (Receive-Job $Job)
}
}

ForEach($Job in Get-Job)
{
    Remove-job -Force $Job
}

                   



Add a security group to CN=DS-Replication-Get-Changes-All,CN=Extended-Rights,CN=Configuration,DC=corp,DC=domain,DC=net

$
0
0

Any help would be greatly appreciated!

The value I am trying to edit is (CN=DS-Replication-Get-Changes-All).  The rightsGuid for the controlAccessRight is 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2.  I have used powershell to update attributes in AD, but have no clue how to update the rights in the configuration or the schema partitions.  I have used the script below to update rights for admins to be able to change passwords etc... but now I need to figure out how to work with the configuration and schema partitions.

Import-Module ActiveDirectory
$acl = get-acl "ad:DC=corp,DC=domain,DC=net"

$group = Get-ADgroup 'AD Service Administration Tasks'

$sid = new-object System.Security.Principal.SecurityIdentifier $group.SID

# The following object specific ACE is to grant Group permission to change user password on all user objects under OU

$objectguid = new-object Guid  00299570-246d-11d0-a768-00aa006e0529 # is the rightsGuid for the extended right User-Force-Change-Password (“Reset Password”)  class

$inheritedobjectguid = new-object Guid  bf967aba-0de6-11d0-a285-00aa003049e2 # is the schemaIDGuid for the user

$identity = [System.Security.Principal.IdentityReference] $SID

$adRights = [System.DirectoryServices.ActiveDirectoryRights] "ExtendedRight"

$type = [System.Security.AccessControl.AccessControlType] "Allow"

$inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance] "Descendents"

$ace = new-object System.DirectoryServices.ActiveDirectoryAccessRule $identity,$adRights,$type,$objectGuid,$inheritanceType,$inheritedobjectguid

$acl.AddAccessRule($ace)

Set-acl -aclobject $acl "ad:DC=corp,DC=domain,DC=net"




Checking for blank passwords on Local User Accounts (remotely)

$
0
0

The most popular script to do this is a VB script.

In the script it basically runs through all of the accounts and attempts to change the password using a blank password as the initial credentials.

I need this done in powershell since the rest of the script design will be done in Powershell.

The problem I'm running into is that it's passing through my admin credentials to change the passwords so it succeeds every time. The script itself looks for an error code of [0] (meaning it worked and the password was blank to begin with) and a fail code in which it kicks back "The password was not blank" then resumes on the next account.

Here is the test version of just the password changing part:


==================================
$ErrorActionPreference
="SilentlyContinue"

$strPassword=""

$server="serverName"

$computer= [ADSI]("WinNT://"+$server+",computer")

$user= [ADSI]("WinNT://"+$server+"/Guest, user")

$user.invoke("SetPassword", $strPassword)

If($?)

{

Write-Host"There was a blank password on the"$computer.Name $user.name "account."

}

If(!$?)

{

Write-Host $computer.Name $user.name"is safe."

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


Is there a way to force it to NOT use my credentials and require a supplied password (not promted but stored in a variable) for each attempt?

The VBS script with the original idea is below.

"

On Error Resume Next
Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strPassword = ""
Set colAccounts = GetObject("WinNT://" & strComputer)
colAccounts.Filter = Array("user")
For Each objUser In colAccounts
objUser.ChangePassword strPassword, strPassword
If Err = 0 or Err = -2147023569
    Then
Wscript.Echo objUser.Name & " is using a blank password."
End If
Err.Clear
Next










Thanks
Jason

Jason Roberson NC State Employees' Credit Union Raleigh, NC

Import AD module

$
0
0

Hi,

Im having difficulty importing the AD module.

I have a 2008 Standard Server, added the remote AD tools.

When I try and load the AD module

PS C:\> import-module activedirectory
Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory.
At line:1 char:14+ import-module <<<<  activedirectory+ CategoryInfo          : ResourceUnavailable: (activedirectory:String) [Import-Module], FileNotFoundException+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Any ideas?


Phil
Viewing all 21975 articles
Browse latest View live


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