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

How to pipe a variable to a filename and save it

$
0
0

Good day all,

I was trying out the Get-WindowsAutoPilotInfo.ps1 script and is trying to find a way to save the corresponding filename to use the serial number of the machine which I am running out.

So far I have tested using the command,

$SN = gwmi win32_bios | fl SerialNumber

which returned the serial number correct in the variable $SN.

When I tried to save it using the command,

Get-WindowsAutoPilotInfo.ps1 -OutputFile D:\$SN.csv

I got the error saying the output filename is too long and have exceed the max length allowed.

I wanted to run the commands in a batch file so it will just generate the corresponding serial number of the machine I run it on.


Listing all the patches available for particular software in remote machine

$
0
0
 $UninstallKey="HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Installer\\Patches\\241630F0445788D4A862850B488648A9\\SourceList"
    #Create an instance of the Registry Object and open the HKLM base key

    $reg=[microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine','machinename') 


    #Drill down into the Uninstall key using the OpenSubKey Method

    $regkey=$reg.OpenSubKey($UninstallKey) 

    #Retrieve an array of string that contain all the subkey names

    $subkeys=$regkey.GetSubKeyNames() 

    #Open each SHKEY_LOCAL_MACHINE\SOFTWARE\Classes\Installer\Patches\41354CB878A265745813AF76B63C05D5\SourceListubkey and use GetValue Method to return the required values for each
    
    #$UserInfo = Get-CimInstance –ComputerName $pc –ClassName Win32_ComputerSystem | Select-Object UserName
    foreach($key in $subkeys)
    {
 
        $thisKey=$UninstallKey+"\\"+$key 

        $thisSubKey=$reg.OpenSubKey($thisKey) 

        $obj = New-Object PSObject
           
        $obj | Add-Member -MemberType NoteProperty -Name "DisplayName" -Value $($thisSubKey.getvalue("PackageName"))
        
 
        $array += $obj
         
    }

  $array | select DisplayName | Where-Object {$_.DisplayName -like "Sunrise Enterprise Scheduling 17.3 Engine Services"}

DSC pull client cannot find resource

$
0
0

Hi All,

below is PULL server config

=======================

Configuration HTTPPullServer

{

   # Module must exist on Pull server

Import-DscResource -ModuleName xPSDesiredStateConfiguration

       Node localhost

       {
           xDSCWebService PSDSCPullServer
           {
             Ensure = 'Present'
             EndpointName = 'PSDSCPullServer'
             Port = 8080
             PhysicalPath = "$env:SYSTEMDRIVE\inetpub\wwwroot\PSDSCPullServer"
             CertificateThumbPrint = 'AllowUnencryptedTraffic'
             ModulePath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Modules"
             ConfigurationPath = "$env:PROGRAMFILES\WindowsPowerShell\DscService\Configuration"
             State = 'Started'
             UseSecurityBestPractices =$False

           }          
   }
}

 # Running this Script will Generate a .Mof file in the location below

HTTPPullServer -OutputPath 'C:\dsc\PullServerConfig\'

Client LCM config

[DSCLocalConfigurationManager()]
configuration LCM_HTTPPULL
{
    

    Node localhost
    {
        Settings
        {

            RefreshMode = 'Pull'
            ConfigurationMode = 'ApplyandAutoCorrect'
            
        }

        ConfigurationRepositoryWeb server-PullSrv
        {
            ServerURL          = 'http://server:8080/PSDSCPullServer.svc' # notice it is https
            RegistrationKey    = '16f46d7b-3b45-4a22-9159-c0dfbb25c032'
            
            AllowUnsecureConnection =$True
            ConfigurationNames = @('test')     

        }

        ReportServerWeb Server-PullSrv
        {
            ServerURL       = 'http://server:8080/PSDSCPullServer.svc' # notice it is https
             AllowUnsecureConnection =$True
        }
    }
}

=============================

And then i create a test.mof

Configuration test
{
    Import-DscResource –ModuleName 'PSDscResources'
    Node localhost
    {
        Registry DisableRC4_128
        {
             Key = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Ciphers\RC4 128/128'
             ValueName = 'Enabled'
             ValueData = '0'
             ValueType = 'Dword'
}

       }

}

and then i put test.mof and it test.mof.checksume  put into C:\Program Files\WindowsPowerShell\DscService\Configuration

but on the client i run update-dsconfiguration -verbose -wait, i saw below log

The attempt to 'get an action' for AgentId A2F77D6E-9CA7-11E8-BB36-005056A7C4C5 from server URL http://server:8080///PSDSCPullServer.svc/Nodes(AgentId='A2F77D6E-9CA7-11E8-BB36-005056A7C4C5')/GetDscAction failed
with server error 'ResourceNotFound(404)'.
For further details see the server error message below or the DSC debug event log with ID 4339.
ServerErrorMessage:- 'The assigned configuration 'test' is not found in the pull server configuration repository.'

Please give me some hits. Thanks



Script to get the disk usage and memory from a list of servers

$
0
0
I have a list of servers in a text file. I want a script to fetch the memory and the full disk space and free disk space and the percentage free space of the drives on these servers in a csv file.

Powershell - Extract sections from range found in word document

$
0
0
Below code works fine, we got start and end point which needs to be extracted but im not able to get range.set/select to work

I'm able to get the range from below, just need to extra and save it to csv file...

$found= $doc.Range($startPosition, $endPosition).Select() - this piece doesnt work...


    $file = "D:\Files\Scan.doc"
    $SearchKeyword1 =  'Keyword1'
    $SearchKeyword2 =  'Keyword2'    
    
    $word = New-Object -ComObject Word.Application
    $word.Visible = $false
    $doc = $word.Documents.Open($file,$false,$true)
    $sel = $word.Selection
    $paras = $doc.Paragraphs
    $paras1 = $doc.Paragraphs
    $paras2 = $doc.Paragraphs
    
    foreach ($para in $paras)
    {
        if ($para.Range.Text -match $SearchKeyword1)
        {
            write-host $para.Range.Text
            $startPosition = $para.Range.Start
    
    }
    }
    foreach ($para in $paras1)
    {
        if ($para.Range.Text -match $SearchKeyword2)
        {
            write-host $para.Range.Text
            $endPosition = $para.Range.Start
        }
    }
    
    Write-host $startPosition
    Write-host $endPosition
$found= $doc.Range($startPosition, $endPosition).Select()
$found.Text | Out-File "D:\Found.txt"
    
    
    # cleanup com objects
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()

Powershell Set-Acl use without changing owner?

$
0
0
I have a folder, and I am trying to grant full permissions to another user, like so:

$Acl = Get-Acl "C:\MyFolder"

$AccessRule = New-Object  system.security.accesscontrol.filesystemaccessrule("bobby","FullControl", "Allow")
$Acl.AddAccessRule($AccessRule)
Set-Acl -AclObject $Acl "C:\MyFolder"

The owner of the folder is "Joe".
The powershell script runs under the "SyncProcess" account.

If Joe is the owner of the folder, the script fails with the error message:
Set-Acl : The security identifier is not allowed to be the owner of this object

If I change the owner of the folder manually to SyncProcess, then the script runs fine without error.

My question is, why does Set-Acl try to change the owner?  I am not trying to change the owner, nor do I want to.  I read the script to mean, get the current Acl, add the full control permission access rule for Bobby, and then update the folder.  I don't think I am doing anything here to change the owner?

if I add $Acl | fl both before and after the AddAccessRule method call, the Owner is the same in both, unchanged.  Whe does Set-Acl think the owner is changing?

Thanks.

Need pwershell output in HTML

$
0
0

Hi All,

The below mention code is for getting App Pool Status & require the HTML page of all server in ONE HTML. Output is generating only the HTML but not generating the content inside the HTML.


$computers = Get-Content "D:\WebSite\ServerBaseAppstatus\Machines.txt"

$ServerName = $computers.Split(",")

$outfile = "D:\WebSite\ServerBaseAppstatus\services.html"

foreach ($Machine in $ServerName) 
{
       Write-Host "_________________________________"
       Write-Host "Details from server $Machine..."
       Write-Host "---------------------------------"
       $result = Invoke-command  -ComputerName $Machine  -ScriptBlock{ param($Machine)

            Import-Module WebAdministration
            set-Location IIS:\AppPools
            $appPoolCollections = dir
            foreach ($pool in $appPoolCollections)
            {
                # Loop through the collection and find the status of the appPool 
                $appPoolName = $pool.Name
                $appPoolState = $pool.state
                $appPoolVersion= $pool.managedRuntimeVersion
                #Write-Host "$appPoolName with version $appPoolVersion is $appPoolState"  
             }
        } 
        
        Write-Host "++++++++++++++++++++++++++++++++++++++++++++++++++++++" 
        
        
  }
  


Sumeet Gill


Get info from Lenovo Laptop

$
0
0
We have different Lenovo laptops like W500, T430s, T61p...
Is there way to get this info by running powershell script?

Powershell Script to Add Text to Host files

$
0
0

Need a powershell script to add host entries to an existing host file for a list of servers.

It should pull from something like servers.txt which will have IP Address or hostname of the server(s) getting updated, add entries to the host file currently located in the standard windows directory, and give an output to a document such as Hosts-Changed.txt of Server that that was updated.

Datetime formatting for script

$
0
0


I'm new at powershell scripting and have cobbled together a script from examples, but like any noob, I am running into some issues.  Your feedback is appreciated.

This script should read $logfile and output entries in the past ten minutes that include text "DPR-ERR".   The log file has datetime stamp formatted like "2018-08-09 07:51:40.714"      I'm using PS v5.   

The errors are listed when I run

PS C:\users\lleichman-sa\Desktop> $logfile = "E:\cognos\c10_64\logs\cogserver.log" 

cat $logfile |
Select-String "DPR-ERR" -SimpleMatch |
  select -expand line 
131.243.164.24:9300	1784	2018-08-09 07:51:40.714	-8	shutdown	na	na	0	main	DISP	5005	1	DPR-ERRAudit.Other.dispatcher.DISP.com.cognos.pogo.services.DispatcherS
ervices	StopService	AnnotationService		Success		
131.243.164.24:9300	7496	2018-08-09 15:17:12.339	-8	shutdown	na	na	0	main	DISP	5005	1	DPR-ERR Audit.Other.dispatcher.DISP.com.cognos.pogo.services.Dispatcher
Services	StopService	PDC		Success		
131.243.164.24:9300	5900	2018-08-13 11:37:25.644	-8	shutdown	na	na	0	main	DISP	5005	1	DPR-ERRAudit.Other.dispatcher.DISP.com.cognos.pogo.services.DispatcherS
ervices	StopService	ReportService		Success		
131.243.164.24:9300	5900	2018-08-13 11:37:28.690	-8	shutdown	na	na	0	main	DISP	5005	1	DPR-ERRAudit.Other.dispatcher.DISP.com.cognos.pogo.services.DispatcherS
ervices	StopService	IBM Cognos Enhanced Search Service		Success

When I run my test script, I'm getting the following error:

You cannot call a method on a null-valued expression.
At C:\Users\lleichman-sa\Desktop\Untitled8.ps1:11 char:15
+               $error_time = [datetime]($matches[1]).split(",")[0]

  

# This script will parse the log file and list errors posted in the last ten minutes including "DPR-ERR"s.

$logfile = "E:\cognos\c10_64\logs\cogserver.log" 

cat $logfile |
Select-String "DPR-ERR" -SimpleMatch |
  select -expand line |
     foreach {
              $_ -match '(.+)\s\[(DPR-ERR)\]\s(.+)'| Out-Null 
              $error_time = [datetime]($matches[1]).split(",")[0]
              if ($error_time -gt (Get-Date).AddMinutes(-10).ToString("yyyy-MM-dd HH:mm:ss:fff")) 
              {
              write-output "CRITICAL: There is an error in the log file $logfile around $($error_time.ToShortTimeString())"; exit(2) 
              }
            }
  write-output "OK: There was no errors in the past 24 hours." 


Compare-Object Not Working via Scheduled Task

$
0
0

I'm stumped, hoping someone might have an idea. Let me provide a short overview:

I'm comparing objects in two different arrays based on a specific property. It works fine when I run it manually (e.g. via Powershell ISE), but when I run it through a scheduled task the compare produces no results when I know it should and it works when I run it manually. The thing I don't get is this script has other sections in it that utilize Compare-Object, and to my knowledge, they work fine.

What am I missing here? Not sure what else to do to troubleshoot, what I've been doing as a troubleshoot step is export the results from both arrays i'm comparing as well as the one that contains the compare results. Both source arrays have data, but the comparison comes up empty. Again, I run it manually I get results.

Any idea? This is the code:

$userObjects = Get-ADObject `
-LDAPFilter "(&(objectCategory=person)(objectClass=user)(msExchHideFromAddressLists=TRUE)(uncPID=*)(homeMDB=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" `
-SearchBase $userObjPath -ResultSetSize $null `
-Properties $objAttributes -Server $domainController | select $objAttributes -ErrorAction SilentlyContinue

#Compare the current dual account users to the hidden contact objects, if they don't exist as a current dual account user, select them looking at the PID
$formerDualAcctUsers = Compare-Object -ReferenceObject $dualAcctUsers -DifferenceObject $userObjects -Property uncPID -PassThru | `
where { $_.sideIndicator -eq "=>" } | select $userObjAttr

#Export the arrays to view the results, when run manually $formerDualAcctUsers has data, when ran as a scheduled task it is empty
$userObjects | export-csv -path "C:\UNCH\GalSync\userObjs.csv" -notypeinformation
$dualAcctUsers | export-csv -path "C:\UNCH\GalSync\dualAcctUsers.csv" -notypeinformation
$formerDualAcctUsers | export-csv -path "C:\UNCH\GalSync\former_dacu.csv" -notypeinformation

Listing (and deleting) AD accounts that have been disabled for XX days

$
0
0

Howdy,

I know I can use the lastlogondate to find Ad accounts that are not used but we're looking to do something a bit different.  When someone leaves our company, we go in and Deactivate their Ad account and move it to a different OUs than the rest of them.  I'm looking to find a script that can find the accounts that have been deactivated for more than 60 days based on the date that we flagged it as inactive and not based on when they logged in last.

Is that easily accomplished?  If so, can someone point me towards a tutorial or give me a sample?  I'm searching around but haven't found this exact scenario yet.

Thanks!

Positional parameter error

$
0
0

Hi I am using https://365lab.net/2016/01/09/create-ad-users-with-help-from-azure-automation-and-sharepoint-online/#comments to run a runbook in Azure automation. When I execute the code 

param ( 
    [object]$WebhookData
)
#SharePoint Connection Info
$SPCredentials = Get-AutomationPSCredential -Name 'SPOAdmin'
$SPConnection = @{
    SharePointSiteURL = "https://abc.sharepoint.com/sites/UserOnboardingTest"
    Username = $SPCredentials.Username
    Password = $SPCredentials.GetNetworkCredential().Password
}
#Create an object from the webhook request
$UserData = ConvertFrom-Json -InputObject $WebhookData.RequestBody
$TargetOU = "OU=NoPolicy,OU=TEST,DC=abc,DC=local"
$ListName = "User Data"
$PasswordLength = "12"
$UPNSuffix = 'abc.com'
$FirstName = $UserData.FirstName
$LastName = $UserData.LastName
$Manager = $UserData.Manager
#region functions
function Convert-ToLatinCharacters {
    param(
        [string]$inputString
    )
    [Text.Encoding]::ASCII.GetString([Text.Encoding]::GetEncoding("Cyrillic").GetBytes($inputString))
}
function Get-JDDNFromUPN {
    param (
        [ValidateScript({Get-ADUser -Filter {UserprincipalName -eq $_}})] 
        [Parameter(Mandatory=$true)][string]$UserPrincipalName
    )
        $ADUser = Get-ADUser -Filter {UserprincipalName -eq $UserPrincipalName} -ErrorAction stop
        return $ADUser.distinguishedname
}
function New-JDSamAccountName {
    param (
        [Parameter(Mandatory=$true)][string]$FirstName,
        [Parameter(Mandatory=$true)][string]$LastName,
        [parameter(Mandatory=$false)][int]$FirstNameCharCount = 3,
        [parameter(Mandatory=$false)][int]$LastNameCharCount = 3
    )
    #Construct the base sAMAccountName
    $BaseSam = "{0}{1}" -f (Convert-ToLatinCharacters $FirstName).Substring(0,$FirstNameCharCount),(Convert-ToLatinCharacters $LastName).Substring(0,$LastNameCharCount)
    #Add a number until you find a free sAMAccountName
    if (Get-ADUser -Filter {samaccountname -eq $BaseSam} -ErrorAction SilentlyContinue) {
        $index = 0
        do {
            $index++
            $sAMAccountName = "{0}{1}" -f $BaseSam.ToLower(),$index
        } until (-not(Get-ADUser -Filter {samaccountname -eq $sAMAccountName } -ErrorAction SilentlyContinue))
    } else {
        $sAMAccountName = $BaseSam.tolower()
    }
    return $sAMAccountName
}
function New-JDUPNAndMail {
    param (
        [Parameter(Mandatory=$true)][string]$FirstName,
        [Parameter(Mandatory=$true)][string]$LastName,
        [Parameter(Mandatory=$true)][string]$UPNSuffix
     )
    #Construct the base userPrincipalName
    $BaseUPN = "{0}.{1}@{2}" -f (Convert-ToLatinCharacters $FirstName).replace(' ','.').tolower(),(Convert-ToLatinCharacters $LastName).replace(' ','.').tolower(),$UPNSuffix
    if (Get-ADUser -Filter {userprincipalname -eq $BaseUPN} -ErrorAction SilentlyContinue) {
        $index = 0
        do {
            $index++
            $UserPrincipalName = "{0}{1}@{2}" -f $BaseUPN.Split("@")[0],$index,$UPNSuffix
        } until (-not(Get-ADUser -Filter {userprincipalname -eq $UserPrincipalName} -ErrorAction SilentlyContinue))
    } else {
        $UserPrincipalName = $BaseUPN
    }
    return $UserPrincipalName
}
function New-JDADUser {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param (
        [Parameter(Mandatory=$true)][string]$FirstName,
        [Parameter(Mandatory=$true)][string]$LastName,
        [Parameter(Mandatory=$true)][string]$UserPrincipalName,
        [Parameter(Mandatory=$true)][string]$sAMAccountName,
        [Parameter(Mandatory=$true)][string]$OU,
        [Parameter(Mandatory=$true)][string]$Manager,
        [Parameter(Mandatory=$true)][int]$PasswordLength = 12
    )
     #Generate a password
     $Password = [System.Web.Security.Membership]::GeneratePassword($PasswordLength,2)
     #Construct the user HT
     $ADUserHt = @{
        GivenName = $FirstName
        SurName = $LastName
        ChangePasswordAtLogon = $true
        EmailAddress = $UserPrincipalName
        UserPrincipalName = $UserPrincipalName
        sAMAccountName = $sAMAccountName
        Name = "$FirstName $LastName ($sAMAccountName)"
        Displayname = "$FirstName $LastName"
        Manager = $Manager
        Path = $OU
        AccountPassword = (ConvertTo-SecureString -String $Password -AsPlainText -Force)
        Enabled = $true
        OtherAttribute = @{proxyAddresses = "SMTP:$UserPrincipalName"}
     }
     try {
        #Create the user and return a custom object
        New-ADUser @ADUserHt -ErrorAction Stop 
        Write-Verbose "Successfully created the user $($ADUserHt.Name)"
        [pscustomobject] @{
            sAMAccountName = $ADUserHt.sAMAccountName 
            UserPrincipalName = $ADUserHt.UserPrincipalName 
            Password = $Password
        }
     } catch {
        Write-Warning "Error creating the user $($ADUserHt.Name) `r`n$_"
     }
}
#endregion functions
    try {
        $sAMAccountName = New-JDSamAccountName -FirstName $Firstname -LastName $LastName
        $UPNandMail = New-JDUPNAndMail -FirstName $Firstname -LastName $LastName -UPNSuffix $UPNSuffix
        $ManagerDN = Get-JDDNFromUPN -UserPrincipalName $Manager
        #Create the user in Active Directory
        $NewAdUserHt = @{
            FirstName = $Firstname
            LastName = $LastName
            Manager = $ManagerDN
            sAMAccountName = $sAMAccountName
            UserPrincipalName = $UPNandMail
            OU = $TargetOU
            PasswordLength = $PasswordLength
        }
        Write-Output $NewAdUserHt
        $ADUser = New-JDADUser @NewAdUserHt -ErrorAction Stop
        $UpdateHt = @{
            Status = 'Created'
            UserName = $ADUser.sAMAccountName 
            EmailAddress = $ADUser.UserPrincipalName 
        }
        Update-SPOListItem -SPOConnection $SPConnection -ListItemID $UserData.ID -ListFieldsValues $UpdateHt -ListName $ListName
    } catch {
         $UpdateHt = @{
            Status = 'Error'
        }
        Update-SPOListItem -SPOConnection $SPConnection -ListItemID $UserData.ID -ListFieldsValues $UpdateHt -ListName $ListName
        Write-Warning $_
    }

I get an error :

Update-SPOListItem : A positional parameter cannot be found that accepts argument '+'.

At line:157 char:9

+         Update-SPOListItem -SPOConnection $SPConnection -ListItemID $ ...+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Update-SPOListItem], ParameterBindingException+ FullyQualifiedErrorId : PositionalParameterNotFound,Update-SPOListItem

Can anyone assist me on this.

Invoke-WebRequest property, analog of "LocationURL" one of "InternetExplorer.Application" ComObject

$
0
0

Is there Invoke-WebRequest property, analog of "LocationURL" one of "InternetExplorer.Application" ComObject?

Example: 

$ie = new-object -ComObject "InternetExplorer.Application"

#some code...

$token=$ie.LocationURL.tostring()

I need to get token from address bar for this service https://oauth.vk.com/authorize?client_id=1&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.8

like here

https://oauth.vk.com/blank.html#access_token=57afnb9797f2d1ef3f5cd6248094ce0c4acc6dd2a778210ab8c2b53cbf13ee38cafb0afb2b7c576db9fca&expires_in=86400&user_id=1

Get a report of No members of a Distribution Group

$
0
0

Hello team !!

I've been trying to get a report of users that don't belong to a certain Distribution List in Office 365, something like this , but just the opposite, no menbers instead of members:

Get-DistributionGroupMember -ResultSize unlimited grupo1@dominio.com | select DisplayName, PrimarySmtpAddress | Export-Csv C:\grupo1.csv -NoTypeInformation

Any ideas ??

thanks in advance

germain 


Network Details from Windows servers

$
0
0

Hi All,

I am trying to get NIC settings from list of windows servers along with  NIC label "NetConnectionID " and DNS suffer list, but unable to accommodate them in excel output , kindly help , below is the script 

$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet1 = $Excel.Worksheets.Item(1)
$Sheet1.Name = "Network"
$Sheet1.Cells.Item(1,1) = "Server_Name"
$Sheet1.Cells.Item(1,2) = "DHCP_Enabled"
$Sheet1.Cells.Item(1,3) = "IP_Address"
$Sheet1.Cells.Item(1,4) = "Subnet_Mask"
$Sheet1.Cells.Item(1,5) = "Default_Gateway"
$Sheet1.Cells.Item(1,6) = "DNS_Servers"
$Sheet1.Cells.Item(1,7) = "DNS_Reg"
$Sheet1.Cells.Item(1,8) = "Primary_WINS"
$Sheet1.Cells.Item(1,9) = "Secondary_WINS"
$Sheet1.Cells.Item(1,10) = "WINS_Lookup"
$Sheet1.Cells.Item(1,11) = "NIC lable"
$intRowNet = 2
$colSheets = ($Sheet1)
foreach ($colorItem in $colSheets){
        $intRow = 2
        $intRowNet = 2
        $WorkBook = $colorItem.UsedRange
        $WorkBook.Interior.ColorIndex = 4
        $WorkBook.Font.ColorIndex = 11
        $WorkBook.Font.Bold = $True
}
foreach ($colorItem in $colSheets){
        $WorkBook = $colorItem.UsedRange
        $WorkBook.EntireColumn.AutoFit()
        cls
}
$Computers = Get-Content .\Servers.txt
Foreach ($Computer in $Computers) {
        
                             
        $NetItems = gwmi Win32_NetworkAdapterConfiguration -ComputerName $Computer -ErrorAction Ignore | ?{$_.IPEnabled -eq "True"}
        $NetItems1 = gwmi Win32_NetworkAdapter -ComputerName $Computer  
        
                                                    foreach ($objItem3 in $NetItems) {
                                                        $Sheet1.Cells.Item($intRowNet, 1) = $Computer
                                                        $Sheet1.Cells.Item($intRowNet, 2) = $objItem3.DHCPEnabled
                                                        $Sheet1.Cells.Item($intRowNet, 3) = $objItem3.IPAddress
                                                        $Sheet1.Cells.Item($intRowNet, 4) = $objItem3.IPSubnet
                                                        $Sheet1.Cells.Item($intRowNet, 5) = $objItem3.DefaultIPGateway
                                                        $Sheet1.Cells.Item($intRowNet, 6) = $objItem3.DNSServerSearchOrder
                                                        $Sheet1.Cells.Item($intRowNet, 7) = $objItem3.FullDNSRegistrationEnabled
                                                        $Sheet1.Cells.Item($intRowNet, 8) = $objItem3.WINSPrimaryServer
                                                        $Sheet1.Cells.Item($intRowNet, 9) = $objItem3.WINSSecondaryServer
                                                        $Sheet1.Cells.Item($intRowNet, 10) = $objItem3.WINSEnableLMHostsLookup
                                                            $NetItems1 | Select-Object -ExpandProperty NetConnectionID | select {$Lable = $_;$Lable;$Sheet1.Cells.Item($intRowNet, 11) = $Lable ;}
                                                            $intRowNet = $intRowNet + 1
                                                        }

                                                            
                
$intRowNet = $intRowNet + 1

}



smart-card & pssc configuration file. Error message Some or all identity references could not be translated

$
0
0

I am attempting to configure a pssc file with required groups for smart-card authentication. I have added the following line to the .pssc:

RequiredGroups = @{ or = 'smartcard-logon' } but I keep receiving the following error message when attempting to register the file:

Register-PSSessionConfiguration : Some or all identity references could not be translated.
At line:1 char:1

If I remove the line the file registers fine and if I run test-pssessionconfigurationfile I receive "True".

I tried with powershell 5.1.14393.2368 first and then 6.0.4

Invoke-RestMethod response encoding

$
0
0

Hi all.

I would like to ask you, if it is possible to change encoding of API response. Response is in XML format.

My request is below: (yes, there is no dot between www and info)

$Response = Invoke-RestMethod http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_std.cgi?ico=28146123

You can try it on your own. You don't need any authorization. It's public list of czech firms.

This request returns me response, where is the city with special character 'á' (Tábor) and powershell shows me 'Tábor' instead.

This city is deep in reponse - $response.ares_odpovedi.odpoved.zaznam.identifikace.Adresa_ARES

so I would like to change encoding of whole XML response. I tried to save it to file and then load it with different encoding, but it didn't work for me. I wanted to change it using [System.Text.Encoding]::UTF8.GetBytes($Response), but it changes only the root of response:

xml                                                  Ares_odpovedi
---                                                   -----------------
version="1.0" encoding="UTF-8"        Ares_odpovedi

So I tried [System.Text.Encoding]::UTF8.GetBytes($Response.ares_odpovedi.odpoved.zaznam.identifikace.Adresa_ARES), but it also returns only root.

Please, could you help me with this issue? 

Thank you for eny advices.

Kind regards, Daniel Vácha

Not Able to Connect Azure from PowerShell.

$
0
0

I Installed AzureRM and Azure but still not able to connect tomy Azure Account. 'Connect-AzureRmAccount' giving me below result.

PS C:\windows\system32> Connect-AzureRmAccount

Account          : 

SubscriptionName : 

SubscriptionId   : 

TenantId         : 

Environment      : 

should i installed anything else? I am new to powershell.

Thanks,

Passing a collection into the pipeline

$
0
0
function Get-Hosts {
    [CmdletBinding(DefaultParameterSetName="HostList")]
    [OutputType([String[]])]
    param(
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)][switch]$Servers          
    )

    #Where we will store all the hosts that we find 
    $hostlist = [System.Collections.ArrayList]@() | Out-Null

    #Where in active directory we are searching
    [string]$searchBase = "OU=Computers,DC=company,DC=com"

    #Using Get-ADComputer to search active directory for our specified list of hosts and adding them to our arraylist
    $hostlist += Get-ADComputer -SearchScope Subtree -Filter "OperatingSystem -like 'Windows 8*'" -Properties * -SearchBase $searchBase | Select-Object -ExpandProperty CN       

    #returning the array list
    $hostlist 
}

function Get-HostUserActivity {

    [CmdletBinding(DefaultParameterSetName="UserActivity")]
    param(
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)][string[]]$ComputerNames, #A list of hosts we want to get the logon history from
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)][switch]$LoggedOnUsers #Will return the users currently logged into the provided hosts
    )

    Write-Output "Function Beginning" 

    $hostlist = [System.Collections.ArrayList]@() | Out-Null
    
    if($LoggedOnUsers){
       
        #Adding all the computers that were passed in into our arraylist
        $hostlist += $ComputerNames

        #Instead of making a single object we are going to make an array of objects
        $loginObj =  @() 

        #Iterating through our list
        foreach($computer in $hostlist){
            
            #We create a custom object so that 
            $tempObj = New-Object PSObject
            
            #Since some of the computers can be terminal servers, there can be more than 1 user logged in     
            $users = @()

            #We are just checking how many users currently have explorer.exe active which gives an accurate assement of who is active on the computer
            Get-WmiObject -Class Win32_Process -Filter "name='explorer.exe'" -ComputerName $computer | ForEach-Object {
                $allusers = $_.GetOwner()
                $users += $allusers | Select-Object -ExpandProperty User
            }

            #Each object in our array of objects will have 2 properties, hostname and users

            #Hostname is just the name of the computer we are currently checking
            Add-Member -InputObject $tempObj -MemberType NoteProperty -Name Hostname -Value $computer 

            #Users is the just a list of all the users currently logged into said computer
            Add-Member -InputObject $tempObj -MemberType NoteProperty -Name Users -Value $($users -join ",")

            #Lastly we add the object to our array
            $loginObj += $tempObj
        }

        $loginObj | Format-List

    }



}

#Get-Hosts | Get-HostUserActivity -LoggedOnUsers -ComputerNames $_
#Get-Hosts |% { Get-HostUserActivity -LoggedOnUsers -ComputerNames $_ }

I have 2 simply functions, 1 that gets a list of hosts and 1 that tells me which users are logged into those machines.  If I runGet-Hosts, I will get 3 computers (expected). However, if I run

Get-Hosts | Get-HostUserActivity -LoggedOnUsers -ComputerNames $_

I get the following output

PS C:\windows\system32> .\pipeline_simplified.ps1
Get-HostUserActivity : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the 
input and its properties do not match any of the parameters that take pipeline input.
At .\pipeline_simplified.ps1:77 char:13+ Get-Hosts | Get-HostUserActivity -LoggedOnUsers -ComputerNames $_+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (augmentarium00:PSObject) [Get-HostUserActivity], ParameterBindingException+ FullyQualifiedErrorId : InputObjectNotBound,Get-HostUserActivity
Get-HostUserActivity : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the 
input and its properties do not match any of the parameters that take pipeline input.
At .\pipeline_simplified.ps1:77 char:13+ Get-Hosts | Get-HostUserActivity -LoggedOnUsers -ComputerNames $_+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (AUGMENTARIUM01:PSObject) [Get-HostUserActivity], ParameterBindingException+ FullyQualifiedErrorId : InputObjectNotBound,Get-HostUserActivity
Get-HostUserActivity : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the 
input and its properties do not match any of the parameters that take pipeline input.
At .\pipeline_simplified.ps1:77 char:13+ Get-Hosts | Get-HostUserActivity -LoggedOnUsers -ComputerNames $_+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (GRID:PSObject) [Get-HostUserActivity], ParameterBindingException+ FullyQualifiedErrorId : InputObjectNotBound,Get-HostUserActivity
Function Beginning

Now, if I run the 2nd test

Get-Hosts |% { Get-HostUserActivity -LoggedOnUsers -ComputerNames $_ }

I will get output but the function will be run 3 times.

PS C:\windows\system32> .\pipeline_simplified.ps1
Function Beginning


Hostname : computer1
Users    : user1



Function Beginning


Hostname : computer2
Users    : user1,user2



Function Beginning


Hostname : computer3
Users    : user3

I have been doing a lot of reading into Powershell's pipeline but I can not seem to figure out what it is I am doing wrong.  My goal is to be able to generate a list of hosts usingGet-Hosts and then pass that list into Get-HostUserActivityand get something like the following output (or if there is a better looking way to gather this information then ill do that this is just the way I have found that works best)

PS C:\windows\system32> .\pipeline_simplified.ps1

Hostname : computer1
Users    : user1

Hostname : computer2
Users : user1,user2 Hostname : computer3 Users : user3

Viewing all 21975 articles
Browse latest View live


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